       
     
          
      
                               huggingface   {"info": {"features": {"commit": {"dtype": "string", "_type": "Value"}, "subject": {"dtype": "string", "_type": "Value"}, "message": {"dtype": "string", "_type": "Value"}, "repos": {"dtype": "string", "_type": "Value"}, "file_path": {"dtype": "string", "_type": "Value"}, "license": {"dtype": "string", "_type": "Value"}, "unix_time": {"dtype": "int64", "_type": "Value"}, "new_contents": {"dtype": "string", "_type": "Value"}, "old_contents": {"dtype": "string", "_type": "Value"}}}}    	     `  4          l   8                         old_contents                       new_contents         $          	   unix_time             @   4                  license $\               	   file_path   P                  repos   x                  message                   subject                               commit                              w}       
     
                                                         x<      B              B            H      {6                                (      C      @              @            P      x      F             F           L     k      hg             hg           xm     3
      w             w           ȃ             ȃ           ؉     >     C@             C@           I@     .=         	                                                                                                                                     (   P   x              @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p        	  8	  `	  	  	  	   
  (
  P
  x
  
  
  
    @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p          8  `           (  P  x          @  h           0   X                !  H!  p!  !  !  !  "  8"  `"  "  "  "   #  (#  P#  x#  #  #  #  $  @$  h$  $  $  $  %  0%  X%  %  %  %  %   &  H&  p&  &  &  &  '  8'  `'  '  '  '   (  ((  P(  x(  (  (  (  )  @)  h)  )  )  )  *  0*  X*  *  *  *  *   +  H+  p+  +  +  +  ,  8,  `,  ,  ,  ,   -  (-  P-  x-  -  -  -  .  @.  h.  .  .  .  /  0/  X/  /  /  /  /   0  H0  p0  0  0  0  1  81  `1  1  1  1   2  (2  P2  x2  2  2  2  3  @3  h3  3  3  3  4  04  X4  4  4  4  4   5  H5  p5  5  5  5  6  86  `6  6  6  6   7  (7  P7  x7  7  7  7  8  @8  h8  8  8  8  9  09  X9  9  9  9  9   :  H:  p:  :  :  :  ;  8;  `;  ;  ;  ;   <  (<  P<  x<  ccb4867d458b6608c2d88d97c10aee8fc33eb825435c833899904499fed321b49967b2b78d7e34ec7dae67a07cc016663318624841fd91faa160517723e23dd147d498e42c281703380e2d7e2809ebd8259fd834f28904fc9aaa4d6a8aef5b045283a9ad79a92cbf166ae548e6ce62e3efbe5e2be1d02ecb229d0527c48722a0f6423570ecb75cd73e5174be5949f53956f66ba861d4fa929be594893e8d26436ceb7c3be63517d30359b8cc44b570ca0ac8c76397e89e99cd6d33e3359aaa4c98c3503da4d84f84dbb84d1f48803abce9d66f23fb3f944819a3b87c0cbab3e85793065ccb39f4a2e7d58aeb8b2a773d62bf3c0073525ebb45ea26d5b06216c28c45929e04e6b25ba794ea6d1c78e16c95d6a5a829ff800ae51831c38a97c40bb80bd8caad28a4f382f32da62bcdad09cecbb65b588a4482591dcfa01cf937a2925dde24e4f7943243d8bac7aba109c8d41e1385b8529b3ce7ad1f86d997ddd0c5c9494e0c04c66f1a127d534d6f5d17bd791746bdd901d9e0c983ad189f0bd4ac8ed1f3bcaa80ae141906ab04f82cb78d4a0ab15ce53b655997c082cc89480a885e6f71ea43c548ae2b508b9344d01ed5e8d00a663859bc5cb32da3a7475bd04dde186958d1fc9113aa6669fccf4dba0f9b61d3689ebd6377062607cf75258d37a669f73d7779dbd9247c838dc65deecef908383de7339d8ec37b8a517b674e3ccadc816744a67f842a6c7033df9c30c969cfd41715941839849d50fe68687ca36ee2e65450081cf02bfffd024ff047d893979d23927645fd4755dd0bfca5c761b2cdfff9af863c7e30a558073625838b6166bf78bdf78e8814a38a9bc88d733fd0ec2c747062ed40209262c115032c03130e231af554832fd332a1bb97a54c8dd3494db402539cf5582ed237a2bba98554745e62130e5eaaed098ba2b821bb055272e761387fee326d7e46a32d460c77ff4dbb13e6b3dd2c3f80a9365dcf6538b5651d5678918d732b48273d349b33be442ff24a6c73fe83a137c4b10752fc367e7614a9746b95009835c39876a613133f8df25aec9e94085340f6267a692f55a68f3c25186f3c2f8784d28bc60fa0ccb5aaac1d09a7ee39c9e6dc42a79d0abc8e4e4bb6651b8bcbc3c055b3ca41e105cbbbc376d1f03ebe5e98ea8a884686e919414aa45097bcfdb31d68166a409a50b624efeb031b119f91195cf087ec88a853007acc30ba5047782e6dbd077778837a588bc036e26a2c44631a1e4fe69c78e99850a9a7606ad83b70117716965b89df5bff20974718efe900e6ac8953ff7fa743fc49bdd317927ba83054bb8e6dd296b51682070e5eb4291586949596bd5fdfeb9c5dbdf01464341657045bfa0ee0143ca3271713a89bb14c4f762737da8d8ad91be195c39b943264392d74cc54a12fb5c3d749237eabbbbfbd7eca35312febfa5fda12a7626823b18358c702de4ca8edb55052803b7d8a23a81aca2230d813cf6cb39ecafb5ad0466331ffcf4d3f6def76858318bd95b60f9104cd541fb1891f0abf3c91438a7d34755308a8aa38973009530b9073e13c1f9eca2ba449ca69dd41954ef97331b81a032a524e79b91b5268395cdef63cc1b449abe7d2baa78033b665a5fe0ef103bf42fa5e56852d9cfb1153f0c3ceba36a46bac3b99e7630475028b9e1119645817068b1a8b43862bb99a3056ca5427bc9cd4a8865c3d52140469af23db1d5c7b3c3d271ac80e9b82c809ef17114eb7e068559de7091627dfec31ab5dd9c31035f27948be5816724b8e951dd98d033f82e8d54eb029009a1c1661eb0b4f5bc4f902bde41d4b52eb452948d3a1ccb872380a05a0298404cfc65981d45c6af30fff7700257a958a2f6c291cec40d2a542e8d40b1ae917eb6446855fb40d0e9ddba20c05db564d13bc338e6d4937663ebb7ce16ebb01537ecd298f5b8c78b5712e9b4265b9ce30b2fc741544b3fee83ddab8a0267eb6f0eceb2b86d79751c55dae49c40b91c0705d323cb1345f94cede302fb84e11e1a82ffd6223e5d6d220c5ea506688bd3761d8b07853b6010d47f3f34f0357ca2a783ad7f63479502344c680b6199f8ec1e1b2c2719848d4f3ce000b68529f5757fd587e1d53f202aebc8eccf4139fbf8922e4e93f5d0ffd44dd89894f49b0f868f943bc21258a16b9d65643ccd75b57b7526f80f93fa9203240abc444ea8429aa673e0c63e62a739178d8fdab70bef84fd2632c2928765dc72b99795946d3cdbb049dc4b35afddad395708ccdf4bce4e9a713ced5346f4d11667ebd7b1a7ab6f6a4cf29b17a4d9e4c825f6258a1a941c635281a9485da346ec23bb23962a72b9a679ba80d92e2439932fb8a939d4a08d0ccf573b779f41bb21d79c04624182f295aaba7894dd5234719f59389d2a6bf2df3a8fd5789a11845d54f4d8d99c5f93553dd534953cbf11ab06602c88953c7ac5baab3cccfde466e85083c59360e046baa875ec35291165c39803a1065f935140d3f81fb181ae4155e510eb3588858c669b9ebd9365b80f34f722a4a648c0ac99921d27b73f2d61785380eeefff9fca82cfef1fd7185a06b5698fa2fcc1d953329596b917eeedc841d97c3231532eb1958f0f8ec9a6b7bdcf9e2470def0901634afeb20e714dd32fbc1ed1af2563544e91c5ea1c3eeb794185bcbd93e3647e5847dd0d27d28fb0dd4524dd3c8e4757099bf177e88e384bb08fce5025ca43ab38d6e8d12c0f67cb966f12aea87af987f7c9138cada8a41d6022a92d89f3e940312a28eab3332d8b2a3e1d92190cb97f8f720c9764b7177c1ad02f6406545b875a43a14a1f9de3b773b3491a6f5dde2fb9fb7c973c3c0ad7a27f076a3d335e647145cab1d1c1c252ed5db68dd33a4ca5349db4b433450b5dc1f07bf4436bcf809b3ff9b7fa188d1fcf4741e21411f1dc08d6d7ee6b858a384c0c951af3810c39bbc0b1dc416b12f3696504eceacb2b3b51b2f2e8f3f5d079e4e0895494114143d4a6e83fc29e920bbe6cc3677cfa5d54b41de753ad29d6ac49332f26cebef98d976b1532802151ecad0313033ee733a2446d9f4781bbbbe185d6901580e2aed5b53dbd6d76457b26c93e0fbebe333e103fb6d1e20856eef8d13a885cffd9929a5a093e3761c14e876596f764e8e4854689438a95f6d85c60e2d54fa9aaec6c67e8ec08ace4747dc53af27656c17af807f307098014af4b48369e02593e354e40d749c63ebd6a879e5d714c72437bbc71c951c1ab05d75e50c912571e92a3702b418ba67ebdda2fc5172e5b8dabe434a28cb0a4c1d1bcbfe81e76e3b55baa50505f388a359dbda6a922baa256a1507529d8d7fc03368bf2e58d3f02523b8f7da1fbbe71b856c7c4085195ce20c7323740612a5486f0c4afcf10adce79894b156a5fa2d291bfa829d77fa64d9e6b2129f425f2534ba534ee4a4a1e220763d13481227679e39aa6372e2f5b36cb779cdbdd1cacdbf9c5f7591a2ab8e2061a7770d0ce91d3ecdcf4ce13d6ce37b60d255c723f98ec1ee8c10e87a05fadd1a7b6c71cfb0c9c3440d5e505a057c50e7f292629a0465e3bfe4f50f18f2f750068c007c9ed593b60c290657ff52686ad8ea0df9e86c297958e2e303ecbba90870c96ee5b3582d889e8a075241e9ad05ce9bf8506a36534982495b5aeabb5f1fc73c76cfcb0a5a094b777da90eed8a1fc540dc28ea32ae762e5ec4d9150c0aadcde2d799778af59f98cc4f77544fa7ec9af21c9feb1b6d15a1dcbd056c1becdcdfbffa6e4671b8f3f82edabe62983289dba79d19b6e8788fae3455d8d52251a6f355de4fb5bcc7c182c803fed74738083e51e22f7fcb25a431b87b65da844c86d898c96fc8fa9566c6d7f08fecd75803ac20088f896516928a6fd33810203408179b713ab55015630a943583b6f3e5feeff8412a418d49f118f31048115c022bd8a4257265eef800777af2f543f86238e1655b670e9fdab3642704901714d7a801d338e5d71aa4bdfa6c4ac56939039a3b52c36ba0b26bd04f11a81536d040a4db43840e58ebe6a068ea1d97455e19891bea974db8cf210b6137303a0cf50d9c79899b0e0bc71693341164c5d7e63a147d418d6be03671990d970e09712fa9187017bb73c305b398a4efc53e2ccbfa2bc6ee387c5a4d1fd11b7260b7485f07deb344ef2afa77675b4d7420f499ffafeea7fb0011fb0f5fc0584ccb9e4e85d6524df9175b575f5eb89388b6010180d14a0492b7b0cb6b7d283cefb748ca4e93a0fe80610c852961f0d87070347f4fc44693ac9edc498ab465d69482a412b5cd1a35543f9a2d56dd7f487aace58254f1817c419a6c6f0039cd525462f94289cc0f8e4c8b9db81d41ab47eef409fc4a7850cd93d629ed6d485caae2b653043c5eb8c0618c5ab03ad56cb345839c83faf0fb30ba66e5906fd744db7cd146a22265371f6aeb726cd231a465d269f944b17bd7520f3c308b2ccad7dbc5e2bb180427f9f5d5533a77a2036e9100ffdd442e3476d3b7a7574bd6549e65f478e0086a9eaef13276dcc41715b1d49b06c77845f135eb61b0bbde25d8f0bb61e32d40020a344545885689363dc02f94af0d154072145ed88d0cdb3163ecc51ae60ea0de3accfc07e6bbefdeed2667c9972842d465c9d0faebbc8e7aefd1f359b68f0263802d853f3615301639734a48a8a3e69b55d0688d16aa8c150f32d9c9f72acdc3a15cea0ef81a65b4ed866cd28ae2e827bcd09e4a9a818fc3bc69c03797ceb91b6d591e51aec8c0bb86f83f0ae1df710eeda354eda28ff3d5bf2df08e951756a414a82704a505cb7ab4a3e04940afba080edaca0427bd1e806da730a8ede602c1cd99033e2b8bfd734c77af2b868648a1fed824ab7b6eb7bfee035f1c75f8924e876fa0872929ba8dd36f13996c1c058fb8f87a30ef40f05a754e8bab373dace5ef2e29efe16ceff53206d6c82833bb901a279507cd3e598a4751c8879d171f778c887bd5fbe4a02cb5989b710c18b2390c2f94817f0076c1167285c043fbbca88158c5e1f6c21b584ce3e084855dad90389ddf8176b4c25f1a7c43b01707e0ee345fd7891c6c788dfb46772cdb304740ff0c8adaf7fd23643e61e75981149b99b5bbb73bfab549d6f43e7e49789aa02931437689e956d90dbc39acc6c37f6ebaab8f2fadf00d914bb1194e89e192f148fa9e96922d46ba14ce5bcb0a216446c10bf791ae59cfe40f0d27a9e82590a8a6c392fd2942c7250f34e090582731553ebe8ac044be8730ef29274b7afe783169ecea129e10b8dd447910d3874f368b458214c243f12f721baa9732696a33261afdd22d413b46c68aa4f00b83b7508ab1e5bab776878e75b2f84c8b2f3d95524dc0793f760e54b89472b9652e38510a12ab547d7f49f897994f92a92510fcbc0c5666f99a1cbf8e819a4f0c894353fe8b94a81e9c000f8c53ba1c44e10e0f1a2b37451242033b4a98054362cd4a7057fb39492a2e074b3bd5728ef017186853bc2252abd0b1a353b237631b1eecfdc631e6f8c138ccb4391660975e38257847f5f0646e94438dff3da4cbdf2f7216f87630171e840e44fd37509f5fb65089ad5ed98166d03c6f419d1b33033f6879e096f435b0814acedd633657bfda37575a07fe7d2141c59c4bc7cf50b06b5027d586517b403cc9ce677794ef382621ac870ef4919648f02c0bd249000ccc72da6ff752169c76c0985ff7aa35e17bb11e9f6c2277c4d3444b4682b4024657f68c82f5fd5e3e2ddd8dbfd4a8eddce32d8c33d977f7b4aa978087e0fea4e2b013b6448b85ec63f5edb094ff287e3a7b65342ae58bfa177a04959d418a7696218d85b3526c758cd4414183169d4c56cf9bf83a348bfc128a31599184c7e926e89ecceb170a736fd760336ed274aeaee2e8e4fe8ae6baea919b21c87ca5ddb9676d4cf1316e9ce341961cbe41d4c7fd18889c2dc772e67a0957b4bacb4fbafe3b6b56ec98637a193f6e6ad2d01057a1169fcdde5413953de6ccf850cba91f85546bfafb4b33d913376ab87b22a335c5ab423ca6b762bcebe532aeec440f287356dbd4b349045880653d824769e51f2fcd832d61266e1dd346b7bbf8375b958158e7bd8981ca95b828cca6d84fd445af5d0ba00cad050779368131f9f7f15925e03eeb2a92af0386fc88eae542ec02f795fc24aa61d33d872e25e3f34facb71e96cdc47c1ddd345f4cbcb47cfb4cda87e56917bdb8708ed11c62204d88fa9c90aea44d5e4abdbc156c12ef30b299cb5cc37113951b080663b24ef93ae63b09aed266fc6c8bca35bf5d8dd4e7080424edb47e553373c0f17c2735610f094a453c801df4f076e434c8e14657942749789e80e6313eac138c4cf37fd9335cd238db41bcc7ed5dab3a07632822226c6b3c6b421245d31b41d432029d6a443f94f78c42a0de99683a0f48ff467bb2b9e0d3997ff41a7291604acb975ebe7799f235049bec9073217b155d59db6e2a3743d97972b70380fb99dc1fcdd98523dc7d3806b93f641880e79f45e237077e373dba396fe924365353955d6e734015973cdc496a217f15a503000f7c5052078a83fa5a072000d390e474842db4515587ac07d2756ed00a013b00310c4d1504de9f8d71a3aff20816a8d7e84fafdcb12b9509a02989140a0537d669b95ce66dcfde37c7e4c1fb6505faf62a7c940ac477dc1ab4ffd1fbe21b01d046be28d2119dcc9fb7919f348ec8fa5c4473b057cb93b953c292fb28fbabd397ac6fcf6e9d799657dade2dcd63b43a15e61f1fb20dfc1eae1047573d2c4c0a70ca689f52f5319789600e64bcc7ba4bee93e0d2beee1466507b8a6afc198c4e85b4ee15a8e65026dfdfd2c6fa1e33347c69afb933156d0eaae7503d9e5a413caeb1d57f34d655c058aae2e58dfcc9524b322d9b48399edc343e62720d0e37fd6b2cebfb5ccadddb0519eb7baf969c404e4f00cdd9b17f631b5512315fd119a01349a9f2a127f989bffd1cd66d71f0a9b7e6fec0348f48c85d1dc540b1d5a2a747c8465ac7b058a66599ab842ea6a4e4d7c00c623b54adbe9bccde65f0cbe5eeca96f0126d31a79909c65b966eea89ee5742ec6137a5d905ff640b4eb4c81e691081872d5f339d4fe95e790f3f7d5cbba0b56b08d33fef95bd85afc63934013dda5f11aa59a374cb24faabe28a8e93e52d7e70d8e59db7b8cd1e6b2efdfc384cfedc5576567a3e2c89d61ddbd8a8bfc7e2b8d634850bef14efa03c8c99ebe27bd8c9fd2ccc34a635920b1753cef7cc92918babe02b32a627c7685dc8bff290dab3e4ce94faf88be5a9f095dcb27451c7ad0a491e824e2187317ea916e7f7bfe8b8c96983243a2d91e22004cb3373bafd098f4f341614badd85886cd6b944323aaa3839ce7d2386b3f463f6ef1ced5f5bb6d8b82f89a3cc2bb5753eade31feac03c54b99e6709503b5b863df6e92e7ca34dc70c3b3ed1b1b34c9a15cc0b11a13615db049d44922eeeb0986e19cf6cdd3ef961ab2d7fcd8d45de0bfed3a740873a2d926ca5f8f7722d8a1cf305ba52d33b0cf014419bc99e6f1cc86b056815b588bd4f1f88e5d49a1ae0c84f147d6dafaa9335da5c8b034d43dc7ddc1cd1d4445f5c372f17022d5ab03253d3c7daefb41b91a7ac5431d87628a32fee0453a7d2a289dd5975bac678aff9e7752e4235e75d91ebd29d59d63ff1a32228e6059faf7f731776a8419314c77fd36fea69239336b30346d4a5b00a7f30da322fff8011b27c8467c44d4ca459db2ff6cc6c85b00415a96b07a662da0d20b8e341bc117315ff92cbaae6e2600833d762b0ae5c12010a893e82f1ebbb44fd01e3f1454ae7bbfe9987ab5e0b51bd6ebdb881d5555daa2380b0e71fff8089cfc0e9a4250c3df7342865e17aa833b294e1cf9dfbf19cf9536769f574458cbd7bd0aa8e39fc5b138b10e702f7b6f9511f508e70349ac3864d41e89031480a3b8182081523329cbad99d261c210abd2ba6962da09aa6d6bfecf27978f3db5358cd81986cb1bf2b1ad9d30d6be1be047fad56031e5a61ce8fdac5c09499b5da2078467953cf307170aa0bff041c442325c0d834fa61ad5db457c1a5c2803be71c6a5f9d54d5747098d27d4cc37bdfe12f57f9393bfcfe943979e4d9000954779bc3f1b7670518333b0d0f3eba06952f71d211736f8ecff58b3d27dd593280f98a30819bc93183bfde3adebf800efe4f049273b1da916dd409582714896c337f1520169345e9fdf348038438481d74a1bf2d360ef6a20847e210f2e3a3c00027ae152638098f22dfb19e421b98900336b211b5b49ca37e5f95602bff99d3e23ec40f286ccf66267b56d5d95b3d488b62c66e5af2c33d9c8f5d7b46850342af8589746b1ecacf43344c043e1d868d654455f72d4cd8bbc67a3f0f66dca3c32abb0d02e8c682072590ee1fb2f67c8b1cf868398f9c83b352f2b4096330a82e1e17d2574afed6594fa06a20896d215c612194079d864ac79168bbc68181cc6362cb39546d8d1df13e9825f4ef3b468ca6903bbae52711bf85d8593ab387da66a5bc43f1e85776b86f14c75e5cf68faef778145d599010f51ecef8bfed4ec508794e14e8da9e344e42fad6f6f0c5d5f0ab1a0d6d732846d40b62524eee03f54f7bfaf1db5ea92fd37fd278244fb1b0e901a17a806f9b136730ed96bef53893835711f6a191b3811b298d8b25b95dca82334c7ad0767a09bc3a9402581fc469e33da35fa33874cb9d5e11cbf4b52efe176c3eb07544bcb9bba770868f60b21caf987703dd338ed9f354db55a405d8d95103e48f079d26f56f0b5bf84c086fe9132259724215abfe704c4b943ed2999b7f493c08fa64c1624e008bb59a52ee6dd4cc0707001d4e3478bf27cabe113cbf8b9e11d8639198d3ede60ad7b9f380db05f2d9702357d68c1cf544c06bfcfc9c30e998465866c44b8f8d10ed8bae0d0f8c4e278dbef63dbd714ce3de903c783a5624e6549c1ace69421e513ae371837e2c95be91cba4492c4aab0b1a9e504c45c9962b2d1330655e63270552a7c3abd02ff756ed66b30c89869adbdc62d22d1f9c4b56627f6ddc7260c37406a9b646233dbc2c015853b9ba59c558dd35854fd9a2a3bff0c43078df224cf32864dbb818fc147e21b95956148108f9b8a9e13b8447e5c0144cfdbc4ee32882585f4198c5ac40d135678a7645fb4030ab09cb0e2d36204b8c0d5a0be1fd6c0fe06aeab55c1049a631f5a5c2134d6ed24c64aea2ce49d1b3e808a8af1d7c2828db6ae3ecdacdad091302f5289e65ea53ee36715a40a2d1a47da793bf328babb544eb58746e62243c62632d1367bcbf1319f33583ce8c704171822537c0ea7ebdff427b9c72a71ec2c2e237f42af7d347016c28da49111e77d7516a0583ec012cf77980fa49c1bd7639ce8b61cc578f6a31152da2b80b525c5044da949a1822c1a56fcc1dcf782df5d5a1b94a867904e3dc1eff008197dc2bf9abaa973ab61c5e6987eebf0f54142d5f3de2ddf5b9a8cd36b0ff525d5ef11e0ade0e28193fad368598450d539b812b7ce72606826692bd1f14ec46e52120edd5af666ee72625e8b1324d7766e5a5b9dd84b9cbf2193af0bc7da144edf757d53808acb641b272f98470dada3f5084da9971a1b0b3c001b74e7572de55dc47533656e5d2ae72d3cf438119289c583a8db26835ef5705f8edf8b323f3f9ef5955111de702976cfa4c3d811f0ddae833523cfef4d17dc61b65562e38d38347cc4f241bbedeb0e0e9c1124b780513f08ae71be2af4881c31a790576df447782deffccd5a3f55b3a0a98876358f79d5d3708a759a5a6350bd71bcca141d0779c582ceed067ccbaa80fbf5fd722e6d5054f76a0d8f5910b01299f19d86027f2718169d19282ee1ecf9e557918a0b8b62e892c2d1a9ffe84b011819f47063adabcccf4e7fd190de0b8bb0edfd52b2370945a0531c16b9f8e03aa7642f0e83ae9616ec57fab13746c15351bacf652ef0a7aa53e10fe58869c0998822ca1654c5ed352a2b29c4562df00f6b4d40a2447ab5815e96ec49f3e13a1b6c2e8df4662515a16ae9ac0c0eb601fd41b91a8c6b64b8d63282c7efc20e07d4518add0053d7b7de2037a535394a8b49ab042e402dc1c2763dd89f99463d4b2e2105e599917d6d5070444d4325c14dce2f12c40d7a50d2bea968b336120042dcef9a9b1665d234ba09d9c97ba9b2028f56568ddc09646f020561afa1f38c2660ed5930231a1ce5f74d4a13cc3867a283dc5dfb9f54253fe2d21cd2e9ede88c5113e0eb9a3853c8236f07e840dcc43147f5f43457a2f87f6f91e27117c1941bceee96e15da0e2bdf1aba6f2f7a522dcab5911af2a343d0cd362c295954a2db4e9f1a35ded6e9a460310f627c1be2acb4449adbb5b569056964dcc45b5be04e4921f07f5ad5436ffb1f0a7a3f5d5e1cab0894301e01bb395f048f652f5d9fc9da7cb78ff09e147cb53357574db16cb2dfd962a1dedc156640ad13024bf25145ff696952c2a852f626b6761fe930b6fb84d6e581ea13e528fde5ca036c7f97d57aa6214cb586effa12de93d1f555ddd80828cefefbc6c9b61d19278b3867791a9fa511116fdc0ef8ad41d261b46f04f9fe5e240736cb03d9ce71bf349d0e978d627ef69d1dea71894d668420b242c8258dea76e6bbec3fb4bb2f6491d1964b3b293345efbe5caecf2a2a14c323b5d9dd75e01e4ca62c78dcbebd85c60226238692b1966ee5d67044d747fd34bb4ecc75c36bc7f5be0e1ece9b62bc770287a70ed1948058bfe7e7cbc1bce63a9ee441de99c6e99d9746ef3ddad09172d9421d93f76884cab4c20bb2f741149196107ffe54f92e0ca51b90a537862ed3c196eacb0191d3588bebb003b37609ff16d3398b72414aa517ad5d0e8f4f77f81da57913dcd7ec024bb08c1cdbd64dc8cc17e3c0cde8151c5110a0594       c                      7  ]  ~        D  O  r              2  _  |          1  V  c  x          5  ^  v        5  M            -  E  v               H        	  1	  >	  k	  	  	  	  $
  
  
  
  !  B  ^            (  >  ^             G  `                -  D  X  m                    <  W  j          )  K  v            -  E  ]  u        8  \  s          $  <  }          T  o          +  ?  X  r          2  G  [  o            !  ;  U  s        <  R  y        /  S                +  7  Q                /  C  e            ;  q            <  P          g          $  C  P          2   k               !  +!  7!  H!  b!  t!  !  !  !  !  !  !  "  5"  I"  ^"  l"  "  "  "  "  "  #  !#  C#  O#  \#  #  #  $  9$  d$  $  $  $  %  8%  m%  %  %  %  %  '&  W&  &  &  &  '  ]'  '  '  '  '  E(  `(  (  (  (  (  #)  >)  l)  )  )  *  2*  k*  *  *  *  +  D+  q+  +  +  +  +  :,  M,  g,  ,  ,  ,   -  X-  -  -  -  -  -  .  %.  B.  .  .  r/  20  0  %1  31  N1  [1  1  1  1  1  2  12  B2  d2  2  2  2  2  3  G3  `3  3  3  3  3  4  4  04  F4  [4  e4  4  4  4  4  4  4  5  -5  c5  u5  5  5  5  6  ;6  O6  {6  Fixed problem with aloja_cli.rFIX: issues #1042 and #1044 (Compiler errors: undefined symbol ts___)added spacing updates to the file, no change to the scriptFixed lines and pointsAdd transparent areaAdd colored plot pointsAdd plot lineAdd some plot parametersUse with blockallow stageRunners in munge proceduresexpanded example with multipanel testsExperimental: implement allPanelsBad form to put assignments before functionsadd placeholder for an allPanels switch, update commentsrename vars to avoid looking (falsely) methodlikeassign from current panel instead of full extentsindentationloop over all panels mirroring axeslogical vectors to find target edgesadd match.axes functionAdded documentation.move functions to topreworked example with multiple plotswhitespaceshorter ticks, thickness relative to pointsizemake sizes relative to configurable base_sizemore space around axis titlesBug fix: used wrong objectspecify aspect ratioFix trim error with factor daterename ggplot themeFEAT: added ability for the compiler to extract typeset definitions from scalars.red.bring in compliance with s3mpi changeUpdate test.rUpdate src_teradata.rSelect only cell lines of current cancer for achilles plotStrange test IIStrange testorder before select in dtm.wordcloudTESTS: added a compiling file message to Red/tests/build-arm-tests.rTESTS: minor corrections to Red/run-all.rr files for week 1 addedTESTS: Fix to allow for multiple runs of CALL/WAITTESTS: Clarify CALL-SHOW? to enable /SHOW if definedTESTS: Create a switch for running CALL with /SHOW or /WAITdo not use tail in this methoddo not use tail for thisfix control matrix extraction bug from current minfi versionchanged suff statsUI defaultsFinished optimizing project file sizeremove defaults from UI for geom and stat typeCreated copy of data.table for modifying field namesShrunk project file sizeInformative errors when species names don't matchAdd informative error when matrix size is diffUse names(input)Minor update to updateInputtest thyroidGłupi błąd w pobierz_dane_szkol().Add pretty-printing of tablesAdd partial test results to mantel.r outputreverted implementation of "pause refreshing" feature to using last_plot since validations are not shown when they are passed to reactiveValues.fixed exampleupdated boxplot codeTESTS: minor fix to run-all.r script.Fix typo in commentAdd todo noteRemove annoying warning resulting from `melt`Attempt to remove conflict warnings when attachingEnable cachingTESTS: fix a uninitialized word in run-all.r.fixed bug, normalization now equivalent to minfi outside chromosomes X and Ybackground correction, dye bias correction and control matrix now identical to funnorm in minficonverted the implementation of "pause refresh" feature to using reactiveValues.re-use helper files from production modelx and y chromosomes handled correctlyUsed textareaInput for plot titletidied up code, same outputssummarize: move error checking to b$matchminor limit fixesPlot loss with non-logarithmic y axis scale.FEAT: minor code reduction.Improve prediction figureFix prediction plot, bugs in make-regress-figs.rFix colours in boxplotadded search for formatting treeMinor layout change on Customize tabAdd census data explorationAdd smoothing, peak and plummetImprove default importFIX: issue #1031 (Red/System spaces don't seem to be printing from within Red)Document semantics of sys module betterExports add_pccoord againsplitting add_pcoa and coordpcoaAdd script name to sys moduleadded examplescorrected spellingexpand grid layout properlyexport Qreg vardo not move split to array, leave commentlabel vars properly in layoutadd result to layout dfremove result naminglimit to one registryreworked confidence plotsRearange codeR/prepare_data.rnote on ape addedape modification doc addedcode cleanupInstall slidifyfix duplicated importsAdd more geo explorations.Hadleyfy the content of the script.fix name handling in melt()adde eigen pca testmodified to properly handle chrX and chrY for males and femalesgit-annex automatic syncDelete commented codeadd melt() function for arrays/dfsvegan::null model instead of vegan::commsimulatorTESTS: removed debugging leftover.TESTS: added support for system/script/argsm >> n in pca bench for nowAdd a few more plots, TODOs, and formattingclarity in cov benchmark + validity checkdebug import_pcoa_data.rdebug import_pcoa_data.rdebug import_pcoa_data.rdebug import_pcoa_data.rdebug import_pcoa_data.rdebuf import_pcoa_data.rDon’t export namespaceTESTS: changes to red/run-all.r in preparation of a --fast optionMake summaries and use cpipack-assets - improved check when cmdReplace can be used and added new walk typeAllow explicitly setting script pathOverview of the datasetInstall rChart by defaultDelete ui for changing import text file settingsAdd parallel eval. and progress bar capabilitiesLoad helper libraries by defaultchange file upload limitallow environment accessChange dates so that they are consistent with used subset of dataPobieranie danych o "artystyczności" szkół.Add index for plot.all.topics and some optimizationsAdd option to supply terms/freqs to wordcloudmake freqs optionalFIX: issue #995 (Shared library can't work on ARM-hf)Add try/catch to amcat.hitsrename local variableDelega all'option width l'ampiezza del terminaleReading now works, at least in simple cases.small but relevant changesFIX: added missing new dependency in ARM backend.PACo method includedD argument for paco_linksfull complement of methodsvegan::eigenvals added to coordpcoaape::pcoa function altered to allow generate non-zero eigenvalueremove margin, add methodHack shiny.error option to skip validation errorsMore functionality.bugs, bugs everywhereupdated plots scriptupdated plots scripts3 adapter should able to write arbitrary objectsMore functionality added.heatmap sorted according to result table in page1.rdelete dependency on plotlyBug fixadded null argumentadded code for paper plotsadded code for paper plotsAdded the load of the CSV fileFurther development - still not functional.detailed aberration plot function updated with new value typeseparate plot for errorsFEAT: cleaner handling of writing errors from the linker on locked files.Preparando country-visTESTS: updated error messages in tests.FIX: make Red compiler not emit routines definitions inline.TESTS: run-all.r script update to reflect changed name for unicode test file.Updated aloja_cli.rUpdate ggplot2_formatter.rFixed that combined bug here as wellSimplified comp1view1Plot after fixing server.rCode cleanupAdded argument assertionsUpdate ggplot2_formatter.rUpdate ggplot2_formatter.rFixed a grammatical mistakeremoved a debugging messageuse director for colouriseadded customUpdate ggplot2_formatter.rtemporary warning on stageRunners with zero stagescalculate pc variances..more descriptive commentupdate commentfix readLongfix readLongactual names are being compareddo not allow environment mixing when coalescing runnersfix stage comparisonremove my superfluous library callcs-lunch presentation random dataengineupdate read-binary-fixes.rNeed director object for scoping environmentcorrect parent scoping on resource injectionsFixed bugupdated to add in running the run_neatline functionadded use of function eudist to get earth sun distanceAdd documentation to module "sys"Minor changesDodana še možnost nastavitve pisav v glavni program.Fix a build failure caused by mergeFix a build failure caused by mergechanged default value for cancersrestructuring graphsUse as.environment for compatibility with objectdiffwhitespacespeed up execution of test_basic.radded option to composite all indices in a loop and providing coorinates for a usearea fileusing mixel2 instead of mixel function and added option to composite all indices with a loopIncluded zoomins for each chradjusted differential expression analysis codeupdated differential expression analysis codeFixed bug in getScorePlotfixed small bug on R code with R version 3.0re-enabled parallel computationformat changeadded the ability to select multiple directories when compositing images.a change was made to the values used in USGS masks. the code now works with both old and new versions of USGS masksizbris tabelepopravek (barve na grafu)added optional --user argument to IRkernel::installspec()odkomentirana 3. fazadodan uvoz nove razpredelnice za koordinate državdodan zemljevidFEAT: improved CATCH statement's error checking and reporting.adaption for ForeCA_0.2.0Remove panel border-2nd predict-2nd predict callinstall necessary packagessimple model againno splittingmore colon issuesfixed better scalefixed hopefullycoef data.frameExtends README in GeneratePlots.rParameterize the paths in GeneratePlots.rtypo corrected in page3.r in plot functionAdded enhancer stuffadded all RNA 0 catchAdded RNA infoRevert "Added RNA column"Added RNA columnadded name based subsetupdated modelRNA; everything is Gaussian right nowInverted colors for TS heatmapuse of on.exit(, add=TRUE)RingSettingprovide resource_name in resourcestesting pushAdd R shebangMaking sure stat_ellipse works correctly when imported into a clean sessioninitial commiting on tracked environment changesrevert environment injection using on.exitrectangle-pack - having a line for sort-method hardcodedpack-assets.r updated to it's current stateFEAT: minor code size reduction.finalize changeContains all functions necessary for page 1FIX: reverting the changes for handling console recompilation to fix the new issues on Mac/Linux.Adding more summary plotsrefactor s3 and data adapter to s3 and s3data adapterMelt data to avoid repeated lines of code.FIX: file path error when precompilng console.fix a bug and make it workAdd error bars to wdays.move changes inside tundraContainer to feel safeExperimental: Adding for cache statistics (WIP).change default adapter behavior to add data when export data flag is setFIX: system/options/boot inconsistency workaround.REL: 0.5.0 objects supportRemove commented portion.FIX: issue #893 (latest release 0.4.3 (commit 1ddcdc66e8) pre-compiles console everytime)Experimental: Adding for cache statistics (WIP).set up test code to add writingfix col.margin parameterAdd -t/--title option to priv/summary.radd caption from attr() instead of hardcoded; fix drop of attr when converting object-typeUpdating to latest results.Turn query errors into warningsadding a figure that didn't get pushed earlierImproving boxplot.Making it fully generic - forgot one more variableFirst version of boxplots from our benchmark data.align colnames to the rightadd code for fig size, but leave commented outAdded hard-coded values for another shared level file. Fixed length value of raw path data.Updating to latest results.Nome do item 11 do menu consertado.Apagando com o clear(), agora ta perfeito kkkAgora apagando os objetos no inicio de cada item do menu.Movido o grafico de linhas para o menuAgora com o plot fodao! *consertando erro de escrita*Agora com o plot fodao!FEAT: added support for internal Red directive #build-date.Ne izpišemo pobrisanih datotek, če jih ni.Dodana še možnost brisanja brez vprašanja.Ne smemo bit vedno tihi:)clearpdf.r vključen v glavni program.Dodana možnost tihega delovanja.Still trying to fix the Travis build issueAdded ... to plotCUB so model and a2 can be passed as argumentsfix table end errorfix line styling placementremoved some non-functioning kmeansrefactored topics over timedon't need to create .rdata file in step 7 of gapminder data cleaningfix small problem in step 4 of gapminder data cleaningfix small problem in 2nd step of gapminder data cleaningadd horizontal line styling to function (partial)clean up position index variablespass args to preprocessordocument args paramtidy and sort docadd comments to stopword codecreate stop word list from tablesfixed visible binding problemFEAT: #call directive now accepts an object's method invocation.Support recursive modules in help validity checkModified Idover.calc to logically work like the version in calculate_diffues_fraction.R. Existing version in Diffuse... seemed to have problems with if statements, logical order, and indexing.Modified Idover.calc to logically work like the version in calculate_diffues_fraction.R. Existing version in Diffuse... seemed to have problems with if statements, logical order, and indexing.Modified Idover.calc to logically work like the version in calculate_diffues_fraction.R. Existing version in Diffuse... seemed to have problems with if statements, logical order, and indexing.isOpen not working appropriately, use tryCatch hackadded analysisfile_extension expects '.r'nsef, not nsearray/summarize: omit empty mappingsFEAT: propagated runtime/environment file changes to the builder include script.debug norm v 5debug norm v 5do not allow global env when sourcing using RamdMerging remote changesedit the graphicsbind data.frame list to each otherbackwards compatibility with hookless containersset table_start_r and table_start_c as baseline coordsadded col margin optionadd 3th OR exampleadd function to print list of tabularsforce these so they can be referenced in hooksurejenostna spremenljivkaUpdated R data dump script with article states.popravek pri uvozusprememba urejenostne spremenljivkeodkomentiran uvoz s pomočjo xmldodala urejenostno spremenljivkobug fix for render v12bug fix for render v12bug fix for render v12bug fix for render v3Uvoz tabelAdded alignDepth plotting functions.respace serialize_xgb_object methodremove requirements of xgboostAccept file! to CALLAccept file! to CALLfix typefix identation spacingarray: fix mask, subset names[to merge with master] customize serialize/deserializeupdate render v11bupdate render v11bfix wrong envir when checking varswav-to-mp3 - using mp3loop utility to have better loops qualityChanged hardcoded values for asset idsmap_simple: fix when apply reduces dimensionsupdate some commentsFix problems with rename due to bug in dplyr            e                      A  h        4  f  r        G  ]            #  8  X  l        
  E  U  b          B  w        '  :  F  l        	  !
  2
  N
  [
  
  
  
  \  j          .  a  p      K          +  U  g            3  X  t        "  <  ]  {              )  >  T  n  |              	  K  g  {                $  O  y              e      S  x              3      @  n            H  c            D  ^              0  d            0  \          <  y      3  X          4   O   k            !  2!  K!  Z!  g!  t!  !  !  !  "  ,"  G"  t"  "  "  #  K#  m#  {#  #  #  #  $  1$  f$  q$  $  <%  %  %  &  k&  &  &  &  &  *'  '  '  '   (  (  I(  Y(  (  (  (  (  (  (  )  )  1)  D)  T)  d)  )  )  )  )  *  *  n*  *  *  *  *  +  +  3+  @+  N+  +  +  +  /,  [,  |,  ,  6-  -  -  -  .  B.  ].  v.  .  .  !/  T/  o/  /  /  0  40  M0  u0  0  0  1  ;1  N1  1  1  1  1  [2  w2  2  2  3  *3  `3  x3  3  3  4  )4  P4  r4  4  4  4  5  U5  q5  5  5  '6  Y6  {6  6  6  6  6  6  7  Y7  7  ^8  9  9  :  #:  >:  L:  q:  :  :  :  ;  (;  _;  9<  j<  <  <  <  <  "=  <=  l=  =  =  =  =  =  >  *>  @>  K>  @  A   A  5A  JA  dA  {A  A  A  A  A  B  YB  B  B  B  C  Fixed problem with aloja_cli.r
FIX: issues #1042 and #1044 (Compiler errors: undefined symbol ts___)
added spacing updates to the file, no change to the script
Fixed lines and points
Add transparent area
Add colored plot points
Add plot line
Add some plot parameters
Use with block
allow stageRunners in munge procedures
expanded example with multipanel tests
Experimental: implement allPanels

1. Maybe ought to be in match.axes instead of main loop.
2. allPanels=T behavior incorrect when axes of middle panels are null:
L and B axes not copied.
3. allPanels=F behavior incorrect when all panels have their own axes:
only panel edges at edge of figure get mirrored.
Bad form to put assignments before functions
add placeholder for an allPanels switch, update comments
rename vars to avoid looking (falsely) methodlike
assign from current panel instead of full extents
indentation
loop over all panels mirroring axes
logical vectors to find target edges
add match.axes function
Added documentation.

Changed S3 objects to fit generic


Former-commit-id: 13a04c0613e04334fef884b0957e67c90021d43bmove functions to top
reworked example with multiple plots
whitespace
shorter ticks, thickness relative to pointsize
make sizes relative to configurable base_size
more space around axis titles
Bug fix: used wrong object
specify aspect ratio
Fix trim error with factor date
rename ggplot theme
FEAT: added ability for the compiler to extract typeset definitions from scalars.red.
bring in compliance with s3mpi change
Update test.rUpdate src_teradata.rSelect only cell lines of current cancer for achilles plot
Strange test II
Strange test
order before select in dtm.wordcloud
TESTS: added a compiling file message to Red/tests/build-arm-tests.r
TESTS: minor corrections to Red/run-all.r
r files for week 1 added
TESTS: Fix to allow for multiple runs of CALL/WAIT
TESTS: Clarify CALL-SHOW? to enable /SHOW if defined
TESTS: Create a switch for running CALL with /SHOW or /WAIT
do not use tail in this method
do not use tail for this
fix control matrix extraction bug from current minfi versionchanged suff stats
UI defaults
Finished optimizing project file size
remove defaults from UI for geom and stat type
Created copy of data.table for modifying field names
Shrunk project file size
Informative errors when species names don't match
Add informative error when matrix size is diff

When the number of species in the Host or Parasite phylogeny is
different to the number of species on the interaction matrix it used to
spit the “subscript out of bounds” error. Now it tells the actual
problem
Use names(input)
Minor update to updateInput
test thyroid
Głupi błąd w pobierz_dane_szkol().
Add pretty-printing of tables
Add partial test results to mantel.r output
reverted implementation of "pause refreshing" feature to using last_plot since validations are not shown when they are passed to reactiveValues.
fixed example
updated boxplot code
TESTS: minor fix to run-all.r script.
Fix typo in comment
Add todo note
Remove annoying warning resulting from `melt`

Treat variable names as characters rather than factors.
Attempt to remove conflict warnings when attaching
Enable caching
TESTS: fix a uninitialized word in run-all.r.
fixed bug, normalization now equivalent to minfi outside chromosomes X and Y
background correction, dye bias correction and control matrix now identical to funnorm in minfi
converted the implementation of "pause refresh" feature to using reactiveValues.
re-use helper files from production model
x and y chromosomes handled correctly
Used textareaInput for plot title
tidied up code, same outputs
summarize: move error checking to b$match
minor limit fixes
Plot loss with non-logarithmic y axis scale.
FEAT: minor code reduction.
Improve prediction figure
Fix prediction plot, bugs in make-regress-figs.r
Fix colours in boxplot
added search for formatting tree
Minor layout change on Customize tab
Add census data exploration
Add smoothing, peak and plummet
Improve default import
FIX: issue #1031 (Red/System spaces don't seem to be printing from within Red)
Document semantics of sys module better
Exports add_pccoord again
splitting add_pcoa and coordpcoa
Add script name to sys module
added examples
corrected spelling
expand grid layout properly
export Qreg var
do not move split to array, leave comment
label vars properly in layout
add result to layout df
remove result naming
limit to one registry
reworked confidence plots
Rearange code
R/prepare_data.r
note on ape added
ape modification doc added
code cleanup
Install slidify
fix duplicated imports
Add more geo explorations.
Hadleyfy the content of the script.

Use dplyr wherever possible.
fix name handling in melt()
adde eigen pca test
modified to properly handle chrX and chrY for males and females
git-annex automatic sync
Delete commented code
add melt() function for arrays/dfs
vegan::null model instead of vegan::commsimulator

`commsimulator` was a deprecated function in vegan. Using the
`nullmodel` approach with has support and is ~ 35% faster.
TESTS: removed debugging leftover.
TESTS: added support for system/script/args
m >> n in pca bench for now
Add a few more plots, TODOs, and formattingclarity in cov benchmark + validity check
debug import_pcoa_data.r
debug import_pcoa_data.r
debug import_pcoa_data.r
debug import_pcoa_data.r
debug import_pcoa_data.r
debuf import_pcoa_data.r
Don’t export namespace

Create special environment and copy exported names into it.
TESTS: changes to red/run-all.r in preparation of a --fast option
Make summaries and use cpi

cpi is consumer price index, its used for inflation estimation
pack-assets - improved check when cmdReplace can be used and added new walk type
Allow explicitly setting script path
Overview of the dataset
Install rChart by default
Delete ui for changing import text file settings
Add parallel eval. and progress bar capabilities

Added parallel evaluation using foreach to spawn an independent process
per link. If doing sequentially it can also add a progress bar borrowed
from plyr. Updated corresponding roxygen comments for the function
Load helper libraries by default
change file upload limit
allow environment access
Change dates so that they are consistent with used subset of data

ggplot2-bayarea uses only subset of data used in sfhousing,
the dates where based on original dataset
Pobieranie danych o "artystyczności" szkół.
Add index for plot.all.topics and some optimizations
Add option to supply terms/freqs to wordcloud
make freqs optional
FIX: issue #995 (Shared library can't work on ARM-hf)
Add try/catch to amcat.hits
rename local variable
Delega all'option width l'ampiezza del terminale
Reading now works, at least in simple cases.
small but relevant changes
FIX: added missing new dependency in ARM backend.
PACo method included
D argument for paco_links
full complement of methods
vegan::eigenvals added to coordpcoa
ape::pcoa function altered to allow generate non-zero eigenvalue
remove margin, add method
Hack shiny.error option to skip validation errors
More functionality.
bugs, bugs everywhere
updated plots script
updated plots script
s3 adapter should able to write arbitrary objects
More functionality added.
heatmap sorted according to result table in page1.r
delete dependency on plotlyBug fix

Needed to supply only "Combined" scores to getHeatmap function
added null argument
added code for paper plots
added code for paper plots
Added the load of the CSV file
Further development - still not functional.
detailed aberration plot function updated with new value type
separate plot for errors
FEAT: cleaner handling of writing errors from the linker on locked files.
Preparando country-vis
TESTS: updated error messages in tests.
FIX: make Red compiler not emit routines definitions inline.
TESTS: run-all.r script update to reflect changed name for unicode test file.
Updated aloja_cli.r
Update ggplot2_formatter.r

Add in human_num as you cannot have labels = human_numbers()Fixed that combined bug here as well
Simplified comp1view1Plot after fixing server.r
Code cleanup
Added argument assertions
Update ggplot2_formatter.r

Change typo human_gdp to human_gbpUpdate ggplot2_formatter.r

Add in extra example for use of 'human_gdp'Fixed a grammatical mistakeremoved a debugging message
use director for colourise
added custom
Update ggplot2_formatter.r

Update with functions created for humanised currencies.temporary warning on stageRunners with zero stages
calculate pc variances..
more descriptive comment
update comment
fix readLong
fix readLong
actual names are being compared
do not allow environment mixing when coalescing runners
fix stage comparison
remove my superfluous library call
cs-lunch presentation random dataengine
update read-binary-fixes.r
Need director object for scoping environment
correct parent scoping on resource injections
Fixed bug

Selecting combined score resulted in oncogene plot
updated to add in running the run_neatline function
added use of function eudist to get earth sun distance
Add documentation to module "sys"
Minor changes
Dodana še možnost nastavitve pisav v glavni program.
Fix a build failure caused by merge
Fix a build failure caused by merge
changed default value for cancers
restructuring graphs
Use as.environment for compatibility with objectdiff
whitespace
speed up execution of test_basic.r

  * only look at first 5 repos
  * only print repo name, owner, updated_at
added option to composite all indices in a loop and providing coorinates for a usearea file
using mixel2 instead of mixel function and added option to composite all indices with a loop
Included zoomins for each chr
adjusted differential expression analysis code

annotation and fall back if there is no replicates
updated differential expression analysis code

allows grouping of replicates now
Fixed bug in getScorePlot
fixed small bug on R code with R version 3.0
re-enabled parallel computation
format change
added the ability to select multiple directories when compositing images.
a change was made to the values used in USGS masks. the code now works with both old and new versions of USGS masks
izbris tabele
popravek (barve na grafu)
added optional --user argument to IRkernel::installspec()
odkomentirana 3. faza
dodan uvoz nove razpredelnice za koordinate držav
dodan zemljevid
FEAT: improved CATCH statement's error checking and reporting.
adaption for ForeCA_0.2.0Remove panel border
-2nd predict
-2nd predict call
install necessary packages
simple model again
no splitting
more colon issues
fixed better scale
fixed hopefully
coef data.frame
Extends README in GeneratePlots.r
Parameterize the paths in GeneratePlots.r
typo corrected in page3.r in plot function
Added enhancer stuff
added all RNA 0 catch
Added RNA info
Revert "Added RNA column"

This reverts commit 944323aaa3839ce7d2386b3f463f6ef1ced5f5bb.
Added RNA column
added name based subset
updated modelRNA; everything is Gaussian right now
Inverted colors for TS heatmap
use of on.exit(, add=TRUE)
RingSetting
provide resource_name in resources
testing push
Add R shebang
Making sure stat_ellipse works correctly when imported into a clean session
initial commiting on tracked environment changes
revert environment injection using on.exit
rectangle-pack - having a line for sort-method hardcoded
pack-assets.r updated to it's current state
FEAT: minor code size reduction.
finalize change
Contains all functions necessary for page 1

page1DataFrame(): filtering of results that are shown in the plots
plotHeatmapPage1(): view 1
plotCategoryOverview(): view 2
FIX: reverting the changes for handling console recompilation to fix the new issues on Mac/Linux.
Adding more summary plots
refactor s3 and data adapter to s3 and s3data adapter
Melt data to avoid repeated lines of code.
FIX: file path error when precompilng console.
fix a bug and make it work
Add error bars to wdays.
move changes inside tundraContainer to feel safe
Experimental: Adding for cache statistics (WIP).
change default adapter behavior to add data when export data flag is set
FIX: system/options/boot inconsistency workaround.
REL: 0.5.0 objects support
Remove commented portion.
FIX: issue #893 (latest release 0.4.3 (commit 1ddcdc66e8) pre-compiles console everytime)
Experimental: Adding for cache statistics (WIP).
set up test code to add writing
fix col.margin parameter
Add -t/--title option to priv/summary.r
add caption from attr() instead of hardcoded; fix drop of attr when converting object-type
Updating to latest results.
Turn query errors into warnings
adding a figure that didn't get pushed earlier
Improving boxplot.
Making it fully generic - forgot one more variable
First version of boxplots from our benchmark data.
align colnames to the right
add code for fig size, but leave commented out
Added hard-coded values for another shared level file.
Fixed length value of raw path data.
Updating to latest results.
Nome do item 11 do menu consertado.
Apagando com o clear(), agora ta perfeito kkk
Agora apagando os objetos no inicio de cada item do menu.
Movido o grafico de linhas para o menu
Agora com o plot fodao! *consertando erro de escrita*
Agora com o plot fodao!
FEAT: added support for internal Red directive #build-date.
Ne izpišemo pobrisanih datotek, če jih ni.
Dodana še možnost brisanja brez vprašanja.
Ne smemo bit vedno tihi:)
clearpdf.r vključen v glavni program.
Dodana možnost tihega delovanja.
Still trying to fix the Travis build issue
Added ... to plotCUB so model and a2 can be passed as arguments
fix table end error
fix line styling placement
removed some non-functioning kmeans

Added term-document matrix section.
refactored topics over time
don't need to create .rdata file in step 7 of gapminder data cleaning
fix small problem in step 4 of gapminder data cleaning
fix small problem in 2nd step of gapminder data cleaning
add horizontal line styling to function (partial)
clean up position index variables
pass args to preprocessordocument args param
tidy and sort doc
add comments to stopword code
create stop word list from tables
fixed visible binding problem
FEAT: #call directive now accepts an object's method invocation.
Support recursive modules in help validity check

Work in progress.
Modified Idover.calc to logically work like the version in calculate_diffues_fraction.R. Existing version in Diffuse... seemed to have problems with if statements, logical order, and indexing.
Modified Idover.calc to logically work like the version in calculate_diffues_fraction.R. Existing version in Diffuse... seemed to have problems with if statements, logical order, and indexing.
Modified Idover.calc to logically work like the version in calculate_diffues_fraction.R. Existing version in Diffuse... seemed to have problems with if statements, logical order, and indexing.
isOpen not working appropriately, use tryCatch hack
added analysis
file_extension expects '.r'nsef, not nse
array/summarize: omit empty mappings
FEAT: propagated runtime/environment file changes to the builder include script.
debug norm v 5
debug norm v 5
do not allow global env when sourcing using Ramd
Merging remote changes
edit the graphics

Trying out some different smoothing
bind data.frame list to each other

Binded each of the html table data frames to one another. Can use "word" function next to get individual words for stoplist. Also refactored data chaining syntax to make more clear.
backwards compatibility with hookless containers
set table_start_r and table_start_c as baseline coords
added col margin option
add 3th OR example
add function to print list of tabulars
force these so they can be referenced in hooks
urejenostna spremenljivka
Updated R data dump script with article states.
popravek pri uvozu
sprememba urejenostne spremenljivke
odkomentiran uvoz s pomočjo xml
dodala urejenostno spremenljivko
bug fix for render v12
bug fix for render v12
bug fix for render v12
bug fix for render v3
Uvoz tabel
Added alignDepth plotting functions.

Added a set of functions to plot alignDepths and gene structures
together with each other.

plotTranscripts
pu.arrows (plot unit arrows)
plotDepthsTranscripts

These should not be considered as finished products. In particular the
plotTranscripts function depends on a specific list / dataframe
structure, that isn't formally described anywhere. I've used this as it
interfaces easily with a function I have for pulling gene transcripts
from a connection to an ensembl database. But it's difficult to make a
formal dependency on those functions. (Though I suppose one could access
directly a publich Ensembl database?).
respace serialize_xgb_object method
remove requirements of xgboost
Accept file! to CALL
Accept file! to CALL
fix type

relase->release
fix identation spacing
array: fix mask, subset names
[to merge with master] customize serialize/deserialize
update render v11b
update render v11b
fix wrong envir when checking vars
wav-to-mp3 - using mp3loop utility to have better loops quality
Changed hardcoded values for asset ids
map_simple: fix when apply reduces dimensions
update some comments
Fix problems with rename due to bug in dplyr

force use of plyr with this currently.
        R  s            *  @  V  l                E  [  o                                      ,    *              	  !	  2	  C	  P	  ]	  n	  	  	  	  	  #
  4
  B
  P
  
  
      /  F              !  M  n  |  '        +  <  M  a  u      "  /  <  S  `  m        Y      
    ,  9  F  S  d            M  \          Q      M        `      5  N          1  r                7  Q  k      7  I        &  3  @  M  Z  g  x      4            #  0      &  e  t      (    &    4!  P!  _!  n!  !  !  !  !  "  *"  @"  "  	#  ^#  #  $  Q$  $  $  $%  y%  %  &  )&  h&  x&  &  &  &  &  '  ''  +  .  ".  1.  F.  X.  .  .  	/  :/  P/  /  /  0   0  ;0  l0  0  0  0  0  1  1  1  1  u2  2  2  3  4  z5  l6  ^7  8  8  9  :  %;  i;  x;  j<  \=  N>  @?  2@  $A  B  %B  6B  CB  SB   C  C  -C  C  C  C  D  D  D  D  @E  qE  E  E  VF  lF  F  F  -G  CG  G  AH  H  I  kI  J  'J  vL  L  L  L  1M  M  M  M  N  N  N  AO  `O  O  O  O  O  O  zP  tU  nZ  h_  7d  1i  Ai  i  i  i  i  i  (j  Tj  j  j  j  j  j  {k  k  k  l  m  m  6m  Nm  fm  |m  )n  n  o  <o  o  p  Ip  Vp  p  q  Fq  dq  sq  q  q  q  q  q  fr  |r  r  r  r  s  Ls  s  s  s  =t  St  it  t  v  v  v  w  /w  vw  w  w  x  $x  Ex  fx  x  mxhdev/aloja,mxhdev/aloja,t-ivanov/aloja,t-ivanov/aloja,t-ivanov/aloja,t-ivanov/aloja,Aloja/aloja,Aloja/aloja,mxhdev/aloja,mxhdev/aloja,t-ivanov/aloja,t-ivanov/aloja,t-ivanov/aloja,Aloja/aloja,mxhdev/aloja,mxhdev/aloja,Aloja/aloja,Aloja/aloja,mxhdev/aloja,t-ivanov/aloja,t-ivanov/aloja,Aloja/aloja,t-ivanov/aloja,Aloja/aloja,Aloja/aloja,mxhdev/aloja,mxhdev/aloja,Aloja/aloja,Aloja/aloja,mxhdev/alojaNikolayShubenkovProgSchool/red,vehar/red,red-eco/red,rheber/red,vehar/red,red-eco/red,NikolayShubenkovProgSchool/red,rheber/redsarahsupp/hb-migration,sarahsupp/hb-migration,sarahsupp/hb-migrationthoolihan/GoogleAnalyticsRExamplethoolihan/GoogleAnalyticsRExamplethoolihan/GoogleAnalyticsRExamplethoolihan/GoogleAnalyticsRExamplethoolihan/GoogleAnalyticsRExamplethoolihan/GoogleAnalyticsRExamplerobertzk/mungebitsinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksinfotroph/ggplot-ticksSMAC-Group/gmwm,SMAC-Group/gmwm,SMAC-Group/gmwm,SMAC-Group/gmwminfotroph/ggplot-ticksinfotroph/DeLuciatoRinfotroph/DeLuciatoRinfotroph/DeLuciatoRinfotroph/DeLuciatoRinfotroph/DeLuciatoRrubayte-nki/oncinfotroph/DeLuciatoRamcat/amcat-rinfotroph/DeLuciatoRNikolayShubenkovProgSchool/red,vehar/red,rheber/red,red-eco/red,NikolayShubenkovProgSchool/red,red-eco/red,vehar/red,rheber/redrobertzk/syberiaStagesxiaodaigh/teradata.dplyrxiaodaigh/teradata.dplyrrubayte-nki/oncsyberia/syberiasyberia/syberiakasperwelbers/corpus-toolsrheber/red,NikolayShubenkovProgSchool/red,vehar/red,red-eco/red,NikolayShubenkovProgSchool/red,red-eco/red,vehar/red,rheber/redred-eco/red,red-eco/red,rheber/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,NikolayShubenkovProgSchool/red,vehar/redCillianMH/pdmExtremeValueTheoryNikolayShubenkovProgSchool/red,rheber/red,NikolayShubenkovProgSchool/red,red-eco/red,red-eco/red,vehar/red,rheber/red,vehar/redvehar/red,red-eco/red,NikolayShubenkovProgSchool/red,rheber/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/redvehar/red,vehar/red,rheber/red,rheber/red,red-eco/red,NikolayShubenkovProgSchool/red,red-eco/red,NikolayShubenkovProgSchool/redrobertzk/Ramdsyberia/directorperishky/meffilgeb5101h/trw,geb5101h/trwyindeng/shinyDatayindeng/shinyDatayindeng/shinyDatayindeng/shinyDatayindeng/shinyDataefcaguab/pacoefcaguab/pacoyindeng/shinyDatayindeng/shinyDatamrinesi/PrediXmod,mrinesi/PrediXmod,mrinesi/PrediXmod,mrinesi/PrediXmodtzoltak/EWDdaneklmr/codons,klmr/codonse3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedvyindeng/shinyDatathillux/rPlotsthillux/rPlotsNikolayShubenkovProgSchool/red,vehar/red,rheber/red,NikolayShubenkovProgSchool/red,red-eco/red,red-eco/red,rheber/red,vehar/redklmr/modules,klmr/modulesklmr/modules,klmr/modulesklmr/codons,klmr/codonsklmr/codons,klmr/codonsklmr/codons,klmr/codonsvehar/red,rheber/red,NikolayShubenkovProgSchool/red,red-eco/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/redperishky/meffilperishky/meffilyindeng/shinyDatarobertzk/Ramdperishky/meffilyindeng/shinyDatatearne/Sampler,tearne/Sampler,tearne/Samplermschubert/narray,mschubert/narraythillux/rPlotsMiradorn/david,nning/david,Miradorn/david,nning/david,Miradorn/david,nning/david,Miradorn/david,EmuxEvans/david,EmuxEvans/david,EmuxEvans/david,nning/david,EmuxEvans/davidrheber/red,vehar/red,NikolayShubenkovProgSchool/red,rheber/red,red-eco/red,red-eco/red,NikolayShubenkovProgSchool/red,vehar/rede3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedve3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedvklmr/codons,klmr/codonsyindeng/shinyDatayindeng/shinyDatamkuzak/RIntroBayareamkuzak/RIntroBayareaklmr/codons,klmr/codonsNikolayShubenkovProgSchool/red,vehar/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/red,red-eco/red,rheber/redklmr/codons,klmr/codonsefcaguab/pacoefcaguab/pacoklmr/codons,klmr/codonsefcaguab/pacoefcaguab/pacomschubert/clustermq,mschubert/clustermq,mschubert/clustermqmschubert/clustermq,mschubert/clustermq,mschubert/clustermqmschubert/clustermq,mschubert/clustermq,mschubert/clustermqmschubert/clustermq,mschubert/clustermq,mschubert/clustermqmschubert/clustermq,mschubert/clustermq,mschubert/clustermqmschubert/clustermq,mschubert/clustermq,mschubert/clustermqmschubert/clustermq,mschubert/clustermq,mschubert/clustermqthillux/rPlotsmkuzak/RIntroBayareaefcaguab/pacoefcaguab/pacoefcaguab/pacoyindeng/shinyDatadaigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawarabanmschubert/narray,mschubert/narraymkuzak/RIntroBayareamkuzak/RIntroBayareamschubert/narray,mschubert/narraywrathematics/pcapack,wrathematics/pcapack,wrathematics/pcapackperishky/meffile3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedv,e3bo/2015pedvyindeng/shinyDatamschubert/narray,mschubert/narrayefcaguab/pacored-eco/red,red-eco/red,rheber/red,NikolayShubenkovProgSchool/red,NikolayShubenkovProgSchool/red,vehar/red,rheber/red,vehar/redvehar/red,red-eco/red,rheber/red,red-eco/red,vehar/red,rheber/red,NikolayShubenkovProgSchool/red,NikolayShubenkovProgSchool/redwrathematics/pcapack,wrathematics/pcapack,wrathematics/pcapacksupertetelman/frc-data-analysis,supertetelman/frc-data-analysiswrathematics/pcapack,wrathematics/pcapack,wrathematics/pcapackDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsklmr/modules,klmr/modulesNikolayShubenkovProgSchool/red,red-eco/red,red-eco/red,rheber/red,rheber/red,vehar/red,vehar/red,NikolayShubenkovProgSchool/redmkuzak/RIntroBayareaOldes/rs,Oldes/rs,Oldes/rs,Oldes/rsklmr/modules,klmr/modulesmkuzak/RIntroBayareadaigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawarabanyindeng/shinyDataefcaguab/pacoklmr/codons,klmr/codonsyindeng/shinyDatakirillseva/microserver,robertzk/microserver,robertzk/microserverhadley/ggplot2-bayareatzoltak/EWDdanekasperwelbers/corpus-toolskasperwelbers/corpus-toolskasperwelbers/corpus-toolsrheber/red,rheber/red,NikolayShubenkovProgSchool/red,vehar/red,red-eco/red,NikolayShubenkovProgSchool/red,vehar/red,red-eco/redamcat/amcat-rrobertzk/microserver,robertzk/microserver,kirillseva/microservergiupo/rprogressbaroldweather/IMMA,oldweather/IMMA,oldweather/IMMA,oldweather/IMMAvanatteveldt/frogrred-eco/red,rheber/red,vehar/red,red-eco/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,NikolayShubenkovProgSchool/redefcaguab/pacoefcaguab/pacoefcaguab/pacoefcaguab/pacoefcaguab/pacoefcaguab/pacoyindeng/shinyDataoldweather/IMMA,oldweather/IMMA,oldweather/IMMA,oldweather/IMMAgiupo/rprogressbarthegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marblesthegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marblesrobertzk/syberiaStagesoldweather/IMMA,oldweather/IMMA,oldweather/IMMA,oldweather/IMMArubayte-nki/oncyindeng/shinyDatarubayte-nki/oncefcaguab/pacothegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marblesthegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marbles,thegricean/sinking-marblesFranjs88/MOOC-Visualization-Toololdweather/IMMA,oldweather/IMMA,oldweather/IMMA,oldweather/IMMArubayte-nki/oncodo/ramjet,odo/ramjetNikolayShubenkovProgSchool/red,NikolayShubenkovProgSchool/red,rheber/red,red-eco/red,red-eco/red,vehar/red,rheber/red,vehar/redFranjs88/MOOC-Visualization-ToolNikolayShubenkovProgSchool/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/red,vehar/red,red-eco/red,rheber/redvehar/red,vehar/red,rheber/red,NikolayShubenkovProgSchool/red,red-eco/red,NikolayShubenkovProgSchool/red,red-eco/red,rheber/redred-eco/red,red-eco/red,NikolayShubenkovProgSchool/red,NikolayShubenkovProgSchool/red,vehar/red,rheber/red,vehar/red,rheber/redmxhdev/aloja,mxhdev/aloja,t-ivanov/aloja,mxhdev/aloja,Aloja/aloja,mxhdev/aloja,Aloja/aloja,t-ivanov/aloja,Aloja/aloja,Aloja/aloja,t-ivanov/aloja,t-ivanov/aloja,mxhdev/aloja,t-ivanov/aloja,t-ivanov/aloja,Aloja/aloja,mxhdev/aloja,Aloja/aloja,mxhdev/aloja,mxhdev/aloja,t-ivanov/aloja,t-ivanov/aloja,Aloja/aloja,mxhdev/aloja,t-ivanov/aloja,Aloja/aloja,Aloja/aloja,mxhdev/aloja,t-ivanov/aloja,Aloja/alojajezdata/R,1R151-1/R,fdryan/Rrubayte-nki/oncrubayte-nki/onchoesler/rwantshue,hoesler/rwantshuehoesler/rwantshue,hoesler/rwantshue1R151-1/R,jezdata/R,fdryan/R1R151-1/R,jezdata/R,fdryan/Rhoesler/rwantshue,hoesler/rwantshuewrbrooks/lagr,wrbrooks/lagrrobertzk/syberiaStagesYupingLu/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,RBigData/pbdADIOSjezdata/R,1R151-1/R,fdryan/Rsyberia/stagerunner,davluangu/stagerunner,kirillseva/stagerunner,robertzk/stagerunnersolgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgndavluangu/stagerunner,syberia/stagerunner,kirillseva/stagerunner,robertzk/stagerunneramsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/riskyamsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/riskyamsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/riskykirillseva/stagerunner,syberia/stagerunner,robertzk/stagerunner,davluangu/stagerunnersyberia/stagerunner,kirillseva/stagerunner,robertzk/stagerunner,davluangu/stagerunnerrobertzk/stagerunner,syberia/stagerunner,kirillseva/stagerunner,davluangu/stagerunneraronlindberg/rgithub,s-u/rgithub,cscheid/rgithub,akhmed1/rgithubfjukstad/kvik,fjukstad/kvikamsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/riskysyberia/directorsyberia/directorrubayte-nki/oncDougFirErickson/LandsatLinkr,jdbcode/LandsatLinkrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrklmr/codons,klmr/codonspablitoarias/DevDatProdaleksandrov2/APPR-2015-16,stifler9/ANPP-2015-16,valentina2pucer/APPR-2015-16,MarvinHerzog/APPR-2015-16,NabergojV/APPR-2015-16,tinarazic/APPR-2017,AccipitrisArti/APPR-2017,idawitha/APPR-2017,rozmanU14/APPR-2015-16,ztrojer/APPR-2017,zantavcar/APPR-2015-16,janrems/APPR-2017,GalDrnovsek/APPR-2015-16,VezensekKaja/APPR-2015-16,vidamaver/APPR-2017,Anchiqua/APPR-2015-16,marinasirk/APPR-2015-16,gasparicdejan/APPR-2015-16,PiaM123/APPR-2015-16,janpristovnik/APPR-2017,masterlord99/APPR-2015-16,StangeljL12/APPR-2015-16,aniiiim/APPR-2015-16,ZigaP/APPR-2015-16,PezdirM14/APPR-2015-16,jakamun/APPR-2017,LonjaTT/APPR-2015-16,VidicL13/APPR-2017,tkordis/APPR-2015-16,tajadebeljak/APPR-2015-16,PirnovarA/APPR-2015-16,nastja88/APPR-2017,LampicJ15/APPR-2017,natasataskov/APPR-2017,jaanos/APPR-2015-16,jernejbanevec/APPR-2017,anamariostarijas/APPR-2017,anamozina/APPR-2015-16,Jan-hexit/APPR-2015-16,HovnikK15/APPR-2017,LeonHorvat/APPR-2017,katjakerzic/APPR-2015-16,jakov-kavcic/APPR-2015-16,jakov-kavcic/APPR-2017,vesnazupanc/APPR-2015-16,ZavbiA/APPR-2017,UrosKrampelj/APPR-2015-16,Charisa/APPR-2015-16,darjapet/APPR-2017,majorcek/APPR-2017,jure310/APPR-2015-16,katykro/APPR-2015-16,mihapelhan/APPR-2015-16,ZilavecM14/APPR-2015-16,pdurcik/APPR-2017giuliolunati/ren-c,codebybrett/ren-c,giuliolunati/ren-c,hostilefork/rebol,rgchris/ren-c,kealist/ren-c,mbk/ren-c,kealist/ren-c,kealist/ren-c,giuliolunati/ren-c,hostilefork/rebol,codebybrett/ren-c,codebybrett/ren-c,codebybrett/ren-c,hostilefork/rebol,kealist/ren-c,rgchris/ren-c,rgchris/ren-c,hostilefork/rebol,draegtun/ren-c,rgchris/ren-c,rgchris/ren-c,kealist/ren-c,giuliolunati/ren-c,mbk/ren-c,giuliolunati/ren-c,draegtun/ren-c,codebybrett/ren-c,hostilefork/rebol,mbk/ren-c,draegtun/ren-c,draegtun/ren-c,draegtun/ren-c,mbk/ren-czsx/r3,zsx/r3,zsx/r3,zsx/r3rubayte-nki/oncodo/ramjet,odo/ramjetrobertzk/mungebitsakhmed1/rgithub,s-u/rgithub,aronlindberg/rgithub,cscheid/rgithubs-u/rgithub,aronlindberg/rgithub,cscheid/rgithub,akhmed1/rgithubjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrDougFirErickson/LandsatLinkr,jdbcode/LandsatLinkrStenbergSimon/CNV_pipetrevormartin/basicrnaseqanalysispipeline,trevormartin/basicrnaseqanalysispipelinetrevormartin/basicrnaseqanalysispipeline,trevormartin/basicrnaseqanalysispipelinerubayte-nki/oncundeadpixel/arr,undeadpixel/arrwrbrooks/lagr,wrbrooks/lagrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkranjazavrl/APPR-2014-15anjazavrl/APPR-2014-15rgbkrk/IRkernel,Phobia0ptik/IRkernel,JanSchulz/IRkernel,ChinaQuants/IRkernel,ibm-et/IRkernel,ibm-et/IRkernel,gdtm86/IRkernel,mikecroucher/IRkernel,elaOnMars/IRkernel,chendaniely/IRkernelanjazavrl/APPR-2014-15anjazavrl/APPR-2014-15anjazavrl/APPR-2014-15NikolayShubenkovProgSchool/red,rheber/red,red-eco/red,red-eco/red,vehar/red,vehar/red,rheber/red,NikolayShubenkovProgSchool/redbjoernwe/gpfa,bjoernwe/gpfabcgov/envreportutilsNCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsNCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsYupingLu/pbdADIOS,RBigData/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOS,go-ski/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,RBigData/pbdADIOSDCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsNCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsphaller/reactive-joins,phaller/reactive-joins,phaller/reactive-joinsphaller/reactive-joins,phaller/reactive-joins,phaller/reactive-joinsrubayte-nki/oncNCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsDCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsNCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomicsNCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsNCBI-Hackathons/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,DCGenomics/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomics,NCBI-Hackathons/hackathon_v001_epigenomicsrubayte-nki/oncyindeng/shinyDataHHoofs/Enigmasyberia/directorgo-ski/pbdADIOS,YupingLu/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,RBigData/pbdADIOStsee/dumbbench,tsee/dumbbenchmmadsen/mmadsenrsyberia/stagerunner,robertzk/stagerunner,kirillseva/stagerunner,davluangu/stagerunnerrobertzk/stagerunner,davluangu/stagerunner,kirillseva/stagerunner,syberia/stagerunnerOldes/rs,Oldes/rs,Oldes/rs,Oldes/rsOldes/rs,Oldes/rs,Oldes/rs,Oldes/rsrheber/red,NikolayShubenkovProgSchool/red,red-eco/red,vehar/red,red-eco/red,NikolayShubenkovProgSchool/red,vehar/red,rheber/redrobertzk/syberiaStagesrubayte-nki/oncred-eco/red,red-eco/red,vehar/red,NikolayShubenkovProgSchool/red,rheber/red,rheber/red,NikolayShubenkovProgSchool/red,vehar/redoduwsdl/archive_profiler,oduwsdl/archive_profilerrobertzk/syberiaStagesbamos/zsh-history-analysis,bamos/zsh-history-analysis,bamos/zsh-history-analysisred-eco/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/redrobertzk/syberiaStagesbamos/zsh-history-analysis,bamos/zsh-history-analysis,bamos/zsh-history-analysisrobertzk/syberiaStagesmsteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterionrobertzk/syberiaStagesrheber/red,vehar/red,red-eco/red,NikolayShubenkovProgSchool/red,red-eco/red,NikolayShubenkovProgSchool/red,vehar/red,rheber/redrheber/red,red-eco/red,red-eco/red,NikolayShubenkovProgSchool/red,vehar/red,NikolayShubenkovProgSchool/red,vehar/red,rheber/redbamos/zsh-history-analysis,bamos/zsh-history-analysis,bamos/zsh-history-analysisred-eco/red,NikolayShubenkovProgSchool/red,rheber/red,rheber/red,NikolayShubenkovProgSchool/red,vehar/red,red-eco/red,vehar/redmsteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterionRBigData/pbdADIOS,RBigData/pbdADIOS,go-ski/pbdADIOS,YupingLu/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOSmhermans/tabulrbasho/basho_bench,fogfish/basho_bench,marksteele/basho_bench,linearregression/basho_bench,linearregression/basho_bench,mrallen1/basho_bench,basho/basho_bench,fogfish/basho_bench,GabrielNicolasAvellaneda/basho_bench,marksteele/basho_bench,mrallen1/basho_bench,marksteele/basho_bench,linearregression/basho_bench,marksteele/basho_bench,GabrielNicolasAvellaneda/basho_bench,GabrielNicolasAvellaneda/basho_bench,linearregression/basho_bench,fogfish/basho_bench,mrallen1/basho_bench,basho/basho_bench,GabrielNicolasAvellaneda/basho_bench,mrallen1/basho_bench,basho/basho_bench,fogfish/basho_benchmhermans/tabulrmsteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterionamcat/amcat-rsarahsupp/hb-migration,sarahsupp/hb-migration,sarahsupp/hb-migrationmsteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterionmmadsen/mmadsenrmsteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterionmhermans/tabulrAndySouth/andysouth.github.io,abbandaniel/abbandaniel.github.io,abbandaniel/abbandaniel.github.io,AndySouth/andysouth.github.io,elliott828/andysouth.github.io,elliott828/andysouth.github.ioOldes/rs,Oldes/rs,Oldes/rs,Oldes/rsmsteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterion,msteindorfer/criterionniltonvasques/traffic-control-rniltonvasques/traffic-control-rniltonvasques/traffic-control-rniltonvasques/traffic-control-rniltonvasques/traffic-control-rniltonvasques/traffic-control-rvehar/red,NikolayShubenkovProgSchool/red,rheber/red,vehar/red,rheber/red,red-eco/red,NikolayShubenkovProgSchool/red,red-eco/redvalentina2pucer/APPR-2015-16,StangeljL12/APPR-2015-16,HovnikK15/APPR-2017,janpristovnik/APPR-2017,ZilavecM14/APPR-2015-16,jure310/APPR-2015-16,jakov-kavcic/APPR-2015-16,katykro/APPR-2015-16,VezensekKaja/APPR-2015-16,ztrojer/APPR-2017,jakov-kavcic/APPR-2017,stifler9/ANPP-2015-16,ZigaP/APPR-2015-16,anamariostarijas/APPR-2017,VidicL13/APPR-2017,PezdirM14/APPR-2015-16,MarvinHerzog/APPR-2015-16,marinasirk/APPR-2015-16,majorcek/APPR-2017,katjakerzic/APPR-2015-16,Charisa/APPR-2015-16,jaanos/APPR-2015-16,jaanos/APPR-2014-15,tinarazic/APPR-2017,LeonHorvat/APPR-2017,Jan-hexit/APPR-2015-16,GalDrnovsek/APPR-2015-16,LonjaTT/APPR-2015-16,pdurcik/APPR-2017,PirnovarA/APPR-2015-16,vidamaver/APPR-2017,rozmanU14/APPR-2015-16,AccipitrisArti/APPR-2017,anjazavrl/APPR-2014-15,gasparicdejan/APPR-2015-16,vesnazupanc/APPR-2015-16,NabergojV/APPR-2015-16,mihapelhan/APPR-2015-16,PiaM123/APPR-2015-16,zantavcar/APPR-2015-16,tkordis/APPR-2015-16,LampicJ15/APPR-2017,ZavbiA/APPR-2017,janrems/APPR-2017,tajadebeljak/APPR-2015-16,darjapet/APPR-2017,UrosKrampelj/APPR-2015-16,aleksandrov2/APPR-2015-16,idawitha/APPR-2017,Anchiqua/APPR-2015-16,jernejbanevec/APPR-2017,natasataskov/APPR-2017,aniiiim/APPR-2015-16,masterlord99/APPR-2015-16,jakamun/APPR-2017,anamozina/APPR-2015-16,nastja88/APPR-2017StangeljL12/APPR-2015-16,Charisa/APPR-2015-16,jernejbanevec/APPR-2017,jakov-kavcic/APPR-2015-16,tinarazic/APPR-2017,ztrojer/APPR-2017,janrems/APPR-2017,Anchiqua/APPR-2015-16,natasataskov/APPR-2017,jaanos/APPR-2014-15,ZavbiA/APPR-2017,LampicJ15/APPR-2017,PirnovarA/APPR-2015-16,masterlord99/APPR-2015-16,jure310/APPR-2015-16,UrosKrampelj/APPR-2015-16,anamozina/APPR-2015-16,ZilavecM14/APPR-2015-16,vesnazupanc/APPR-2015-16,jaanos/APPR-2015-16,jakamun/APPR-2017,tajadebeljak/APPR-2015-16,valentina2pucer/APPR-2015-16,darjapet/APPR-2017,jakov-kavcic/APPR-2017,vidamaver/APPR-2017,nastja88/APPR-2017,gasparicdejan/APPR-2015-16,VezensekKaja/APPR-2015-16,aleksandrov2/APPR-2015-16,marinasirk/APPR-2015-16,majorcek/APPR-2017,rozmanU14/APPR-2015-16,pdurcik/APPR-2017,Jan-hexit/APPR-2015-16,NabergojV/APPR-2015-16,katykro/APPR-2015-16,anamariostarijas/APPR-2017,anjazavrl/APPR-2014-15,ZigaP/APPR-2015-16,idawitha/APPR-2017,PiaM123/APPR-2015-16,aniiiim/APPR-2015-16,GalDrnovsek/APPR-2015-16,VidicL13/APPR-2017,HovnikK15/APPR-2017,LeonHorvat/APPR-2017,LonjaTT/APPR-2015-16,AccipitrisArti/APPR-2017,janpristovnik/APPR-2017,MarvinHerzog/APPR-2015-16,tkordis/APPR-2015-16,katjakerzic/APPR-2015-16,zantavcar/APPR-2015-16,PezdirM14/APPR-2015-16,stifler9/ANPP-2015-16,mihapelhan/APPR-2015-16VezensekKaja/APPR-2015-16,MarvinHerzog/APPR-2015-16,katjakerzic/APPR-2015-16,Jan-hexit/APPR-2015-16,Anchiqua/APPR-2015-16,ZigaP/APPR-2015-16,tinarazic/APPR-2017,NabergojV/APPR-2015-16,janpristovnik/APPR-2017,jaanos/APPR-2015-16,jakov-kavcic/APPR-2015-16,PezdirM14/APPR-2015-16,VidicL13/APPR-2017,jakov-kavcic/APPR-2017,tkordis/APPR-2015-16,PirnovarA/APPR-2015-16,vesnazupanc/APPR-2015-16,marinasirk/APPR-2015-16,natasataskov/APPR-2017,janrems/APPR-2017,jernejbanevec/APPR-2017,mihapelhan/APPR-2015-16,AccipitrisArti/APPR-2017,masterlord99/APPR-2015-16,anjazavrl/APPR-2014-15,ZavbiA/APPR-2017,majorcek/APPR-2017,nastja88/APPR-2017,gasparicdejan/APPR-2015-16,Charisa/APPR-2015-16,jure310/APPR-2015-16,HovnikK15/APPR-2017,jaanos/APPR-2014-15,katykro/APPR-2015-16,PiaM123/APPR-2015-16,LeonHorvat/APPR-2017,UrosKrampelj/APPR-2015-16,stifler9/ANPP-2015-16,StangeljL12/APPR-2015-16,vidamaver/APPR-2017,anamozina/APPR-2015-16,tajadebeljak/APPR-2015-16,ZilavecM14/APPR-2015-16,aniiiim/APPR-2015-16,LampicJ15/APPR-2017,rozmanU14/APPR-2015-16,zantavcar/APPR-2015-16,pdurcik/APPR-2017,jakamun/APPR-2017,darjapet/APPR-2017,valentina2pucer/APPR-2015-16,GalDrnovsek/APPR-2015-16,aleksandrov2/APPR-2015-16,ztrojer/APPR-2017,idawitha/APPR-2017,anamariostarijas/APPR-2017,LonjaTT/APPR-2015-16vidamaver/APPR-2017,pdurcik/APPR-2017,jernejbanevec/APPR-2017,HovnikK15/APPR-2017,AccipitrisArti/APPR-2017,Anchiqua/APPR-2015-16,stifler9/ANPP-2015-16,janrems/APPR-2017,VezensekKaja/APPR-2015-16,GalDrnovsek/APPR-2015-16,ztrojer/APPR-2017,jakamun/APPR-2017,LeonHorvat/APPR-2017,jakov-kavcic/APPR-2015-16,nastja88/APPR-2017,PirnovarA/APPR-2015-16,vesnazupanc/APPR-2015-16,MarvinHerzog/APPR-2015-16,darjapet/APPR-2017,anamariostarijas/APPR-2017,mihapelhan/APPR-2015-16,anamozina/APPR-2015-16,katykro/APPR-2015-16,katjakerzic/APPR-2015-16,jaanos/APPR-2015-16,natasataskov/APPR-2017,NabergojV/APPR-2015-16,ZavbiA/APPR-2017,rozmanU14/APPR-2015-16,LonjaTT/APPR-2015-16,majorcek/APPR-2017,tkordis/APPR-2015-16,janpristovnik/APPR-2017,LampicJ15/APPR-2017,Charisa/APPR-2015-16,Jan-hexit/APPR-2015-16,gasparicdejan/APPR-2015-16,jakov-kavcic/APPR-2017,zantavcar/APPR-2015-16,aniiiim/APPR-2015-16,idawitha/APPR-2017,masterlord99/APPR-2015-16,UrosKrampelj/APPR-2015-16,ZilavecM14/APPR-2015-16,aleksandrov2/APPR-2015-16,StangeljL12/APPR-2015-16,marinasirk/APPR-2015-16,jure310/APPR-2015-16,VidicL13/APPR-2017,PezdirM14/APPR-2015-16,tinarazic/APPR-2017,valentina2pucer/APPR-2015-16,PiaM123/APPR-2015-16,tajadebeljak/APPR-2015-16,ZigaP/APPR-2015-16nastja88/APPR-2017,jakov-kavcic/APPR-2017,stifler9/ANPP-2015-16,anjazavrl/APPR-2014-15,jaanos/APPR-2014-15,masterlord99/APPR-2015-16,LonjaTT/APPR-2015-16,aniiiim/APPR-2015-16,marinasirk/APPR-2015-16,tajadebeljak/APPR-2015-16,jernejbanevec/APPR-2017,ztrojer/APPR-2017,valentina2pucer/APPR-2015-16,pdurcik/APPR-2017,majorcek/APPR-2017,StangeljL12/APPR-2015-16,darjapet/APPR-2017,anamariostarijas/APPR-2017,Charisa/APPR-2015-16,aleksandrov2/APPR-2015-16,zantavcar/APPR-2015-16,vidamaver/APPR-2017,GalDrnovsek/APPR-2015-16,NabergojV/APPR-2015-16,UrosKrampelj/APPR-2015-16,AccipitrisArti/APPR-2017,tkordis/APPR-2015-16,MarvinHerzog/APPR-2015-16,Jan-hexit/APPR-2015-16,jakamun/APPR-2017,idawitha/APPR-2017,jakov-kavcic/APPR-2015-16,tinarazic/APPR-2017,Anchiqua/APPR-2015-16,janrems/APPR-2017,anamozina/APPR-2015-16,katjakerzic/APPR-2015-16,PezdirM14/APPR-2015-16,jaanos/APPR-2015-16,jure310/APPR-2015-16,HovnikK15/APPR-2017,PiaM123/APPR-2015-16,LampicJ15/APPR-2017,ZilavecM14/APPR-2015-16,natasataskov/APPR-2017,ZavbiA/APPR-2017,janpristovnik/APPR-2017,VidicL13/APPR-2017,vesnazupanc/APPR-2015-16,rozmanU14/APPR-2015-16,mihapelhan/APPR-2015-16,ZigaP/APPR-2015-16,PirnovarA/APPR-2015-16,gasparicdejan/APPR-2015-16,VezensekKaja/APPR-2015-16,katykro/APPR-2015-16,LeonHorvat/APPR-2017mmadsen/mmadsenrsnoweye/cubfits,snoweye/cubfits,snoweye/cubfits,snoweye/cubfitsmhermans/tabulrmhermans/tabulrpetercarrjones/icc-data,petercarrjones/icc-datapetercarrjones/icc-data,petercarrjones/icc-dataReproducible-Science-Curriculum/rr-multifileReproducible-Science-Curriculum/rr-multifileReproducible-Science-Curriculum/rr-multifilemhermans/tabulrmhermans/tabulrsyberia/directorsyberia/directorAndySouth/andysouth.github.io,abbandaniel/abbandaniel.github.io,AndySouth/andysouth.github.io,abbandaniel/abbandaniel.github.io,elliott828/andysouth.github.io,elliott828/andysouth.github.iopetercarrjones/icc-data,petercarrjones/icc-datapetercarrjones/icc-data,petercarrjones/icc-dataRBigData/pbdADIOS,RBigData/pbdADIOS,go-ski/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,go-ski/pbdADIOS,YupingLu/pbdADIOS,YupingLu/pbdADIOS,YupingLu/pbdADIOS,RBigData/pbdADIOSvehar/red,NikolayShubenkovProgSchool/red,rheber/red,rheber/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/red,red-eco/redklmr/modules,klmr/modulessarahsupp/extreme_limitssarahsupp/extreme_limitssarahsupp/extreme_limitsrobertzk/syberiaStagesYupingLu/pbdADIOS,RBigData/pbdADIOS,RBigData/pbdADIOS,YupingLu/pbdADIOS,RBigData/pbdADIOS,go-ski/pbdADIOS,YupingLu/pbdADIOS,go-ski/pbdADIOS,RBigData/pbdADIOS,go-ski/pbdADIOSibm-et/IRkernel,gdtm86/IRkernel,mikecroucher/IRkernel,JanSchulz/IRkernel,rgbkrk/IRkernel,Phobia0ptik/IRkernel,ChinaQuants/IRkernel,elaOnMars/IRkernel,chendaniely/IRkernel,ibm-et/IRkernelozway/debugCubfits,ozway/debugCubfits,ozway/debugCubfitsmschubert/narray,mschubert/narrayvehar/red,vehar/red,NikolayShubenkovProgSchool/red,red-eco/red,rheber/red,red-eco/red,NikolayShubenkovProgSchool/red,rheber/redDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsrobertzk/RamdGoodly/text-thresher-backend,Goodly/text-thresher-backend,Goodly/text-thresher-backend,Goodly/TextThresher,Goodly/TextThresher,Goodly/TextThresherpetercarrjones/icc-data,petercarrjones/icc-datapetercarrjones/icc-data,petercarrjones/icc-datasyberia/tundra,robertzk/tundramhermans/tabulrmhermans/tabulrmhermans/tabulrmhermans/tabulrrobertzk/tundra,syberia/tundraanjazavrl/APPR-2014-15Goodly/text-thresher-backend,Goodly/TextThresher,Goodly/text-thresher-backend,Goodly/TextThresher,Goodly/text-thresher-backend,Goodly/TextThresheranjazavrl/APPR-2014-15anjazavrl/APPR-2014-15anjazavrl/APPR-2014-15anjazavrl/APPR-2014-15DrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsanjazavrl/APPR-2014-15lmjakt/rbamtools_wokai_mj,lmjakt/rbamtools_wokai_mj,lmjakt/rbamtools_wokai_mjrobertzk/syberiaStagesrobertzk/syberiaStageszsx/r3,zsx/r3,zsx/r3,zsx/r3draegtun/ren-c,kealist/ren-c,rgchris/ren-c,codebybrett/ren-c,hostilefork/rebol,hostilefork/rebol,hostilefork/rebol,codebybrett/ren-c,giuliolunati/ren-c,giuliolunati/ren-c,rgchris/ren-c,giuliolunati/ren-c,mbk/ren-c,codebybrett/ren-c,kealist/ren-c,kealist/ren-c,kealist/ren-c,codebybrett/ren-c,rgchris/ren-c,giuliolunati/ren-c,kealist/ren-c,hostilefork/rebol,draegtun/ren-c,rgchris/ren-c,draegtun/ren-c,mbk/ren-c,mbk/ren-c,draegtun/ren-c,mbk/ren-c,codebybrett/ren-c,hostilefork/rebol,giuliolunati/ren-c,draegtun/ren-c,rgchris/ren-ckoji-to/effort_calculator,koji-to/effort_calculator,koji-to/effort_calculatorrobertzk/syberiaStagesmschubert/narray,mschubert/narrayrobertzk/syberiaStagesDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsDrOppenheimer/matR-apps,DrOppenheimer/matR-apps,DrOppenheimer/matR-appsmschubert/narray,mschubert/narrayOldes/rs,Oldes/rs,Oldes/rs,Oldes/rsOldes/rs,Oldes/rs,Oldes/rs,Oldes/rsmschubert/narray,mschubert/narraymschubert/narray,mschubert/narraypetercarrjones/icc-data,petercarrjones/icc-data          )   C   L   U   ^   g   p   y                                 	      (  2  <  F  P  W  a  k  u                          4  K  U  ^  z                    ;  U  j                           /  ?  O  i  s                %  G  U  k                        #  5  G  Y  k  }                         )  3  C  e                        (  :  L  ^  g  x               	  	  )	  8	  N	  X	  b	  l	  	  	  	  	  	  	  	  	  	  	  
  
  
  6
  M
  \
  
  
  
  
  
  
  
    ,  V  ^  u  |                    %  1  =  P  c  p                  0  ^  n  ~                *  5  K  S  \  l  |                    *  1  ;  L  ]  q  ~                    !  2  C  T  e  l  }              &  7  H  Y  j  {                    +  Z  _  j                                  /  F  T  k                  $  <  F  P  Z  f  r  ~                          J  y                    '  /  T  y                  <  O  Z  b  i  }                  
       W              (  :  L  f  q  z          $  S  \  e  k  aloja-web/resources/aloja_cli.rcompiler.ragg_hb_checklists_paper2.rexplore.rexplore.rexplore.rexplore.rexplore.rexplore.rR/munge.rexample.rmirror.ticks.rmirror.ticks.rmirror.ticks.rmirror.ticks.rmirror.ticks.rmirror.ticks.rmirror.ticks.rmirror.ticks.rmirror.ticks.rR/avar.rmirror.ticks.rexample.rggthemes.rggthemes.rggthemes.rggthemes.rpage2.rggthemes.rR/amcatr.rggthemes.rutils/extractor.rR/adapter.rtest/test.rR/src_teradata.rpage2.rR/zzz.rR/zzz.rR/corpus.rtests/build-arm-tests.rrun-all.rr_files_introTask/NormMax.rquick-test/quick-test.rquick-test/quick-test.rquick-test/quick-test.rR/define.rR/utils.rR/functional-normalization.rsuff_stats.rinst/shinyDataApp/ui.rinst/shinyDataApp/project.rinst/shinyDataApp/ui.rinst/shinyDataApp/data.rinst/shinyDataApp/project.rR/prepare_data.rR/prepare_data.rinst/shinyDataApp/project.rinst/shinyDataApp/server.r3_calc_PEER_adj_exp.rR/pobierz_dane_szkol.rscripts/knit.rsrc/mantel-testing.rinst/shinyDataApp/sheets.rexample.rplot.rtests/run-all.rR/import.rR/import_package.rscripts/knit.rscripts/knit.rscripts/knit.rtests/run-all.rnormalize-450k.rnormalize-450k.rinst/shinyDataApp/sheets.rR/define.rnormalize-450k.rinst/shinyDataApp/ui.rsampler-spike/src/main/resources/farrington/script.rprocess.rplot.rbenchmarks/plot.loss.rsystem/compiler.rsrc/make-regression-results-figs.rsrc/make-regression-results-figs.rscripts/knit.rinst/shinyDataApp/ui.rinst/shinyDataApp/ui.rRIntroBayarea.rRIntroBayarea.rscripts/knit.rlexer.rscripts/sys.rR/add_pcoord.rR/add_pcoord.rscripts/sys/__init__.rR/add_pcoord.rR/prepare_data.rBatchJobsWrapper.rBatchJobsWrapper.rBatchJobsWrapper.rBatchJobsWrapper.rBatchJobsWrapper.rBatchJobsWrapper.rBatchJobsWrapper.rplot.rRIntroBayarea.rR/prepare_data.rR/add_pcoord.rR/add_pcoord.rinst/shinyDataApp/sheetsCustomize.rinit.rprocess.rRIntroBayarea.rRIntroBayarea.rprocess.rtest/pca.rnormalize-450k.rsrc/make-regression-results-figs.rinst/shinyDataApp/sheetsCustomize.rprocess.rR/PACo.rtests/run-all.rtests/run-all.rtest/pca.rquick-analysis.rbenchmark/cov.rimport_pcoa_data.rimport_pcoa_data.rimport_pcoa_data.rimport_pcoa_data.rimport_pcoa_data.rimport_pcoa_data.rR/import_package.rrun-all.rR/RIntroBayarea.rprojects-rswf/pack-assets/divided/pack-assets.rR/module_cache.rR/RIntroBayarea.rinit.rinst/shinyDataApp/ui.rR/paco_links.rscripts/knit.rinst/shinyDataApp/global.rR/microserver.r2-time-series.rR/pobierz_dane_szkol.rR/topmod.rR/corpus.rR/corpus.rsystem/formats/ELF.rR/query.rR/microserver.rR/progressbar.rR/IMMA/R/IMMA-package.rR/frog.rsystem/targets/ARM.rR/paco_links.rR/PACo.rR/PACo.rR/add_pcoord.rR/add_pcoord.rR/PACo.rinst/shinyDataApp/global.rR/IMMA/R/IMMA-package.rR/progressbar.rwriting/_2015/cogsci_2015/rscripts/plots.rwriting/_2015/cogsci_2015/rscripts/plots.rR/adapter.rR/IMMA/R/IMMA-package.rpage1.rinst/shinyDataApp/global.rpage1.rR/PACo.rwriting/_2015/cogsci_2015/rscripts/plots.rwriting/_2015/cogsci_2015/rscripts/plots.rserver.rR/IMMA/R/IMMA-package.rpage1.rpriv/summary.rsystem/linker.rserver.rtests/source/compiler/run-time-error-test.rcompiler.rtests/run-all.raloja-web/resources/aloja_cli.rggplot2_formatter.rpage1.rpage1.rR/iwanthue.rR/iwanthue.rggplot2_formatter.rggplot2_formatter.rR/rwantshue.rR/lagr.tune.bw.rR/utils.rR/adios-package.rggplot2_formatter.rR/stage_runner.rR/pca.rR/stage_runner.rformats/src/test/resources/read-binary-fixes.rformats/src/test/resources/read-binary-fixes.rformats/src/test/resources/read-binary-fixes.rR/stage_runner.rR/stage_runner.rR/stage_runner.rtests/testthat/test_basic.rdataengine/data-engine.rformats/src/test/resources/read-binary-fixes.rR/zzy_resource.rR/zzy_resource.rpage3.rR/run_landsatlinkr.rR/msscost.rscripts/sys/__init__.rserver.rprojekt.rsrc/boot/words.rsrc/boot/words.rpage4.rpriv/summary.rR/munge.rinst/tests/test_basic.rinst/tests/test_basic.rR/run_landsatlinkr.rR/calibrate_and_composite.rsegment_CNV.rCode/bulkrundeseq.rCode/bulkrundeseq.rpage3.rr/client.rR/lagr.dispatch.rR/msscal_single.rR/run_landsatlinkr.rR/tmunpackr.ruvoz/uvoz.rvizualizacija/vizualizacija.rR/kernel.rprojekt.ruvoz/uvoz.rvizualizacija/vizualizacija.rsystem/compiler.rsrc/foreca_node.rR/theme_soe.rfeaturizeModel3.rfeaturizeModel3.rfeaturizeModel3.rfeaturizeModel3.rfeaturizeModel3.rR/zzz.rfeaturizeModel2.rfeaturizeModel2.rfeaturizeModel2.rsrc/test/scala/scala/async/perf/GeneratePlots.rsrc/test/scala/scala/async/perf/GeneratePlots.rpage3.rfeaturizeModel1.rfeaturizeModel1.rfeaturizeModel1.rfeaturizeModel1.rfeaturizeModel1.rfeaturizeModel1.rfeaturizeModel1.rpage1.rinst/shinyDataApp/helpers.rSyntax.rR/zzy_resource.rdemo/test_heat.rr/boxplot.rR/plotting.rR/stage_runner.rR/stage_runner.rprojects/rectangle-pack/latest/rectangle-pack.rprojects-rswf/pack-assets/divided/pack-assets.rred.rR/adapter.rplotCategoryOverview.rred.rbenchmark/analyze.rR/adapter.rplot.rred.rR/adapter.rplot.rR/adapter.rresources/r/benchmarks.rR/adapter.rred.rversion.rplot.rred.rresources/r/benchmarks.rtests/test_heat.rtable_export_openxlsx.rpriv/summary.rtable_export_openxlsx.rresources/r/benchmarks.rR/query.rhb-migration.rresources/r/benchmarks.rR/plotting.rresources/r/benchmarks.rtable_export_openxlsx.rrmd2md.rprojects-rswf/pack-assets/divided/pack-assets.rresources/r/benchmarks.rsrc/main.rsrc/main.rsrc/main.rsrc/output.rsrc/output.rsrc/output.rcompiler.rclearpdf.rclearpdf.rclearpdf.rprojekt.rclearpdf.rR/dataset-functions.rR/cedric.plotting.rtable_export_openxlsx.rtable_export_openxlsx.rtopics.rtopics.rdata4exercise1/07_filter-every-five-years.rdata4exercise1/04_merge-pop-lifeExp-gdpPercap.rdata4exercise1/02_extract-from-excel-lifeExp.rtable_export_openxlsx.rtable_export_openxlsx.rR/zzy_resource.rR/zzy_resource.rrmd2md.rtable.rtable.rR/adios_read_str.rcompiler.rR/help.rDiffuse_fraction_of_solar_radiation.rDiffuse_fraction_of_solar_radiation.rDiffuse_fraction_of_solar_radiation.rR/utils.rtests/test_heat.rR/kernel.rR/cedric.mapBMatNames.rprocess.rbuild/includes.rnormalize_fun.2-27-14/norm_redux.v5.rnormalize_fun.2-27-14/norm_redux.v5.rR/load_dependency.rdump_data.rtopics.rtable.rR/tundra_container.rtable_export_openxlsx.rtable_export_openxlsx.rexamples.rtable_export_openxlsx.rR/tundra_container.ruvoz/uvoz.rdump_data.rlib/xml.ruvoz/uvoz.ruvoz/uvoz.ruvoz/uvoz.rplot_fun.12-10-13/pcoa/render_calculated_pcoa.dev.v12.rplot_fun.12-10-13/pcoa/render_calculated_pcoa.dev.v12.rplot_fun.12-10-13/pcoa/render_calculated_pcoa.dev.v12.rplot_fun.12-10-13/pcoa/render_calculated_pcoa.dev.v12.ruvoz/uvoz.rR/rbamtools.rR/utils.rR/adapter.rsrc/boot/natives.rsrc/boot/natives.rscript/calculate_metrics.rR/adapter.rprocess.rR/adapter.rplot_fun.12-10-13/pcoa/render_calculated_pcoa.dev.v11b.rplot_fun.12-10-13/pcoa/render_calculated_pcoa.dev.v11b.rchecks.rprojects/wav-to-mp3/latest/wav-to-mp3.rprojects-rswf/pack-assets/divided/pack-assets.rprocess.rprocess.rload.r         
      "   +   4   =   F   O   X   [   ^   a   d   g   j   m   p   s   v   y                                                                                               #  *  1  4  7  :  =  G  J  M  Y  e  q  {                                          !  +  5  ?  K  U  \  c  m  t  {                                      !  -  0  3  =  D  P  \  c  m  t                              	            "  %  (  4  7  :  =  G  J  V  ]  d  k  r  y                                                	            '  0  3  6  9  @  I  L  O  R  \  f  p  s  v  y  |                                                                      
        %  ,  3  :  A  H  O  V  b  n  q  x                                                  #  &  )  ,  8  ;  G  S  V  b  n  u  }                                  !  +  7  :  =  @  C  F  P  W  _  g  j  m  t  {                                       	  	  	  $	  '	  1	  4	  7	  :	  B	  J	  R	  Z	  ]	  `	  j	  m	  p	  s	  v	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  
  
  
  &
  0
  3
  apache-2.0bsd-3-clausebsd-2-clauseunlicenseunlicenseunlicenseunlicenseunlicenseunlicensemitmitmitmitmitmitmitmitmitmitmitagpl-3.0mitmitmitmitmitmitmitmitmitmitbsd-3-clausemitmitmitmitmitmitmitbsd-3-clausebsd-3-clausemitbsd-3-clausebsd-3-clausebsd-3-clausemitmitartistic-2.0mitmitmitmitmitmitmpl-2.0mpl-2.0mitmitmitmitapache-2.0mitmitbsd-3-clausebsd-3-clausebsd-3-clauseapache-2.0apache-2.0apache-2.0apache-2.0apache-2.0bsd-3-clauseartistic-2.0artistic-2.0mitmitartistic-2.0mitapache-2.0apache-2.0bsd-3-clausemitbsd-3-clausemitmitapache-2.0mitmitapache-2.0apache-2.0apache-2.0bsd-3-clauseapache-2.0mpl-2.0mpl-2.0apache-2.0mpl-2.0mpl-2.0apache-2.0apache-2.0apache-2.0apache-2.0apache-2.0apache-2.0apache-2.0bsd-3-clauseapache-2.0mpl-2.0mpl-2.0mpl-2.0mitmitapache-2.0apache-2.0apache-2.0apache-2.0mpl-2.0artistic-2.0mitmitapache-2.0mpl-2.0bsd-3-clausebsd-3-clausempl-2.0apache-2.0mpl-2.0bsd-2-clausebsd-2-clausebsd-2-clausebsd-2-clausebsd-2-clausebsd-2-clauseapache-2.0bsd-3-clauseapache-2.0bsd-3-clauseapache-2.0apache-2.0mitmitmpl-2.0apache-2.0mitmitmitmitmitmitmitbsd-3-clausemitmitmitapache-2.0mitbsd-3-clausempl-2.0mpl-2.0mpl-2.0mpl-2.0mpl-2.0mpl-2.0mitapache-2.0mitmitmitmitapache-2.0mitmitmitmpl-2.0mitmitmitapache-2.0mitmitbsd-3-clausemitbsd-3-clausebsd-3-clausebsd-3-clauseapache-2.0unlicensemitmitmitmitunlicenseunlicensemitmitmitmpl-2.0unlicensemitmitmitapache-2.0apache-2.0apache-2.0mitmitmitmitmitapache-2.0mitmitmitmitmitapache-2.0mitmitapache-2.0apache-2.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitbsd-3-clausemitapache-2.0cc0-1.0cc0-1.0cc0-1.0cc0-1.0cc0-1.0mpl-2.0cc0-1.0cc0-1.0cc0-1.0bsd-3-clausebsd-3-clausemitcc0-1.0cc0-1.0cc0-1.0cc0-1.0cc0-1.0cc0-1.0cc0-1.0mitmitapache-2.0mitmpl-2.0artistic-2.0apache-2.0mitmitbsd-3-clausebsd-3-clausebsd-3-clausemitmitbsd-3-clausemitmitmitbsd-3-clausemitmitmitbsd-2-clausemitbsd-3-clausebsd-3-clausemitbsd-3-clausebsd-2-clausempl-2.0agpl-3.0apache-2.0agpl-3.0bsd-2-clausemitbsd-2-clausebsd-2-clauseapache-2.0bsd-2-clauseagpl-3.0mitbsd-3-clausebsd-2-clauseapache-2.0apache-2.0apache-2.0apache-2.0apache-2.0apache-2.0bsd-3-clausemitmitmitmitmitapache-2.0mpl-2.0agpl-3.0agpl-3.0mitmitcc0-1.0cc0-1.0cc0-1.0agpl-3.0agpl-3.0mitmitmitmitmitmpl-2.0bsd-3-clauseapache-2.0bsd-2-clausebsd-2-clausebsd-2-clausemitmpl-2.0mitmpl-2.0apache-2.0bsd-3-clausebsd-2-clausebsd-2-clausemitapache-2.0mitmitmitagpl-3.0agpl-3.0agpl-3.0agpl-3.0mitmitapache-2.0mitmitmitmitbsd-2-clausebsd-2-clausebsd-2-clausebsd-2-clausemitartistic-2.0mitmitapache-2.0apache-2.0mitmitapache-2.0mitbsd-2-clausebsd-2-clauseapache-2.0bsd-3-clausebsd-3-clauseapache-2.0apache-2.0mit     mT    T    !T    >T    >T    6T    K6T    6T    5T    3T    T    T    .pT    nT    SkT    jT    bhT    *gT    aT    `T    PT    &JT    3T    b#T    N#T    "T    T     T    &T    lT    0T    >T    
T    /T    T    T    }T    (T    -T    T    z|T    T    DT    T    bT    T    T    ST    T    uT    rT    qT    qT    ]^T    YRT    KT    u>T    -5T    oT    uT    oT    T    T    T    T    T    /T    /T    U#T    4#T    ;T    T    `T    T    4T    NtT    KT    a7T    `T    8T    pT    ]T    VT    j9T    T    T    3T    T    VT    T    VT    JT    :T    ET    9T    T    T    T    QT    NT    mNT    LT    JT    {?T    4;T    'T    T    (T    uT    T    LCT    5T    )T     T    T    T    bT    XT    XDT    T    T    kT    kT    T    	T    T    T    T    ܦT    T    FT    T    T    T    pT    OaT    ZT    T    (T    T    [T    )T    BT    \T    T    yT    EPT    T    0WT    T    T    T    nzT    T    {T    7T    >T    'T    T    9T    T    T    vT    T    nT    Q5T    AAT    AAT    7T    "T    8T    fT    	T    xT    T    T    NT    xT    yT    hT    }T    CT    PT    T    GT    rT    VYT    aT    ZT    T    pT    T    ̴T    ==T    /T    'T    T    T    T    T    jXT    BT    v@T    l>T    Q.T    l'T    !T    ܠT    T    HT    ~T    T    iT    ^T    ]T    2T    RT    JT    ׷T    ׷T    ڶT    ~8T    T    轵T    張T    oYT    WNT    >T    6T    5T    T    T    xT    WIT    HT    HT    #HT    GT    T    ѯT    ѯT    XѯT    RT    T    FT    \T    :T    T    ҊT    T    T    }T    |T    bT    [T    ZT    2T    aT    eT    z_T    A_T    (_T    UT    ]ST    #AT    $T    "T    T    HT    8=T    4T    7TT    2T    ũT    T    T    7΢T    YT    0T    T    |
T    2T    yT    xT    |T    ZT    GUT    sJT    KT    T    T    T    .T    T    A7T    !T    T    ǒT    ѽT    >9T    T    <ՐT    nT    =T    z%T    T    <T    T    CT    wT    pT    fT    eT    T    PT    YT    |T    T    ST    wT    ?T    7T    ^T    T    dT    T    T    T    T    T    ȉT    1T    `uT    QT    FT    T    qT    ڈT    ؈T    ؈T    ؈T    T    ET    T    T    !xT    
T    ^lT    fT    aT    *T    a2T    1T    ,T    yT    lT    =T    uT    o<T    MT    뀃T    (cT    bT    vT    T    yT    OT    T    9T    &T    _9T    ^/T    ӀT    .ÀT    .ÀT    8T    T    {T    !]T    !LT    xJT    }&T    `T    T    ~T    ~T    ~T           ː   × O  {  ͱ   5      7' P1 9 > @ <C E yG Q fS  R    r    n / )   =r   % \B   ` H - *D Y ^ b v   /  07   	  ;  I V gc o Gt @ 9   ɾ |	 K	 `	 	 |	 +	 "6 2O g at      , 1i p  = V p  @   C* SH f  ̵     (    C T a  q  n  4 ,; ? bD E L M ^p ƈ 0 A   1   
 - 7  o o   % + 4 4B r  g p  m o1  z _ ?  c %   P* L   ? ^ xE . _ ^4  z k \2 W d} W   % % Ӄ s   )  b < ; : ɭ     [ h          ț f j   1 ;  B Y 6[ 8e :o z ٔ #   Ө Ϳ  R  Q  
 n( NC V o y 7    + 1! ! 0#! qP! }! ! ! " " <*" Q" u" R" " " " K" r# e# &# 6# F# Qk# ܆# s# q# # # # m$ a$ $ P% Ļ% y% && })& ,5& q& Z~& o& & c& b.' ' /( V( V( 	\( ( J) pc) d) җ) ) UQ* \* + + K+ "M, m, ~, E- - - - Z-  - - - ;/ >/ B/ D/ bF/ 'I/ )X/ / n/ / 6/ / / [0 @0 ]0 u0 f0 0 0 0 #0 T0 Q2 a2 &2 2 P2 2 2 3 m3 P73 @3 3 /3 3 3 4 4 !4 I74 I4 R4 bj4 4 4 4 4 Й4 M4 Ш4 t5 ?6 
7 7 7 U: c: i: =; ~; a; 1; ; F!< <  = = = V> U> > > #!/usr/bin/env Rscript

# Josep Ll. Berral-García
# ALOJA-BSC-MSR hadoop.bsc.es
# 2014-12-11
# Launcher of ALOJA-ML
 
# usage: ./aloja_cli.r -m method [-d dataset] [-l learned model] [-p param1=aaaa:param2=bbbb:param3=cccc:...] [-a] [-n dims] [-v]
#	 ./aloja_cli.r --method method [--dataset dataset] [--learned learned model] [--params param1=aaaa:param2=bbbb:param3=cccc:...] [--allvars] [--numvars dims] [--verbose]
#
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1-small:vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size"
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p1 -d m5p1-tt.csv -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":sorted=asc -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":sorted=asc -v
#
#	 ./aloja_cli.r -m aloja_outlier_dataset -d m5p1-tt.csv -l m5p1 -p sigma=3:hdistance=3:saveall=m5p1test
#	 ./aloja_cli.r -m aloja_outlier_instance -l m5p1 -p instance="sort,ETH,RR3,8,10,1,65536,None,32,Azure L":observed=100000:display=1 -v
#
#	 ./aloja_cli.r -m aloja_pca -d aloja-dataset.csv -p saveall=pca1
#	 ./aloja_cli.r -m aloja_regtree -d pca1-transformed.csv -p prange=1e-4,1e+4:saveall=m5p-simple-redim -n 20
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p-simple-redim -p inst_predict="1922.904354752,70.1570440421649,2.9694955079494,-3.64259027685954,-0.748746678239734,0.161321484374316,0.617610510007444,-0.459044093400257,0.251211132013151,0.251937462205716,-0.142007748147355,-0.0324862729758309,0.406308900544488,0.13593705166432,0.397452596451088,-0.731635384355167,-0.318297127484775,-0.0876192175148721,-0.0504762335523307,-0.0146283091875174" -v
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p-simple-redim -d m5p-simple-redim-tt.csv -v
#	 ./aloja_cli.r -m aloja_transform_data -d newdataset.csv -p pca_name=pca1:saveall=newdataset
#	 ./aloja_cli.r -m aloja_transform_instance -p pca_name=pca1:inst_transform="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1
#	 ./aloja_cli.r -m aloja_dataset_collapse_expand -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1:inst_general="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L"
#	 ./aloja_cli.r -m aloja_best_configurations -p bvec_name=dsc1 -v
#
#	 ./aloja_cli.r -m aloja_minimal_instances -l m5p1 -p saveall=mi1
#	 ./aloja_cli.r -m aloja_minimal_instances -l m5p1 -p kmax=200:step=10:saveall=mi1

library(devtools);
source_url("https://raw.githubusercontent.com/Aloja/aloja-ml/master/functions.r");
options(width=as.integer(1000));

###############################################################################
# Read arguments from CLI

	suppressPackageStartupMessages(require(optparse));

	option_list = list(
		make_option(c("-m", "--method"), action="store", default=NULL, type='character', help="Method to be executed"),
		make_option(c("-p", "--params"), action="store", default=NULL, type='character', help="Generic list of parameters, separated by two points and no spaces"),
		make_option(c("-v", "--verbose"), action="store_true", default=FALSE, help="Outputs the result of the method"),
		make_option(c("-d", "--dataset"), action="store", default=NULL, type='character', help="For training methods: Dataset source of data"),
		make_option(c("-a", "--allvars"), action="store_true", default=FALSE, help="All vars are input but first one (for reduced dimensions)"),
		make_option(c("-n", "--numvars"), action="store", default=NULL, type='integer', help="All n vars after first one are input (for reduced dimensions)"),
		make_option(c("-l", "--learned"), action="store", default=NULL, type='character', help="For prediction methods: Learned model for prediction")
	);

	opt = parse_args(OptionParser(option_list=option_list));

###############################################################################
# Error and Warning messages on arguments

	if (is.null(opt$method))
	{
		cat("[ERROR] No method selected. Aborting mission.\n");
		quit(save="no", status=-1);
	}

###############################################################################
# Read datasets

	dataset <- NULL;

	if (!is.null(opt$dataset))
	{
		# Call for aloja_get_data
		params_1 <- list();
		params_1[["fread"]] = opt$dataset;

		dataset <- do.call(aloja_get_data,params_1);
	}

###############################################################################
# Parse parameters

	params <- list();
	params[["ds"]] <- dataset;

	if (opt$method %in% c("aloja_regtree","aloja_nneighbors","aloja_linreg","aloja_nnet","aloja_pca","aloja_dataset_collapse","aloja_dataset_collapse_expand","aloja_outlier_dataset","aloja_outlier_instance","aloja_binarize_instance"))
	{
		if (is.null(opt$vout)) params[["vout"]] <- "Exe.Time";

		if (is.null(opt$vin))
		{
			if (opt$allvars)
			{
				params[["vin"]] = colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))];
			} else if (!is.null(opt$numvars)) {
				params[["vin"]] = (colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))])[1:opt$numvars];
			} else {
				params[["vin"]] = c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
			}
		}
	}

	if (opt$method  %in% c("aloja_print_individual_summaries","aloja_print_summaries"))
	{
		params[["vin"]] <- c("Exe.Time","Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
	}

	if (!is.null(opt$learned))
	{
		params_2 <- list();
		params_2[["tagname"]] <- opt$learned;
		params[["learned_model"]] <- do.call(aloja_load_object,params_2);
	}

	if (!is.null(opt$params))
	{
		saux_1 <- strsplit(opt$params, ":");
		saux_2 <- strsplit(saux_1[[1]],"=");

		for (i in 1:length(saux_2))
		{
			params[[saux_2[[i]][1]]] <- strsplit(saux_2[[i]][2],",")[[1]];
		}
		rm(saux_1,saux_2);
	}

	if (is.null(params$vin) && opt$method  == "aloja_predict_instance")
	{
		if (length(params$inst_predict) == length(params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
		}
	}
	if (is.null(params$vin) && opt$method  == "aloja_predict_dataset")
	{
		if (all(colnames(params$ds) %in% params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
		}
	}

###############################################################################
# Execute call

	result <- do.call(opt$method,params);

	if (opt$verbose) result;

###############################################################################
# C'est fini

	quit(save="no", status=0);

REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	types-cache:   make hash!  100						;-- store compiled typesets [types array name...]
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		forever foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct try
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall forever]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| #get pos: (process-get-directive pos/1 pos)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	make-typeset: func [
		spec [block!] option [block! none!]
		/local bs ts word bit idx name
	][
		spec: sort spec									;-- sort types to reduce cache misses
		
		either bs: find/only/skip types-cache spec 3 [
			ts: bs/2
			name: bs/3
		][
			ts: copy [0 0 0]

			foreach type spec [
				type: either word: in extracts/scalars type [get word][reduce [type]]
				
				foreach word type [
					word: head remove back tail form word	;-- remove ending #"!"
					replace/all word #"-" #"_"
					type: to word! uppercase head insert word "TYPE_"
					bit: select extracts/definitions type
					idx: (bit / 32) + 1
					poke ts idx ts/:idx or shift/logical -2147483648 bit and 255
				]
			]
			forall ts [ts/1: to integer! to-bin32 ts/1]	;-- convert to little-endian values
			
			redirect-to literals [
				name: decorate-series-var 'ts
				emit reduce [to set-word! name 'typeset/create ts/1 ts/2 ts/3]
				insert-lf -5
			]
			append types-cache reduce [spec ts name]
		]
		either option [
			option: to word! join "~" clean-lf-flag option/1
			reduce ['type-check-alt option name]
		][
			reduce ['type-check name]
		]
	]
	
	emit-type-checking: func [name [word!] spec [block!] /local pos type][
		name: to word! next form name					;-- remove prefix decoration
		
		either pos: find spec name [
			type: case [
				block? pos/2 					[pos/2]
				all [string? pos/3 block? pos/3][pos/3]
				'else 							[[default!]]
			]
			make-typeset type find/reverse pos refinement!
		][
			none
		]
		
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit [[stack/adjust]]
			][
				mark: tail output
				unless head? path [
					emit [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
								if path? pc/1 [emit [as red-path!]]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
							emit [as red-path!]
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
							if path? pc/1 [emit [as red-path!]]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-change*
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-change*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-change* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-try: does [
		unless block? pc/1 [
			pc: back pc
			comp-word									;-- fallback to interpreter
			exit
		]
		emit [catch RED_ERROR]
		insert-lf -2
		body: comp-sub-block 'try
		if body/1 = 'stack/reset [remove body]
		mark: tail output
		emit-open-frame 'try
		insert body mark
		clear mark
		append body [
			stack/unwind
		]
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
	
	comp-forever: does [
		pc: back pc
		change/part pc [while [true]] 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk args?
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		args?: yes
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			if symbols/1 = '~local [args?: no]			;-- signal end of arguments
			
			if all [
				args?
				blk: emit-type-checking symbols/1 spec
			][
				append init blk
				append init (index? symbols) - 1		;-- index of argument for the type-checker
			]
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native words/_body
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec select objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			redirect-to literals [
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			]
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame op
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-get-directive: func [
		path code [block!] /local obj ctx blk
	][
		unless path? path [
			throw-error ["invalid #get argument:" spec]
		]
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 2
		blk: [red/word/get-in (decorate-exec-ctx ctx) (get-word-index/with last path ctx)]
		insert code compose blk
	]
	
	process-in-directive: func [
		path word code [block!] /local obj ctx blk
	][
		if any [not path? path not any-word? :word][
			throw-error ["invalid #in argument:" mold path mold :word]
		]
		append path word
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 3
		blk: [red/object/get-word (decorate-exec-ctx ctx) (get-word-index/with word ctx)]
		insert code compose blk
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc form load-cache %version.r
				comp-expression
				true
			]
			#build-date [
				change pc mold now
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		clear types-cache
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
# Cleans up the data needed for the hummingbird migration project. 
# Only needs to be done once with the raw files sent from FAL
# files in "eBird_checklists_2008-2014
# SRS 25 Feb 2015

library(chron)
library(tools)


#path to files
filepath = "/home/sarah/Dropbox/Hummingbirds/hb_migration_data/ebird_raw/eBird_checklists_2008-2014/"
writepath = "/home/sarah/Dropbox/Hummingbirds/hb_migration_data/ebird_raw/eBird_checklists_2008-2014/aggregated_by_species/"


#----------------------------------------------------FUNCTIONS
GroupDuplicates = function(humdat) { 
  #gets rid of duplicate records that are part of the same group. 
  #Takes only the first record to move to analysis, keeps all single records that are not part of a group.
  gid = sort(unique(humdat$GROUP_ID))
  
  #open start a new dataframe with same columns as the main dataframe
  keep = humdat[1,]
  out = 0
  
  for (g in 1:length(gid)){
    out = out + 1
    tmp = humdat[which(humdat$GROUP_ID == gid[g]),]
    #record the first line of the data (assume the group has the same information)
    if (nrow(tmp) == 1) { keep[out,] = tmp }
    else{ keep[out,] = tmp[1,] }
  }
  
  keepnongroup = humdat[which(is.na(humdat$GROUP_ID)),]
  keep = rbind(keep, keepnongroup)
  return(keep)
}


#------------------------------------------------ AGGREGATE THE FILES
files = list.files(path = filepath, pattern = "eBird_checklists_*", recursive=TRUE, full.names=TRUE)

for (f in 1:length(files)){
  data = read.table(files[f], header=TRUE, sep="\t", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  #really ugly regex to pull month from filename
  MONTH = as.numeric(sub("_20[0-9][0-9]", "", sub("eBird_checklists_", "", basename(file_path_sans_ext(files[f])))))
  MONTH = rep(MONTH, nrow(data))
  data = cbind(data, MONTH)
  
  if (f == 1) { agg_data = data }
  else{ agg_data = rbind(agg_data, data) }
  print (paste("file", f, "is completed:", basename(file_path_sans_ext(files[f]))))
}


# print the species names
unique(agg_data$SCI_NAME)

#put migratory species in separate datafiles
bchu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Archilochus alexandri"),])
ruhu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Selasphorus rufus"),])
bthu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Selasphorus platycercus"),])
rthu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Archilochus colubris"),])
cahu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Selasphorus calliope"),])

#write the files to the folder for output
write.table(bchu, file = paste(writepath,"bchu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(ruhu, file = paste(writepath,"ruhu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(bthu, file = paste(writepath,"bthu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(rthu, file = paste(writepath,"rthu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(cahu, file = paste(writepath,"cahu08-14.txt", sep=""), row.names=FALSE, sep=",")

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")

     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "l",
          col = "white",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     xarea <- c(Day.Index, rev(Day.Index))
     yarea <- c(Pageviews, rep(0, nrow(data)))
     polygon(xarea, yarea, col = rgb(0.3, 0.8, 1, 0.5), border=NA)      
     
     lines(Pageviews ~ Day.Index, col = "navy")     
     
     points(Pageviews ~ Day.Index,  
            pch = 21,
            bg = "navy",
            col = "blue")       
     
     abline(a = 100, 
            b = 0,
            col = "gray")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")

     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          pch = 21,
          bg = "navy",
          col = "navy",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     xarea <- c(Day.Index, rev(Day.Index))
     yarea <- c(Pageviews, rep(0, nrow(data)))
     polygon(xarea, yarea, col = rgb(0.3, 0.8, 1, 0.5), border=NA)     
     
     abline(a = 100, 
            b = 0,
            col = "gray")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          col = "blue",
          pch = 21,
          bg = "navy",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     abline(a = 100, 
            b = 0,
            col = "gray")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          col = "blue",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     abline(a = 100, 
            b = 0,
            col = "gray")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          col = "blue",
          main = "Google Analytics",
          ylim = c(0, 200)) 
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b")
})
#' General-purpose data munging
#'
#' One can use \code{munge} to take a \code{data.frame}, apply a given set
#' of transformations, and persistently store the operations on
#' the \code{data.frame}, ready to run on a future \code{data.frame}.
#'
#' @param dataframe a data set to operate on.
#' @param ... usually a list specifying the necessary operations (see
#'    examples).
#' @param stagerunner logical or list. Whether to run the munge procedure or
#'    return the parametrizing stageRunner object (see package stagerunner).
#'    If a list, one can specify \code{remember = TRUE} to pass to the
#'    stageRunner initializer.
#' @param train_only logical. Whether or not to leave the \code{trained}
#'    parameter on each mungebit to \code{TRUE} or \code{FALSE} accordingly.
#'    For example, if \code{stagerunner = TRUE} and we are planning to re-use
#'    the stagerunner for prediction, it makes sense to leave the mungebits
#'    untrained. (Note that this will prevent one from being able to run the
#'    predict functions!)
#' @return data.frame that has had the specified operations applied to it,
#'    along with an additional property \code{mungepieces} that records
#'    the history of applied functions. These can be used to reproduce
#'    the transformations on e.g., a dataset that needs to have a
#'    prediction run.
#' @export
#' @examples
#' \dontrun{
#' iris2 <- munge(iris,
#'   list(column_transformation(function(x) 2 * x), 'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#'
#' iris2 <- munge(iris,
#'    # train function & predict function
#'    list(c(column_transformation(function(x) 2 * x),
#'         column_transformation(function(x) 3 * x)),
#'    # arguments to pass to transformation, i.e. column names in this case
#'    'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#' iris3 <- munge(iris, attr(iris2, 'mungepieces'))
#' # used transformations ("mungepieces") stored on iris2 and apply to iris3.
#' # They will remember that they've been trained already and run the
#' # prediction routine instead of the training routine. Note the above is
#' # also equivalent to the shortcut: munge(iris, iris2)
#' stopifnot(iris3[['Sepal.Length']] == iris[['Sepal.Length']] * 3)
#' }
munge <- function(dataframe, ..., stagerunner = FALSE, train_only = FALSE) {
  mungepieces <- list(...)
  if (length(mungepieces) == 0) return(dataframe)

  plane <- if (is.environment(dataframe)) dataframe else mungeplane(dataframe)

  if (is.data.frame(mungepieces[[1]]))
    mungepieces[[1]] <- attr(mungepieces[[1]], 'mungepieces')
  else if (is(mungepieces[[1]], 'tundraContainer'))
    mungepieces[[1]] <- mungepieces[[1]]$munge_procedure

  # If mungepieces[[1]] is of the form
  # list(list|mungepiece|function, list|mungepiece|function, ...)
  # just put it into mungepieces. This is so munge can be called as either
  # munge(dataframe, list(...)) or munge(dataframe, ...)
  if (length(mungepieces) == 1 && is.list(mungepieces[[1]]) &&
      all(unlist(lapply(mungepieces[[1]],
        function(x) is.mungepiece(x) || is.mungebit(x) || is.list(x) || is.function(x))))) {
      mungepieces <- mungepieces[[1]]
  }

  mungepieces <- lapply(mungepieces, parse_mungepiece,
                        train_only = !identical(train_only, FALSE))

  # order matters, do not parallelize!
  stages <- lapply(mungepieces, function(piece) {
    force(piece);
    if (is(piece, 'stageRunner') || is.function(piece)) { piece }
    else { function(env) piece$run(env) }
  })
  stages <- append(stages, list(function(env) {
    # For now, store the mungepieces on the dataframe
    if (length(mungepieces) > 0)
      attr(env$data, 'mungepieces') <- append(attr(env$data, 'mungepieces'), mungepieces)
  }))
  names(stages)[length(stages)] <- "(Internal) Store munge procedure on dataframe"

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) require(stagerunner)
  remember <- if ('remember' %in% names(stagerunner)) stagerunner$remember else FALSE
  runner <- stageRunner$new(as.environment(plane), stages, remember = remember)

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) runner
  else {
    runner$run()
    plane$data
  }
}

require(ggplot2)
require(grid)
require(gtable)
require(gridExtra) # just for multiplot demos.

source("mirror.ticks.r")

testplot=(ggplot(mtcars, aes(wt, hp))
	+geom_point())

grid.arrange(testplot, mirror.ticks(testplot))

# The reason I did this in the first place: 
# My advisor prefers INWARD-facing ticks on all sides.
lab_theme = theme_bw(10)+theme(
	panel.grid.major = element_blank(), 
	panel.grid.minor = element_blank(), 
	axis.ticks.length = unit(-0.25 , "lines"),
	axis.ticks.margin = unit(0.5 , "lines"))

testplot.fancy=(ggplot(mtcars, aes(wt, hp, color=factor(cyl)))
	+geom_point()
	+lab_theme)

grid.arrange(testplot.fancy, mirror.ticks(testplot.fancy))


# Multipanel plots:
tp_grid = (testplot.fancy
	+facet_grid(am~carb)
	+ggtitle("facet_grid, fixed scales"))
grid.arrange(
	tp_grid, 
	mirror.ticks(tp_grid), 
	mirror.ticks(tp_grid, allPanels=TRUE))

tp_grid_free = (testplot.fancy
	+facet_grid(am~carb, scales="free")
	+ggtitle("facet_grid, free scales"))
grid.arrange(
	tp_grid_free, 
	mirror.ticks(tp_grid_free), 
	mirror.ticks(tp_grid_free, allPanels=TRUE))

tp_wrap = (testplot.fancy
	+facet_wrap(~carb)
	+ggtitle("facet_wrap, fixed scales"))
grid.arrange(
	tp_wrap, 
	mirror.ticks(tp_wrap),
	mirror.ticks(tp_wrap, allPanels=TRUE))

tp_wrap_free = (testplot.fancy
	+facet_wrap(~carb, scales="free")
	+ggtitle("facet_wrap, free scales"))
grid.arrange(
	tp_wrap_free, 
	mirror.ticks(tp_wrap_free),
	mirror.ticks(tp_wrap_free, allPanels=TRUE))
mirror.ticks = function(ggobj, allPanels=FALSE){
	# Given a ggplot object with axes on the bottom and left, 
	# add matching axes on the top and right.
	# For a multipanel figure: 
	# if allPanels=F, mirrors ticks to the other end of the row/column. 
	# allPanels=T *not yet implemented*, 
	# when done it will mirror ticks from B->T and L->R within EACH panel...
	# But think about whether that's really what you want! 
	# The last thing most multipanel plots need is more tick marks.

	require(gtable)
	
	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	ggobj = ggplotGrob(ggobj)

	panel_extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		
		if(allPanels==FALSE && !is_toprow[i] && !is_rtcol[i]){
			# no mirroring to do in this panel, bail now
			next
		}

		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		
		if(allPanels==TRUE || is_rtcol[i]){
			rtax = axes$grobs[[cur_axes[1]]]

			rttxt = axgrep(rtax$children$axis, "text")
			rtax$children$axis$grobs[[rttxt]]$label = NULL

			rttick = axgrep(rtax$children$axis, "ticks")
			rtax_x = rtax$children$axis$grobs[[rttick]]$x
			rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
			class(rtax_x) = c("unit.list", "unit")
			rtax$children$axis$grobs[[rttick]]$x = rtax_x
		}else{
			rtax=grob(name=NULL)
			class(rtax) = c("zeroGrob", class(rtax))
		}

		if(allPanels==TRUE || is_toprow[i]){
			topax = axes$grobs[[cur_axes[2]]]

			toptxt = axgrep(topax$children$axis, "text")
			topax$children$axis$grobs[[toptxt]]$label = NULL
			
			toptick = axgrep(topax$children$axis, "ticks")
			topax_y = topax$children$axis$grobs[[toptick]]$y
			topax_y = sapply(topax_y, swaptick, simplify=FALSE)
			class(topax_y) = c("unit.list", "unit")
			topax$children$axis$grobs[[toptick]]$y = topax_y
		}else{
			topax=grob(name=NULL)
			class(topax) = c("zeroGrob", class(topax))
		}

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj, allPanels=FALSE){
	# Given a ggplot object with axes on the bottom and left, 
	# add matching axes on the top and right.
	# For a multipanel figure: 
	# if allPanels=F, mirrors ticks to the other end of the row/column. 
	# allPanels=T *not yet implemented*, 
	# when done it will mirror ticks from B->T and L->R within EACH panel...
	# But think about whether that's really what you want! 
	# The last thing most multipanel plots need is more tick marks.

	require(gtable)
	
	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	ggobj = ggplotGrob(ggobj)

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax_x = rtax$children$axis$grobs[[rttick]]$x
		rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
		class(rtax_x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax_x

		topax_y = topax$children$axis$grobs[[toptick]]$y
		topax_y = sapply(topax_y, swaptick, simplify=FALSE)
		class(topax_y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax_y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj, allPanels=FALSE){
	# Given a ggplot object with axes on the bottom and left, 
	# add matching axes on the top and right.
	# For a multipanel figure: 
	# if allPanels=F, mirrors ticks to the other end of the row/column. 
	# allPanels=T *not yet implemented*, 
	# when done it will mirror ticks from B->T and L->R within EACH panel...
	# But think about whether that's really what you want! 
	# The last thing most multipanel plots need is more tick marks.

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax_x = rtax$children$axis$grobs[[rttick]]$x
		rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
		class(rtax_x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax_x

		topax_y = topax$children$axis$grobs[[toptick]]$y
		topax_y = sapply(topax_y, swaptick, simplify=FALSE)
		class(topax_y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax_y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax_x = rtax$children$axis$grobs[[rttick]]$x
		rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
		class(rtax_x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax_x

		topax_y = topax$children$axis$grobs[[toptick]]$y
		topax_y = sapply(topax_y, swaptick, simplify=FALSE)
		class(topax_y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax_y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax.x = rtax$children$axis$grobs[[rttick]]$x
		rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
		class(rtax.x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax.x

		topax.y = topax$children$axis$grobs[[toptick]]$y
		topax.y = sapply(topax.y, swaptick, simplify=FALSE)
		class(topax.y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax.y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax.x = rtax$children$axis$grobs[[rttick]]$x
		rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
		class(rtax.x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax.x

		topax.y = topax$children$axis$grobs[[toptick]]$y
		topax.y = sapply(topax.y, swaptick, simplify=FALSE)
		class(topax.y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax.y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=panel.extents$t,
			l=panel.extents$l,
			r=panel.extents$r,
			b=panel.extents$b,
			z=panel.extents$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
## Creates RcppArmadillo S3 object export within R



#' @title Calculate the Allan Variance
#' @description Computes the Allan Variance
#' @usage avar(x)
#' @param x A \code{vec} containing the time series under observation.
#' @return Allan variance fixed
#' @author JJB
#' @examples
#' set.seed(999)
#' x=rnorm(100)
#' avar(x)
avar = function(x) {
  x = as.vector(x)
  av = .Call('GMWM_avar_fixed_arma', PACKAGE = 'GMWM', x)
  av$adev = sqrt(av$allan)
  av$lci = av$adev - av$errors*av$adev
  av$uci = av$adev + av$errors*av$adev
  class(av) = "avar"
  av
}

#' @title Prints Allan Variance
#' @description Displays the allan variance information
#' @method print avar
#' @param x A \code{avar} object.
#' @param ... Arguments to be passed to methods
#' @author JJB
#' @return console output
#' @examples
#' set.seed(999)
#' x=rnorm(100)
#' out = avar(x)
#' print( out )
print.avar = function(x, ...) {
  cat("\n Clusters: \n")
  print(x$clusters, digits=5)
  cat("\n Allan Variances: \n")
  print(x$allan, digits=5)
  cat("\n Errors: \n")
  print(x$errors, digits=5)
}

#' @title Plot Allan Variance
#' @description Displays a plot containing the allan variance
#' @method plot avar
#' @param x A \code{avar} object.
#' @param ... Arguments to be passed to methods
#' @author JJB
#' @return ggplot2 graph
#' @examples
#' set.seed(999)
#' x=rnorm(100)
#' out = avar(x)
#' plot( out )
plot.avar = function(x, ...){
  plot(x$clusters, x$adev,log="xy",
       xlab=expression("Scale " ~ tau),
       ylab=expression("Allan Deviation " ~ phi[tau]),
       main=expression(log(tau) ~ " vs. " ~ log(phi[tau]))
  )
  lines(x$clusters, x$adev, type="l")
  lines(x$clusters, x$lci, type="l", col="grey", lty=2)
  lines(x$clusters, x$uci, type="l", col="grey", lty=2)
}


#' @title Summary Allan Variance
#' @description Displays the summary table of allan variance
#' @method summary avar
#' @param object A \code{avar} object.
#' @param ...  additional arguments affecting the summary produced.
#' @author JJB
#' @return Summary table
#' @examples
#' set.seed(999)
#' x=rnorm(100)
#' out = avar(x)
#' summary( out )
summary.avar = function(object, ...) {
  out_matrix = matrix(0, nrow = length(object$clusters), ncol = 6)
  colnames(out_matrix) = c("Time", "AVAR", "ADEV", "Lower CI", "Upper CI", "Error")
  out_matrix[,"Time"] = object$clusters
  out_matrix[,"AVAR"] = object$allan
  out_matrix[,"ADEV"] = object$adev
  out_matrix[,"Lower CI"] = object$lci
  out_matrix[,"Upper CI"] = object$uci
  out_matrix[,"Error"] = object$errors
  
  class(out_matrix) = "summary.avar"
  out_matrix
}mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
library(ggplot2)
library(devtools) # for file downloads from Github
library(grid)
library(gridExtra) # for multiplot demo
library(gtable)

source("ggthemes.r")
source_url("https://raw.githubusercontent.com/infotroph/ggplot-ticks/master/mirror.ticks.r")


# An example scatterplot from the ggplot2 `mtcars` dataset:
# Plot weight converted to kg against miles per US gallon
# First something you might use in a small on-screen display...
carplot = (ggplot(mtcars, aes(wt*453.592, mpg))
	+geom_smooth(method="lm", se=TRUE, linetype="dotted", color="black")
	+geom_point()
	+xlab("Vehicle weight (kg)")
	+ylab("MPG")
	+theme_ggEHD(12))

# ...then one with room to blow it up.
carbigplot = (ggplot(mtcars, aes(wt*453.592, mpg))
	+geom_smooth(method="lm", se=TRUE, linetype="dotted", color="black")
	+geom_point(size=4)
	+xlab("Vehicle weight (kg)")
	+ylab("MPG")
	+theme_ggEHD(32))

# Let's put both plots side-by-side to see the differences.
# Try resizing the plot window and watch what happens.
# The settings you want depend on your image size!
# Note that mirror.ticks converts the plot from a ggplot object
# to a gtable object, so it should be the last thing you call after
# you've finished modifying the rest of the plot.
grid.arrange(
	mirror.ticks(carplot),
	mirror.ticks(carbigplot),
	nrow=1)
theme_ggEHD = function(base_size=18, ...){
	(theme_bw(base_size=base_size) %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		rect = element_rect(size=rel(0.75)),
		line = element_line(size=rel(1)),
		axis.ticks.length = unit(-(base_size*0.5), "points"),
		axis.ticks.margin = unit((base_size*1.5), "points"),
		plot.margin = unit(base_size*c(1,1,1,1), "points"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=base_size,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}
theme_ggEHD = function(base_size=18, ...){
	(theme_bw(base_size=base_size) %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		rect = element_rect(size=rel(0.75)),
		line = element_line(size=rel(1)),
		axis.ticks.length = unit(-(base_size*0.5), "points"),
		axis.ticks.margin = unit((base_size*1.5), "points"),
		plot.margin = unit(base_size*c(1,1,1,1), "points"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=base_size,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}theme_ggEHD = function(base_size=18, ...){
	(theme_bw(base_size=base_size) %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-(base_size*0.75), "points"),
		axis.ticks.margin = unit((base_size*1.5), "points"),
		plot.margin = unit(base_size*c(1,1,1,1), "points"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=base_size,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}theme_ggEHD = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		plot.margin = unit(c(1,1,1,1), "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}getPage2Plots = function(updateProgress = NULL,cancer, gene, sampleSelection) {
  
  if (gene == "")
  {
    return()
  }
  if (is.null(gene))
  {
    return()
  }
  
	if (sampleSelection == 1) {
		#priorDetails = tcgaResults[[cancer]]$prioritize.details
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = tcga.cna[[cancer]][[1]]
		acgh.group2 = tcga.mn.cna[[cancer]][[1]]
		achilles.ut = tcgaResultsAT[[cancer]][2]
		achilles.lt = tcgaResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#56B4E9")
		lab.group1="Tumors" 
		lab.group2="Normals"
		pvalue=TRUE
		cls = tcgaResults[[cancer]]$cls
	} else if (sampleSelection == 2) {
	  #priorDetails = ccleResults[[cancer]]$prioritize.details
		priorDetails = ccleResultsPrioDetails[[cancer]]
		exprs.group1 = ccle.exprs.combat[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = ccle.cna.combat[[cancer]][[1]]
		acgh.group2 = tcga.mn.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#009E73", "#56B4E9")
		lab.group1="Cell lines" 
		lab.group2="Normals"
		pvalue=TRUE
		cls = ccleResults[[cancer]]$cls
	} else {
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs.combat[[cancer]][[1]]
		exprs.group2 = ccle.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth.combat[[cancer]]
		#meth.group2 = tcga.mn.meth.combat[[cancer]]
		acgh.group1 = tcga.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#009E73")
		lab.group1="Tumors" 
		lab.group2="Cell lines"
		pvalue=FALSE
		cls = tcgaResults[[cancer]]$cls
	}
	#meth.anno = infinium450.probe.ann
  if (is.element(gene,rownames(achilles)))
  {
   achls = achilles[gene, cls]    
  }else{
    achls = NULL
  }
	#achls = achilles
	
	plots = plotGene(gene, priorDetails, samples=NULL, 
		 	 exprs.group1, exprs.group2, 
		 	 #meth.group1, meth.group2, meth.anno, 
		 	 acgh.group1, acgh.group2, 
		 	 achls, achilles.ut, achilles.lt, 
		 	 lab.group1=lab.group1, lab.group2=lab.group2, 
		 	 color.palette=color.palette,
		 	 size=4, width=0.2, pvalue=pvalue)
# 	if (sampleSelection != 1) {
# 		plots[["methylation"]] = NULL
# 	}
	if (sampleSelection == 3) {
		plots[["achilles"]] = NULL
	}
	
	plots
}
theme_ggEHD = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title=element_text(vjust=0.3),
		aspect.ratio=0.75,
		...
	))
}library(rjson)
library(RCurl)

#' Connect to the AmCAT API
#'
#' Connect to the AmCAT API and requests a temporary (24h) authentication token that will be stored in the output
#' If username and password are not given, a file ~/.amcatauth will be read, which should be a csv file with
#' columns host (may be *), username, password. If the file cannot be read, username will be taken from $USER
#' and the user will be prompted for the password.
#' 
#' @param host the hostname, e.g. http://amcat.vu.nl or http://localhost:8000
#' @param username the username to login with, e.g. 'amcat'. 
#' @param passwd the password to login with, e.g. 'amcat'
#' @param token an existing token to authenticate with. If given, username and password are not used and the token is not tested
#' @param disable_ipv6. If True, only use ipv4 resolving (faster if ipv6 causes timeout). Defaults to true, but this may change in the future.
#' @return A list with authentication information that is used by the other functions in this package
#' @export
amcat.connect <- function(host, username=NULL, passwd=NULL, token=NULL, disable_ipv6=TRUE) {
  opts = if (disable_ipv6) list(ipresolve=1) else list()
  
  if (is.null(token)) {
    if (is.null(passwd)) { # try amcatauth file
      a = tryCatch(.readauth(host), error=function(e) warning("Could not read ~/.amcatauth"))
      if (!is.null(a)) {
        username = a$username
        passwd = a$password
      }
    }
    if (is.null(username)) { # try USER variable
      username = Sys.getenv("USER")
      if (username == '') { # ask
        cat(paste("Please enter the username for", host, "\n"))
        username=readline()
      }
    }
    if (is.null(passwd)) { #ask
      cat(paste("Please enter the password for ",username,"@", host, " (or create a ~/.amcatauth file) \n", sep=""))
      passwd=readline()
    }
    # get auth token
    url = paste(host, '/api/v4/get_token', sep='')
    
    res = tryCatch(postForm(url, username=username, password=passwd, .checkParams=F, .opts=opts), 
                   error=function(e) stop(paste("Could not get token from ",
                                                 username,":",passwd,"@", host,
                                                 " please check host, username and password. Error: ", e, sep="")))
    token = fromJSON(res)$token
  }
  list(host=host, token=token, opts=opts)
}

#' Get authentication info from ~/.amcatauth file
.readauth <- function(host) {
  if (!file.exists("~/.amcatauth")) return()
  rows = read.csv("~/.amcatauth", header=F, stringsAsFactors=F)
  colnames(rows) <- c("host", "username", "password")
  r = rows[rows$host == '*' | rows$host == host,]
  if (nrow(r) > 0) list(username=r$username[1], password=r$password[1]) 
}


#' Retrieve a single URL from AmCAT with authentication and specified filters (GET or POST) 
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param path the path of the url to retrieve (using the host from conn)
#' @param filters a named vector of filters, e.g. c(project=2, articleset=3)
#' @param post use HTTP POST instead of GET
#' @return the raw result
#' @export
amcat.getURL <- function(conn, path, filters=NULL, post=FALSE, post_options=list(), error_unless_200=TRUE) {
  httpheader = c(Authorization=paste("Token", conn$token))
  url = parse_url(conn$host)
  url$path = paste(path, sep="/")
  h = getCurlHandle()
  # strip NULL filters
  for (n in names(filters)) if (is.null(filters[[n]])) filters[[n]] <- NULL
  if (!post) {
    # convert list(a=c(1,2)) to list(a=1, a=2). From: http://stackoverflow.com/a/22346656
    url$query = structure(do.call(c, lapply(filters, function(z) as.list(z))), names=rep(names(filters), sapply(filters, length)))
    
    # build GET url query
    url = build_url(url)
    message("GET ", url)
    result = getURL(url, httpheader=httpheader, .opts=conn$opts, curl=h)
    if (getCurlInfo(h)$response.code != 200){
      if (error_unless_200) stop("Unexpected Response Code ", getCurlInfo(h)$response.code, "\n", result)
      return(NULL)
    }
    result
  } else {  
    
    post_opts = modifyList(conn$opts, list(httpheader=httpheader))
    post_opts = modifyList(post_opts, post_options)
    postForm(build_url(url), .params=filters, .opts=post_opts)
  }
}

#' Get and rbind pages from the AmCAT API
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param path the path of the url to retrieve (using the host from conn)
#' @param filters: a named vector of filters, e.g. c(project=2, articleset=3)
#' @param post use HTTP POST instead of GET
#' @param page: the page number to start retrieving
#' @param page_size: the number of rows per page
#' @param max_page: the page number to stop retrieving at, if given
#' @return dataframe 
#' @export
amcat.getpages <- function(conn, path, format='csv', page=1, page_size=1000, filters=NULL, post=FALSE, max_page=NULL) {
  filters = c(filters, page_size=page_size, format=format)
  result = data.frame()
  while (TRUE) {
    if (!is.null(max_page)) if (page > max_page) break
    page_filters = c(filters, page=page)
    subresult = amcat.getURL(conn, path, page_filters, post=post)
    if (subresult == "") break
    subresult = .amcat.readoutput(subresult, format=format)
    result = rbind(result, subresult)
    if(nrow(subresult) < page_size) break
    page = page + 1
  }
  result
}

#' Get objects from the AmCAT API
#'
#' Get a table of objects from the AmCAT API, e.g. projects, sets etc.
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param resource the name of the resource, e.g. 'projects'. If it is of length>1, a path a/b/c/ will be created (e.g. c("projects",1,"articlesets"))
#' @param ... Other options to pass to \code{\link{amcat.getpages}}, e.g. page_size, format, and filters
#' @return A dataframe of objects (rows) by properties (columns)
#' @export
amcat.getobjects <- function(conn, resource, ...) {
  if (length(resource) > 1) resource = paste(c(resource, ""), collapse="/")
  path = paste('api', 'v4', resource, sep='/')
  amcat.getpages(conn, path, ...)
}

#' Internal call to check GET results and parse as csv or json
.amcat.readoutput <- function(result, format){
  if (result == '401 Unauthorized')
    stop("401 Unauthorized")
  if (format == 'json') {
    result = fromJSON(result)
    
  } else  if (format == 'csv') {
    con <- textConnection(result)
    result = tryCatch(read.csv(con), 
                      error=function(e) data.frame())
  }
  result
}

#' Run an action from the AmCAT API
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param action the name of the action
#' @param format the format to request, e.g. csv or json
#' @param ... any additional (e.g. action-specific) arguments to pass to the action API
#' @return A dataframe containing the result of the action [WvA: shouldn't that depend on the action??]
#' @export
amcat.runaction <- function(conn, action, format='csv', ...) {
  resource = 'api/action'
  url = paste(conn$host, resource, action, sep="/")
  url = paste(url, '?format=', format, sep="")
  message("Running action at ", url)
  httpheader = c(Authorization=paste("Token", conn$token))
  result = postForm(url, ..., .opts=list(httpheader=httpheader))
  
  if (result == '401 Unauthorized')
    stop("401 Unauthorized")
  if (format == 'json') {
    result = fromJSON(result)
  } else  if (format == 'csv') {
    con <- textConnection(result)
    result = read.csv2(con)
  }
  result
}

#' Get article metadata from AmCAT
#'
#' Uses the \code{\link{amcat.getobjects}} function to retrieve article metadata, and applies some
#' additional postprocessing, e.g. to convert the data to Date objects.
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param set the article set id to retrieve
#' @param filters additional filters, e.g. list(medium=1)
#' @param columns the names of columns to retrieve
#' @param time if true, parse the date as POSIXct datetime instead of Date
#' @param dateparts if true, add date parts (year, month, week)
#' @param medium_names if true, retrieve medium names and turn medium column into a factor
#' @param ... additional arguments are passed to \code{\link{amcat.getpages}}. Useful arguments include page_size, page (starting page) and maxpage (end page)
#' @return A dataframe containing the articles and the selected columns
#' @export
amcat.getarticlemeta <- function(conn, set, filters=list(), columns=c('id','date','medium','length'), time=F, dateparts=F, medium_names=T, ...){
  filters[['articleset']] = set 
  result = amcat.getobjects(conn, "articlemeta", filters=filters, ...)
  if(length(columns > 0)) result = result[,columns]
  if ("date" %in% names(result)) {
    result$date = (if(time == T) as.POSIXct(result$date, format='%Y-%m-%d %H:%M:%S') 
                   else as.Date(result$date, format='%Y-%m-%d'))
  }
  if (dateparts) {
    result$year = as.Date(format(result$date, '%Y-1-1'))
    result$month = as.Date(format(result$date, '%Y-%m-1'))
    result$week = as.Date(paste(format(result$date, '%Y-%W'),1), '%Y-%W %u')
  }
  if (medium_names) {
    media = unique(result$medium)
    # make filter from names by adding names (pk=)
    names(media) = rep("pk", length(media))
    media = amcat.getobjects(conn, "medium", filters=media)
    result$medium = factor(result$medium, levels=media$id, labels=media$name)
  }
  return(result)
}


#' Add articles to an article set
#' 
#' Add the given article ids to a new or existing article set
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param project the project to add the articles to
#' @param articles a vector of article ids
#' @param articleset the article set id of an existing set
#' @param articleset.name the name for a new article set
#' @param articleset.provenance a provenance text for a new article set
#' @return The articleset id of the new or existing article set
#' @export
amcat.add.articles.to.set <- function(conn, project, articles, articleset=NULL,
                                      articleset.name=NULL, articleset.provenance=NULL) {
  if (is.null(articleset)) {
    if (is.null(articleset.name)) 
      stop("Provide articleset or articleset.name")
    path = paste("api", "v4", "projects",project, "articlesets", "?format=json", sep="/")
    if (is.null(articleset.provenance)) 
      articleset.provenance=paste("Uploaded", length(articles), "articles from R on", format(Sys.time(), "%FT%T"))
    r = amcat.getURL(conn, path, filters=list(name=articleset.name, provenance=articleset.provenance), post=TRUE) 
    
    articleset = fromJSON(r)$id
    message("Created articleset ", articleset, ": ", articleset.name," in project ", project)
  }
  if (!is.null(articles)) {
    idlist = lapply(articles, function(x) list(id=x))
    url = paste(conn$host, "api", "v4", "projects",project, "articlesets", articleset, "articles", "", sep="/")
    
    resp = POST(url, body=toJSON(idlist), content_type_json(), accept_json(), add_headers(Authorization=paste("Token", conn$token)))
    if (resp$status_code != 201) stop("Unexpected status: ", resp$status_code, "\n", content(resp, type="text/plain"))
    content(resp)
  }
  articleset
}

#' Upload new articles to AmCAT
#' 
#' Upload articles into a given project and article set, or into a new article set if the articleset argument is character
#' All arguments headline, medium etc. should be either of the same length as text, or of length 1
#' All factor arguments will be converted to character using as.character
#' For date, please provide either a string in ISO notatoin (i.e. "2010-12-31" or "2010-12-31T23:59:00")
#' or a variable that can be converted to string using format(), e.g. Date, POSIXct or POSIXlt. 
#' The articles will be uploaded in batches of 100. 
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param project the project to add the articles to
#' @param articleset the article set id of an existing set, or the name of a new set to create
#' @param text the text of the articles to upload
#' @param headline the headlines of the articles to upload
#' @param medium the medium of the articles to upload. 
#' @param provenance if articleset is character, an optional provenance string to store with the new set
#' @param ... and additional fields to upload, e.g. author, byline etc. 
#' @export
amcat.upload.articles <- function(conn, project, articleset, text, headline, date, medium, provenance=NULL, ...) {
  
  n = length(text)
  if (is.character(articleset)) {
    if (is.null(provenance)) provenance=paste("Uploaded", n, "articles using R function amcat.upload.articles")
    articleset = amcat.add.articles.to.set(conn, project, articles=NULL, articleset.name=articleset, articleset.provenance=provenance) 
  }
  
  if (is.factor(date)) date=as.character(date)
  if (!is.character(date)) date = format(date, "%Y-%m-%dT%H:%M:%S")
  fields = data.frame(headline=headline, text=text, date=date, medium=medium, ...)
  # make sure all fields have correct length
  for (f in names(fields)) {
    if (is.factor(fields[[f]])) fields[[f]] = as.character(fields[[f]])
    if (length(fields[[f]]) == 1) fields[[f]] = rep(fields[[f]], n)
    if (length(fields[[f]]) != n) stop(paste("Field", f, "has incorrect length:", length(fields[[f]]), "should be 1 or ", n))
  }
  
  # not very efficient, but probably not the bottleneck
  chunks = split(fields, ceiling((1:n)/100))
  for(chunk in chunks) {
    json_data = vector("list", nrow(chunk))
    for (i in seq_along(json_data)) {
      json_data[[i]] = unlist(lapply(chunk, function(x) x[i]))
    }
    json_data = toJSON(json_data)
    message("Uploading ", nrow(chunk), " articles to set ", articleset)
    
    url = paste(conn$host, "api", "v4", "projects",project, "articlesets", articleset, "articles", "", sep="/")
    
    resp = POST(url, body=json_data, content_type_json(), accept_json(), add_headers(Authorization=paste("Token", conn$token)))
    if (resp$status_code != 201) stop("Unexpected status: ", resp$status_code, "\n", content(resp, type="text/plain"))
  }
  invisible(articleset)
}
theme_ggEHD = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title=element_text(vjust=0.3),
		...
	))
}REBOL [
	Title:   "Information extractor from Red runtime source code"
	Author:  "Nenad Rakocevic"
	File: 	 %extractor.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Notes: {
		These utility functions extract types ID and function definitions from Red
		runtime source code and make it available to the compiler, before the Red runtime
		is actually compiled.
		
		This procedure is required during bootstrapping, as the REBOL compiler can't
		examine loaded Red data in memory at runtime.
	}
]

context [
	definitions: make block! 100
	data: load-cache %runtime/macros.reds
	
	extract-defs: func [type [word!] /local list index][
		list: select data type
		
		index: 0
		forall list [
			if set-word? list/1 [
				list/1: to word! list/1
				index: list/2
			]
			if word? list/1 [
				repend definitions [list/1 index]
				index: index + 1
			]
		]
	]
	
	extract-defs 'datatypes!
	extract-defs 'actions!
	extract-defs 'natives!
	
	data: none
	
	scalars: context [typeset!: block!]					;-- fake a convenient definition
	scalars: make scalars copy skip load-cache %environment/scalars.red 2
]#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/",
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#'
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    if (is.element('output', names(object))) {
      if (is.element("data", names(object$output$options))) {
        data_restore_on_exit <- object$output$options$data
        on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
        object$output$options$data <- NULL
      }
      if (is.element("label", names(object$output$options))) {
        label_restore_on_exit <- object$output$options$label
        on.exit(object$output$options$label <- label_restore_on_exit, add = TRUE)
        object$output$options$label <- NULL
      }
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/",
    # or wants to overwrite an already existing file by providing an option,
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource, safe = opts$safe)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

 # TODO: (RK) Read default_options in from config, so a user can
 # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- list(data = switch(1 + is.element("data", names(object$output$options)),
                              NULL, object$output$options$data),
                label = switch(1 + is.element("label", names(object$output$options)),
                               NULL, object$output$options$label))

    # If the user provided an s3 path, like "s3://somebucket/some/path/",
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) {
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
#library("teradataR")
library("RODBC")
library("dplyr")
library("assertthat")


#con <- tdConnect(dsn, uid = uid, pwd = pwd, database = database)
#a <- td.data.frame(test_table)
# tdQuery('select count(*) from udparm.ao_sovn')

#td.stats(a, "Delinquency")
#tdClose()

#a1 <- as.td.data.frame(a, tableName = "ao_sovn2", database = "udparm")

st <- src_teradata(dsn = dsn, uid = uid, pwd = pwd)
a <- tbl(st, "airlines")
dim(a)
collect(a)
collapse(a)
compute(a)

a1 <- filter(a, carrier == "AA")
collect(a1)
collapse(a1)
compute(a1)
dim(a1)

# library('teradataR') library('RODBC') library('dplyr') library(data.table) library('assertthat')

# DBI for ODBC Create an ephemeral in-memory RSQLite database
#' td.table - a R reference to Teradata table
td.table <- function(con, table, database = "") {
  if (missing(database) || is.null(database) || nchar(database) == 0) {
    obj <- gettextf("\"%s\"", table)
  } else obj <- gettextf("\"%s\".\"%s\"", database, table)
  query <- gettextf("SELECT * FROM %s SAMPLE 0", obj)
  res <- try(sqlQuery(con, query))
  if (is.null(attr(res, "class"))) {
    res <- data.table()
    attr(res, "totalRows") <- 0
    warning("Teradata table not found.  Result is empty data frame.")
  } else {
    query <- sprintf("SELECT CAST(COUNT(*) AS FLOAT) FROM %s", obj)
    res2 <- try(sqlQuery(con, query))
    attr(res, "totalRows") <- as.numeric(res2)
  }
  attr(res, "class") <- "td.table"
  attr(res, "tableName") <- table
  if (!is.null(database) && !missing(database) && nchar(database) > 0) {
    attr(res, "database") <- database
  } else {
    res2 <- try(sqlQuery(con, "SELECT DATABASE"))
    if (!is.null(attr(res2, "class"))) 
      attr(res, "database") <- as.character(res2[[1]])
  }
  return(res)
}

#' A src_teradata based on ODBC
#' @import RODBC
#' @export
#' @example
#' src_teradata(host = dsn, user = uid, password = pwd)
src_teradata <- function(dsn = NULL, database = NULL, uid = NULL, pwd = NULL, port = NULL, ...) {
  tdConnection <- NULL
  # code adapted from teradataR's tdConnect function
  st <- paste0("DSN=", dsn)
  if (nchar(uid)) 
    st <- paste0(st, ";UID=", uid)
  if (nchar(pwd)) 
    st <- paste0(st, ";PWD=", pwd)
  if (nchar(database)) 
    st <- paste0(st, ";Database=", database)
  tdConnection <- odbcDriverConnect(st, ...)
  
  src <- src_sql("teradata", tdConnection, database = database)
  # By default the source of the connection is RODBC need to add a class
  class(src$con) <- c("RODBC.teradata", class(src$con))
  src
}

#' @export
src_desc.src_teradata <- function(xx) {
  x <- xx[[1]]
  # code adapted from print.odbc of the RODBC package
  con <- strsplit(attr(x, "connection.string"), ";", fixed = TRUE)[[1L]]
  case <- paste("case=", attr(x, "case"), sep = "")
  cat("Teradata RODBC Connection ", as.vector(x), "\nDetails:\n  ", sep = "")
  cat(case, con, sep = "\n  ")
  invisible(x)
}

#' @export
db_list_tables.RODBC.teradata <- function(con) {
  sqlTables(con)
}

#' @export
db_has_table.RODBC.teradata <- function(con, table) {
  tmp <- sqlTables(con)$TABLE_NAME
  table %in% tmp
}

src_translate_env.src_teradata <- function(x) {
  # src_translate_env.tbl_sql(x)
  sql_variant(base_scalar, base_agg)
}

sql_escape_ident.RODBC.teradata <- function(con, x) {
  sql_quote(x, "\"")
}


#' @export
tbl.src_teradata <- function(src, from, ...) {
  tbl_sql("teradata", src = src, from = from, ...)
}


db_query_fields.RODBC.teradata <- function(con, sql, ...) {
  RODBC::sqlColumns(con, sql, ...)$COLUMN_NAME
}

sql_select.RODBC.teradata <- dplyr:::sql_select.DBIConnection

query.RODBC.teradata <- function(con, sql, .vars) {
  # return an object with embedded functions
  
  #browser()
  Teradata.Query$new(con, sql, .vars)
  # warning('This will return the whole table') sqlQuery(con,sql)
}

# funciton taken from dplyr
sql_subquery.RODBC.teradata <- function(con, sql, name = unique_name(), ...) {
  if (is.ident(sql)) 
    return(sql)
  build_sql("(", sql, ") AS ", ident(name), con = con)
}

tbl_vars.tbl_teradata <- function(x) {
  as.character(x$select)
}


#' This suffers from obvious performance issues. Not recommended for large datasets
#' @import assertthat
copy_to.src_teradata <- function(dest, df, name = deparse(substitute(df)), database = dest$database, ...) {
  warning("The copy_to function for Teradata suffers from performance issues. If you need to upload large data to Teradata you are highly recommended to use the standard tools that Teradata provides")
  # dest is expected to have a $con which should be the output of src_teradata ZJ: worry about the dest part later as I need to totally rip up
  # the teradataR to do that
  assert_that(is.data.frame(df), is.string(name))
  
  x <- df
  # the below code is adapted from tdSave of the teradataR package tdSave(df, name)
  if (inherits(x, "td.data.frame") | inherits(x, "td.table")) {
    return(x)
  } else if (inherits(x, "data.frame")) {
    tablename <- name
    if (nchar(tablename) > 0) 
      tbl <- tablename else tbl <- deparse(substitute(x))
    if ("RODBC.teradata" %in% class(dest$con)) {
      # drop the table first if it already exists
      if (db_has_table(dest$con, tbl)) {
        if (nchar(database)) 
          sqlQuery(dest$con, sprintf("drop table %s.%s", database, tbl)) else sqlQuery(dest$con, sprintf("drop table %s", tbl))
      }
      
      # zJ: it would be disaster if the nrows is large and the first column has only a few values aim to have each column on less than 10k
      # manually create a id
      if (any(table(x[[1]]) > 10000)) {
        x <- cbind(rep(1:(nrow(x)/10000), length.out = nrow(x)), x)
      }
      
      if (nchar(database)) 
        sqlSave(dest$con, x, tablename = paste0(database, ".", tbl)) else sqlSave(dest$con, x, tablename = tbl)
      
      return(td.table(dest$con, table = tbl, database))
    }
  }
} 


db_save_query.RODBC.teradata <- function (con, sql, name, temporary = TRUE, ...) {
  tt_sql <- build_sql("CREATE ", if (temporary) 
    sql("MULTISET VOLATILE "), "TABLE ", ident(name), " AS (", sql, ") with data on commit preserve rows",
    con = con)
  res <- sqlQuery(con, tt_sql)
  name
}
getPage2Plots = function(updateProgress = NULL,cancer, gene, sampleSelection) {
  
  if (gene == "")
  {
    return()
  }
  if (is.null(gene))
  {
    return()
  }
  
	if (sampleSelection == 1) {
		#priorDetails = tcgaResults[[cancer]]$prioritize.details
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = tcga.cna[[cancer]][[1]]
		acgh.group2 = tcga.mn.cna[[cancer]][[1]]
		achilles.ut = tcgaResultsAT[[cancer]][2]
		achilles.lt = tcgaResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#56B4E9")
		lab.group1="Tumors" 
		lab.group2="Normals"
		pvalue=TRUE
		cls = tcgaResults[[cancer]]$cls
	} else if (sampleSelection == 2) {
	  #priorDetails = ccleResults[[cancer]]$prioritize.details
		priorDetails = ccleResultsPrioDetails[[cancer]]
		exprs.group1 = ccle.exprs.combat[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = ccle.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.mn.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#009E73", "#56B4E9")
		lab.group1="Cell lines" 
		lab.group2="Normals"
		pvalue=TRUE
		cls = ccleResults[[cancer]]$cls
	} else {
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs.combat[[cancer]][[1]]
		exprs.group2 = ccle.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth.combat[[cancer]]
		#meth.group2 = tcga.mn.meth.combat[[cancer]]
		acgh.group1 = tcga.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#009E73")
		lab.group1="Tumors" 
		lab.group2="Cell lines"
		pvalue=FALSE
		cls = tcgaResults[[cancer]]$cls
	}
	#meth.anno = infinium450.probe.ann
  if (is.element(gene,rownames(achilles)))
  {
   achls = achilles[gene, cls]    
  }else{
    achls = NULL
  }
	#achls = achilles
	
	plots = plotGene(gene, priorDetails, samples=NULL, 
		 	 exprs.group1, exprs.group2, 
		 	 #meth.group1, meth.group2, meth.anno, 
		 	 acgh.group1, acgh.group2, 
		 	 achls, achilles.ut, achilles.lt, 
		 	 lab.group1=lab.group1, lab.group2=lab.group2, 
		 	 color.palette=color.palette,
		 	 size=4, width=0.2, pvalue=pvalue)
# 	if (sampleSelection != 1) {
# 		plots[["methylation"]] = NULL
# 	}
	if (sampleSelection == 3) {
		plots[["achilles"]] = NULL
	}
	
	plots
}
.onAttach <- function(...) {
  if (!isTRUE(getOption("syberia.silent"))) {
    packageStartupMessage(paste0("Loading ", director:::colourise('Syberia', 'red'), "...\n"))
  }
  print(getwd())
  # TODO: (RK) Find syberia project off getwd() and call syberia_project().
}

.onAttach <- function(...) {
  if (!isTRUE(getOption("syberia.silent"))) {
    packageStartupMessage(paste0("Loading ", director:::colourise('Syberia', 'red'), "...\n"))
  }
  browser()
  # TODO: (RK) Find syberia project off getwd() and call syberia_project().
}


#' Cast data.frame to sparse matrix
#' 
#' Create a sparse matrix from matching vectors of row indices, column indices and values
#' 
#' @param rows a vector of row indices: [i,]
#' @param columns a vector of column indices: [,j]
#' @param values a vector of the values for each (non-zero) cell: [i,j] = value
#' @return a sparse matrix of the dgTMatrix class (\code{\link{Matrix}} package) 
#' @export
cast.sparse.matrix <- function(rows, columns, values=NULL) {
  if(is.null(values)) values = rep(1, length(rows))
  d = data.frame(rows=rows, columns=columns, values=values)
  if(nrow(d) > nrow(unique(d[,c('rows','columns')]))){
    message('(Duplicate row-column matches occured. Values of duplicates are added up)')
    d = aggregate(values ~ rows + columns, d, FUN='sum')
  }
  unit_index = unique(d$rows)
  char_index = unique(d$columns)
  sm = spMatrix(nrow=length(unit_index), ncol=length(char_index),
                match(d$rows, unit_index), match(d$columns, char_index), d$values)
  rownames(sm) = unit_index
  colnames(sm) = char_index
  sm
}

#' Create a document term matrix from a list of tokens
#' 
#' Create a \code{\link{DocumentTermMatrix}} from a list of document ids, terms, and frequencies. 
#' 
#' @param documents a vector of document names/ids
#' @param terms a vector of words of the same length as documents
#' @param freqs a vector of the frequency a a term in a document
#' @return a document-term matrix  \code{\link{DocumentTermMatrix}}
#' @export
dtm.create <- function(documents, terms, freqs=rep(1, length(documents))) {
  # remove NA terms
  d = data.frame(ids=documents, terms=terms, freqs=freqs)
  if (sum(is.na(d$terms)) > 0) {
    warning("Removing ", sum(is.na(d$terms)), "rows with missing term names")
    d = d[!is.na(d$terms), ]
  }
  sparsemat = cast.sparse.matrix(rows=d$ids, columns=d$terms, values=d$freqs)
  as.DocumentTermMatrix(sparsemat, weighting=weightTf)
}

#' Compute some useful corpus statistics for a dtm
#' 
#' Compute a number of useful statistics for filtering words: term frequency, idf, etc.
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
term.statistics <- function(dtm) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]    # get rid of empty rows/columns
  vocabulary = colnames(dtm)
  data.frame(term = vocabulary,
             characters = nchar(vocabulary),
             number = grepl("[0-9]", vocabulary),
             nonalpha = grepl("\\W", vocabulary),
             termfreq = col_sums(dtm),
             docfreq = col_sums(dtm > 0),
             reldocfreq = col_sums(dtm > 0) / nDocs(dtm),
             tfidf = tapply(dtm$v/row_sums(dtm)[dtm$i], dtm$j, mean) * log2(nDocs(dtm)/col_sums(dtm > 0)))
}

#' Compute the chi^2 statistic for a 2x2 crosstab containing the values
#' [[a, b], [c, d]]
chi2 <- function(a,b,c,d) {
  ooe <- function(o, e) {(o-e)*(o-e) / e}
  tot = 0.0 + a+b+c+d
  a = as.numeric(a)
  b = as.numeric(b)
  c = as.numeric(c)
  d = as.numeric(d)
  (ooe(a, (a+c)*(a+b)/tot)
   +  ooe(b, (b+d)*(a+b)/tot)
   +  ooe(c, (a+c)*(c+d)/tot)
   +  ooe(d, (d+b)*(c+d)/tot))
}

#' Compare two corpora
#' 
#' Compare the term use in corpus dtm with a refernece corpus dtm.ref, returning relative frequencies
#' and overrepresentation using various measures
#' 
#' @param dtm.x the main document-term matrix
#' @param dtm.y the 'reference' document-term matrix
#' @param smooth the smoothing parameter for computing overrepresentation
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
corpora.compare <- function(dtm.x, dtm.y, smooth=.001) {
  freqs = term.statistics(dtm.x)[, c("term", "termfreq")]
  freqs.rel = term.statistics(dtm.y)[, c("term", "termfreq")]
  f = merge(freqs, freqs.rel, all=T, by="term")    
  f[is.na(f)] = 0
  f$relfreq.x = f$termfreq.x / sum(freqs$termfreq)
  f$relfreq.y = f$termfreq.y / sum(freqs.rel$termfreq)
  f$over = (f$relfreq.x + smooth) / (f$relfreq.y + smooth)
  f$chi = chi2(f$termfreq.x, f$termfreq.y, sum(f$termfreq.x) - f$termfreq.x, sum(f$termfreq.y) - f$termfreq.y)
  f
}

#' Plot a word cloud from a dtm
#' 
#' Compute the term frequencies for the dtm and plot a word cloud with the top n topics
#' You can either supply a document-term matrix or provide terms and freqs directly
#' (in which case this is an alias for wordcloud::wordcloud with sensible defaults)
#' 
#' @param dtm the document-term matrix
#' @param nterms the amount of words to plot (default 100)
#' @param freq.fun if given, will be applied to the frequenies (e.g. sqrt)
#' @param terms the terms to plot, ignored if dtm is given
#' @param freqs the frequencies to plot, ignored if dtm is given
#' @param scale the scale to plot (see wordcloud::wordcloud)
#' @param min.freq the minimum frquency to include (see wordcloud::wordcloud)
#' @param rot.per the percentage of vertical words (see wordcloud::wordcloud)
#' @param pal the colour model, see RColorBrewer
#' @export
dtm.wordcloud <- function(dtm=NULL, nterms=100, freq.fun=NULL, terms=NULL, freqs=NULL, scale=c(6, .5), min.freq=1, rot.per=.15, pal=brewer.pal(6,"YlGnBu")) {
  if (!is.null(dtm)) {
    t = term.statistics(dtm)
    t = t[order(t$termfreq, decreasing=T), ]
    terms = t$term
    freqs = t$termfreq
  }
  if (!is.null(freq.fun)) freqs = freq.fun(freqs)
  if (!is.null(nterms)) {
    select = order(-freqs)[1:nterms]
    terms = terms[select] 
    freqs = freqs[select]
  }
   
  if (is.null(terms) | is.null(freqs)) stop("Please provide dtm or terms and freqs")
  wordcloud(terms, freqs, 
          scale=scale, min.freq=min.freq, max.words=Inf, random.order=FALSE, 
          rot.per=rot.per, colors=pal)
}REBOL [
    Title:   "Builds a set of Red & Red/System Tests to run on an ARM host"
	File: 	 %build-arm-tests.r
	Author:  "Peter W A Wood"
	Version: 0.2.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; This script must be run from the Red/red/tests dir

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

;; use win-call if running Rebol 2.7.8 under Windows
if all [
    system/version/4 = 3
    system/version/3 = 8              
][
		do %../quick-test/call.r					               
		set 'call :win-call
]

;; process arguments (if any)
target: none
if system/script/args  [
    target: second parse system/script/args " "
	if not any [
	    target = "Linux"
	    target = "Android"
	    target = "RPi"
	    target = "Darwin"
	][
	    target: none
	]
]

;; if no target supplied, ask the user
unless target [
    target: ask {
        Choose ARM target:
        1) Linux
        2) Android
        3) Linux armhf
        => }
    target: pick ["Linux-ARM" "Android" "RPi"] to-integer target
]

;; make the Arm dir if needed
arm-dir: clean-path %../quick-test/runnable/arm-tests/red/
make-dir/deep arm-dir

;; empty the Arm dir
foreach file read arm-dir [delete join arm-dir file]

;; build the test files
do %source/units/run-all-init.r

;; compile the tests into to runnable/arm-tests/red
output: copy ""
foreach file [
    "run-all-comp1.red"
    "run-all-comp2.red"
    "run-all-interp.red"
][
    print ["Compiling" file] "..." 
    test-file: join %source/units/auto-tests/ file
    exe: replace file ".red" ""
    exe: to-local-file join arm-dir exe
    cmd: join "" [  to-local-file system/options/boot " -sc "
        to-local-file clean-path %../red.r
        " -t " target " -o " exe " "
    	to-local-file test-file	
    ]
    clear output
    call/output cmd output
    print output
]

;; copy the bash script and mark it as executable
runner: arm-dir/run-all.sh
write/binary runner trim/with read/binary %run-all.sh "^M"
if system/version/4 <> 3 [
	set-modes runner [
	  owner-execute: true
	  group-execute: true
	  world-execute: true
	]
]

;; tidy up
system/options/quiet: store-quiet-mode

print ["Red/System ARM tests built in" arm-dir]  
REBOL [
	Title:   "Builds and Runs All Red and Red/System Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.3.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; function to find and run-tests
run-all-script: func [
	dir [file!]
	file [file!]
][
	qt/tests-dir: system/script/path/:dir
  	foreach line read/lines dir/:file [
  		if any [
			find line "===start-group"
  	  		find line "--run-"
  		][
  			do line
  		]
  	]
]

batch-mode: false
each-mode: false
binary?: false
args: any [system/script/args system/options/args]
if args  [
	;; should we run non-interactively?
	batch-mode: find system/script/args "--batch"
	
	;; should we run each file individually?
	each-mode: find system/script/args "--each"

	;; should we use the binary compiler?
	args: parse system/script/args " "
	if find system/script/args "--binary" [
		binary?: true
		bin-compiler: select args "--binary"
		if any [
			bin-compiler = "--batch"
			bin-complier = "--each"
		][
			bin-compiler: none								;; use default
		]
		if bin-compiler [						
			if not attempt [exists? to file! bin-compiler] [
				either batch-mode [
					write %quick-test/quick-test.log "Invalid compiler path"
					quit/return 1
				][
					print "Invalid compiler path supplied"
					print args
					print ""
					halt
				]
			]
		]
	
	]
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true
store-current-dir: what-dir

do %quick-test/quick-test.r
qt/tests-dir: clean-path %/tests/

if binary? [
	qt/binary?: binary?
	if bin-compiler [qt/bin-compiler: bin-compiler]
]

qt/tests-dir: clean-path %system/tests/
do %system/tests/source/units/make-red-system-auto-tests.r

qt/tests-dir: clean-path %tests/
do %tests/source/units/run-all-init.r

;; run the tests
print rejoin ["Quick-Test v" qt/version]
print rejoin ["REBOL " system/version]

start-time: now/precise

***start-run-quiet*** "Complete Red Test Suite"

do %tests/source/units/run-all-extra-tests.r

either each-mode [
    do %tests/source/units/auto-tests/run-each-comp.r
    do %tests/source/units/auto-tests/run-each-interp.r
][
    --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
    --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
    --run-test-file-quiet %source/units/auto-tests/run-all-interp.red    
]
qt/script-header: "Red/System []"
qt/tests-dir: clean-path %system/tests/ 
run-all-script %system/tests/ %run-all.r

***end-run-quiet***

end-time: now/precise
print ["       in" difference end-time start-time newline]
system/options/quiet: store-quiet-mode
either batch-mode [
	quit/return either qt/test-run/failures > 0 [1] [0]
][
	print ["The test output was logged to" qt/log-file]
	ask "hit enter to finish"
	print ""
	qt/test-run/failures
]
# Function 'NormMax'
# Killian Martin--Horgassan
# 19-02-2015

# Generates the list of maxima [M_1, ..., M_n] of the list of
# i.i.d random variables [X_1,...,X_n]. Plots the M_i against 
# the i.

# Arguments :
# - N     : number of r.v. X_i
# - DIST  : a vector of N pseudo-random numbers from a certain 
#			distribution.
# RETURNS the list of maxima

NormMax <- function(N = 10000, DIST = rnorm(10000,0,1)) {
 	ListX   <- DIST
 	ListMax <- rep(0,N)
 	
 	# Computes the list of the M_i
 	for (i in 1:length(ListMax)) {
 		ListMax[i] <- max(ListX[1:i])
 	}
 	
 	# Plots the 1-D scatter plot of the M_i
 	title_1 <- "1-D scatter plot of the maxima"
 	xlabel_1 <- expression(M[i])
 	stripchart(ListMax, xlab = xlabel_1, main = title_1)
 	
 	# Opens a new graphic window
 	quartz()
 	
 	# Plots the M_i against the i
 	title_2 <- "Maxima as a function of the time steps"
 	xlabel_2 <- "Time step"
 	ylabel_2 <- "Maximum"
 	plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =
 			title_2)
 	
 	# Opens a new graphic windows
 	quartz()
 	
 	# Plot the 1-D scatter plot of the M_i and the M_i against the
 	# i together in a grid.
 	par(mfrow = c(1,2))
 	
 	stripchart(ListMax, xlab = xlabel_1, main = title_1)
    plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =
 			title_2, pch = 4)
 	points(1:N,sqrt(log(1:N)),col="cyan", pch = 3)
 	legend(x="bottomright",y=NULL,c("Maxima",
 		expression("sqrt(log(n))")), col = c("black","cyan"),
 		bty="o", pch = c(4,3))
 		
 	# Exports the plots to a PDF file
 	pdf(file = "graphIntroTask.pdf", width = 10, height = 8)
	par(mfrow = c(1,2))
 	stripchart(ListMax, xlab = xlabel_1, main = title_1)
    plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =
 			title_2, pch = 4)
 	points(1:N,sqrt(log(1:N)),col="cyan", pch = 3)
 	legend(x="bottomright",y=NULL,c("Maxima",
 		expression("sqrt(log(n))")), col = c("black","cyan"),
 		bty="o", pch = c(4,3))
 	dev.off()
 	
 	return(ListMax)
 }REBOL [
  Title:   "Simple testing framework for Red and Red/System programs"
	Author:  "Peter W A Wood"
	File: 	 %quick-test.r
	Version: 0.12.0
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

comment {
	This script makes some assumptions about the directory structure in which 
	files are stored. They are:
    	this script is stored in Red/quick-test/
    	the Red & Red/System compiler is stored in Red/
    	the default dir for tests is Red/system/tests/
    	
    	The default test dirs can be overriden by setting qt/tests-dir before
    	tests are processed
    	The default script header for code supplied as string is Red [], this 
    	can be overriden by setting qt/script-header
    	The default location of the compiler binary is Red/build/bin, this can
    	be overriden by setting qt/bin-compiler
}

qt: make object! [
  
  ;;;;;;;;;;; Setup ;;;;;;;;;;;;;;
  ;; set the base-dir to ....Red/
  base-dir: system/script/path
  base-dir: copy/part base-dir find base-dir "quick-test"
  ;; set the red/system runnable dir
  runnable-dir: dirize base-dir/quick-test/runnable
  ;; set the default base dir for tests
  tests-dir: dirize base-dir/system/tests
  
  ;; set the version number
  version: system/script/header/version
  
  ;; switch for binary compiler usage
  binary?: false

  ;; check if call-show? is enabled for call
  either any [
  		not value? 'call-show?
  		equal? call-show? 'wait
  	] [call-show?: 'wait] [call-show?: 'show]
  call*: to path! 'call
  append call* :call-show?
  append call* 'output
  
  ;; default binary compiler path
  bin-compiler: base-dir/build/bin/red
  
  ;; default script header to be inserted into code supplied in string form
  script-header: "Red []"
  
  ;; set temporary files names
  ;;  use Red/quick-test/runnable for temp files
  comp-echo: runnable-dir/comp-echo.txt
  comp-r: runnable-dir/comp.r
  test-src-file: runnable-dir/qt-test-comp.red
  
  ;; set log file 
  log-file: join system/script/path "quick-test.log"

  ;; make runnable directory if needed
  make-dir runnable-dir
  
  ;; windows ?
  windows-os?: system/version/4 = 3
  
  ;; use Cheyenne call with REBOL v2.7.8 on Windows (re: 'call bug on Windows 7)
  if all [
    windows-os?
    system/version/3 = 8              
  ][
		do %call.r					               
		set 'call :win-call
	]
	
	;; script header parse rules - assumes parsing without /all
	red?: false
	red-header: ["red" any " " "[" to end (red?: true)]
	red-system-header: ["red/system" any " " "[" to end (red?: false)]
	red?-rule: [(red?: false) any [red-system-header | red-header | skip]]
	script-header-rule: [
		(no-script-header?: true) 
		any [ 
				[["red/system" | "red"] any " " "[" (no-script-header?: false)]
			|
				skip
		]
	]

	;;;;;;;;; End Setup ;;;;;;;;;;;;;;
  
  comp-output: copy ""                 ;; output captured from compile
  output: copy ""                      ;; output captured from pgm exec
  exe: none                            ;; filepath to executable
  source-file?: true                   ;; true = running  test file
                                       ;; false = runnning test script
				  

  summary-template: ".. - .................................................. / "
  
  data: make object! [
    title: copy ""
    no-tests: 0
    no-asserts: 0
    passes: 0
    failures: 0
    reset: does [
      title: copy ""
      no-tests: 0
      no-asserts: 0
      passes: 0
      failures: 0
    ]
  ]
  
  file: make data []
  test-run: make data []
  _add-file-to-run-totals: does [
    test-run/no-tests: test-run/no-tests + file/no-tests
    test-run/no-asserts: test-run/no-asserts + file/no-asserts
    test-run/passes: test-run/passes + file/passes
    test-run/failures: test-run/failures + file/failures
  ]
  _signify-failure: does [
    ;; called when a compiler or runtime error occurs
    file/failures: file/failures + 1           
    file/no-tests: file/no-tests + 1
    file/no-asserts: file/no-asserts + 1
    test-run/failures: test-run/failures + 1           
    test-run/no-tests: test-run/no-tests + 1
    test-run/no-asserts: test-run/no-asserts + 1
  ]
  
  ;; group data
  group-name: copy ""
  group?: false
  group-name-not-printed: true
  _init-group: does [
    group?: false
    group-name-not-printed: true
    group-name: copy ""
  ]
  
  ;; test data
  test-name: copy ""
  _init-test: does [
    test-name: copy ""
  ]
  
  ;; print diversion function
  _save-print: :print
  print-output: copy ""
  _quiet-print: func [val] [
    append print-output join "" [reduce val "^/"]
  ]
        
  	compile: func [
  		src [file!]
  		/bin
  		/lib
  	  		target [string!]	
  	  	/local
  	  		comp                          	;; compilation script
  	  		cmd                           	;; compilation cmd
  	  		exe								;; executable name
  ][
    clear comp-output
    
    ;; workout executable name
    either find/last/tail src "/" [
      exe: copy find/last/tail src "/"
    ][
      exe: copy src
    ]
    exe: copy/part exe find exe "."
    either lib [
      switch/default target [
        "Windows"	[exe: join exe [".dll"]]
        "Darwin"   	[exe: join exe [".dylib"]]
      ][
      	  exe: join exe [".so"]
      ]
      exe
    ][     
      if windows-os? [
        exe: join exe [".exe"]
      ]
    ]
    
    ;; find the path to the src
    if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    
    ;; red/system or red
    red?: false
    parse read src red?-rule
 
    ;; compose and write compilation script
    either binary? [
    	if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    	either lib [
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe
    					  " -dlib -t " target " "
    					  to-local-file src
    		]
    	][
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe " "
    					  to-local-file src	
    		]  		
    	]
    	comp-output: make string! 1024
    	do call* cmd comp-output
    ][
    	comp: mold compose/deep [
    	  REBOL []
    	  halt: :quit
    	  echo (comp-echo)
    	  do/args (reduce base-dir/red.r) (join " -o " [
    	  	  	  reduce runnable-dir/:exe " ###lib###***src***" 
    	  ])
    	]
    	either lib [
    		replace comp "###lib###" join "-dlib -t " [target " "]
    	][
    		replace comp "###lib###" ""
    	]
    
    	replace comp "***src***"  clean-path src
    	write comp-r comp

    	;; compose command line and call it
    	cmd: join to-local-file system/options/boot [" -sc " comp-r]
    	do call* cmd make string! 1024	;; redirect output to anonymous
    											;; buffer
    ]
    
    ;; collect compiler output & tidy up
    if exists? comp-echo [
    	comp-output: read comp-echo
    	delete comp-echo
    ]
    if exists? comp-r [delete comp-r]
    either compile-ok? [
      exe
    ][
      none
    ]    
  ]
  
  compile-and-run: func [src /error /pgm] [
    source-file?: true
    either exe: compile src [
      either error [
        run/error  exe
      ][
      	  either pgm [
      	  	  run/pgm exe
      	  ][
      	  	  run exe
      	  ]
      ]
    ][
      compile-error src
      output: "Compilation failed"
    ]
  ]
    
  compile-and-run-from-string: func [src /error] [
    source-file?: false
    either exe: compile-from-string src [
      either error [
        run/error  exe
      ][
        run exe
      ]
    ][
      
      compile-error "Supplied source"
      output: "Compilation failed"
    ]
  ]
  
  compile-dll: func [
    lib-src [file!]
    target	[string!]
    /local
    	dll
  ][
    ;; compile the lib into the runnable dir
    if not dll: compile/lib lib-src target [
      compile-error lib-src
      output: "Lib compilation failed"  
    ]
    dll
  ]
  
  compile-from-string: func [src][
    ;-- add a default header if not provided
    parse src script-header-rule
    if no-script-header? [
    	insert src join script-header "^/"
    ]
    write test-src-file src
    compile test-src-file                  ;; returns path to executable or none
  ]
  
  compile-error: func [
    src [file! string!]
  ][
    print join "^/" [src " - compiler error^/"]
    print comp-output
    print newline
    clear output                           ;; clear the output from previous test
    _signify-failure
  ]
  
  compile-ok?: func [] [
    either find comp-output "output file size :" [true] [false]
  ] 
  
  compile-run-print: func [src [file!] /error][
  	  either error [
  	  	  compile-and-run/error src
  	  ][
  	  	  compile-and-run src
    ]
    if output <> "Compilation failed" [print output]
  ]
  
  compiled?: func [
    src [string!]
  ][
    exe: compile-from-string src
    clean-compile-from-string
    qt/compile-ok?
  ]
  
  run: func [
    prog [file!]
    ;;/args                         ;; not yet needed
      ;;parms [string!]             ;; not yet needed
    /error                          ;; run time error expected
    /pgm							;; a program not a test
    /local
    exec [string!]                  ;; command to be executed
  ][
    exec: to-local-file runnable-dir/:prog
    ;;exec: join "" compose/deep [(exec either args [join " " parms] [""])]
    clear output
    do call* exec output
    if all [red? windows-os?] [output: qt/utf-16le-to-utf-8 output]
    if all [
      source-file?
      not pgm
      any [
      	  all [
      	   none <> find output "Runtime Error"
      	   not error
      	  ]
      	  none = find output "Passed"
      ]
    ][	
    print "signify failure"
      _signify-failure
    ]
  ]
  
  run-unit-test: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd make string! 1024
  ]
  
  run-unit-test-quiet: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    test-name: find/last/tail src "/"
    test-name: copy/part test-name find test-name "."
    prin [ "running " test-name #"^(0D)"]
    clear output
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd output
    if find output "Error:" [_signify-failure]
    add-to-run-totals
    write/append log-file output
    file/title: test-name
    replace file/title "-test" ""
    _print-summary file
  ]
  
  run-script: func [
    src [file!]
    /local
     filename                     ;; filename of script 
     script                       ;; %runnable/filename
  ][
    if not filename: copy find/last/tail src "/" [filename: copy src]
    script: runnable-dir/:filename
    write to file! script read join tests-dir [src]
    if error? try [do script] [_signify-failure]
  ]
  
  run-script-quiet: func [
  	src [file!]
  ][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-script src
    add-to-run-totals
    print: :_save-print
    write/append log-file print-output
    _print-summary file
  ]
  
  run-test-file: func [
  	src [file!]
  ][
    file/reset
    unless file/title: find/last/tail to string! src "/" [file/title: src]
    replace file/title "-test.reds" ""
    replace file/title "-test.red" ""
    compile-run-print src
    add-to-run-totals
  ]
  
  run-test-file-quiet: func [
  	src [file!]
  	][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-test-file src
    print: :_save-print
    write/append log-file print-output
    _print-summary file
    output: copy ""
  ]
  
  add-to-run-totals: func [
    /local
      tests
      
      asserts
      passes
      failures
      rule
      digit
      number
  ][
    digit: charset [#"0" - #"9"]
    number: [some digit]
    ws: charset [#"^-" #"^/" #" "]
    whitespace: [some ws]
    rule: [
      thru "Number of Tests Performed:" whitespace copy tests number
      thru "Number of Assertions Performed:" whitespace copy asserts number
      thru "Number of Assertions Passed:" whitespace copy passed number
      thru "Number of Assertions Failed:" whitespace copy failures number
      to end
    ]
    if parse/all output rule [
      file/no-tests: file/no-tests + to integer! tests
      file/no-asserts: file/no-asserts + to integer! asserts
      file/passes: file/passes + to integer! passed
      file/failures: file/failures + to integer! failures
      _add-file-to-run-totals
    ]
  ]
  
  _start: func [
    data [object!]
    leader [string!]
    title [string!]
  ][
    print [leader title]
    data/title: title
    data/no-tests: 0
    data/no-asserts: 0
    data/passes: 0
    data/failures: 0
    _init-group
  ]

  start-test-run: func [
    title [string!]
  ][
    _start test-run "***Starting***" title
    prin newline
  ]
  
  start-test-run-quiet: func [
    title [string!]
      ][
    _start test-run "" title
    prin newline
    write log-file rejoin ["***Starting*** " title newline]
  ]
  
  start-file: func [
    title [string!]
  ][
    _start file "~~~started test~~~" title
  ]
  
  start-group: func[
    title [string!]
  ][
   group-name: title
   group?: true
  ]
  
  start-test: func[
    title [string!]
  ][
    _init-test
    test-name: title
    file/no-tests: file/no-tests + 1
  ]
    
  assert: func [
    assertion [logic!]
  ][
    file/no-asserts: file/no-asserts + 1
    either assertion [
      file/passes: file/passes + 1
    ][
      file/failures: file/failures + 1
      if group? [
        if group-name-not-printed [
          print ""
          print ["===group===" group-name]
        ]
      ]
      print ["---test---" test-name "FAILED**************"]
    ]
  ]
  
  assert-msg?: func [msg][
    assert found? find qt/comp-output msg
  ]
  
  assert-printed?: func [msg] [
    assert found? find qt/output msg
  ]
  
  clean-compile-from-string: does [
    if exists? test-src-file [delete test-src-file]
    if all [exe exists? exe][delete exe]
]
  
  end-group: does [
    _init-group
  ]
  
  _end: func [
    data [object!]
    leader [string!]
  ][
    print [leader data/title]
    print ["No of tests  " data/no-tests]
    print ["No of asserts" data/no-asserts]
    print ["Passed       " data/passes]
    print ["Failed       " data/failures]
    if data/failures > 0 [print "***TEST FAILURES***"]
    print ""
  ]
  
  end-file: func [] [
    _end file "~~~finished test~~~" 
    _add-file-to-run-totals
  ]
  
  end-test-run: func [] [
      print ""
    _end test-run "***Finished***"
  ]
  
  end-test-run-quiet: func [] [
    print: :_quiet-print
    print-output: copy ""
    end-test-run
    print: :_save-print
    write/append log-file print-output
    prin newline
    _print-summary test-run
  ]
  
  _print-summary: func [
    data [object!]
    /local
      print-line
  ][
    print-line: copy summary-template
    print-line: skip print-line 5
    remove/part print-line length? data/title
    insert print-line data/title
    print-line: skip tail print-line negate (3 + length? mold data/passes)
    remove/part print-line length? mold data/passes
    insert print-line data/passes
    append print-line data/no-asserts
    print-line: head print-line
    either data/no-asserts = data/passes [
      replace print-line ".." "ok"
    ][
      replace/all print-line "." "*"
      append print-line " **"
    ]
    print print-line
  ]
  
  make-if-needed?: func [
    {This function is used by the Red run-all scripts to build the auto files
     when necessary.} 
    auto-test-file [file!]
    make-file [file!]
    /lib-test
    /local
      stored-length   ; the length of the make... .r file used to build auto tests
      stored-file-length
      digit
      number
      rule
  ][
    auto-test-file: join tests-dir auto-test-file
    make-file: join tests-dir make-file
    
    stored-file-length: does [
      parse/all read auto-test-file rule
      stored-length
    ]
    digit: charset [#"0" - #"9"]
    number: [some digit]
    rule: [
      thru ";make-length:" 
      copy stored-length number (stored-length: to integer! stored-length)
      to end
    ]
    
    if not exists? make-file [return]
   
    if any [
      not exists? auto-test-file
      stored-file-length <> length? read make-file
      0:00 < difference modified? make-file modified? auto-test-file
    ][
      print ["Making" auto-test-file " - it will take a while"]
      do make-file
    ]
  ]
  
  setup-temp-files: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    comp-echo: join runnable-dir ["comp-echo" f ".txt"]
  	comp-r: join runnable-dir ["comp" f ".r"]
  	test-src-file: join runnable-dir ["qt-test-comp" f ".red"]
  ]
  
  delete-temp-files: does [
  	  if exists? comp-echo [delete comp-echo]
  	  if exists? comp-r [delete comp-r]
  	  if exists? test-src-file [delete test-src-file]  
  ]
  
  seperate-log-file: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    log-file: join base-dir ["quick-test/quick-test" f ".log"]
  ]
  
  utf-16le-to-utf-8: func [
    {Translates a utf-16LE encoded string to an utf-8 encoded one
     the algorithm is copied from lexer.r                         }
    in-str [string!]
    /local
      out-str
      code
  ][
   out-str: copy ""
   foreach [low high] to binary! in-str [
     code: high * 256 + low
     case [
       code <= 127  [
         append out-str to char! code					            ;-- c <= 7Fh
       ]
       code <= 2047 [							                        ;-- c <= 07FFh
         append out-str join "" [ 
           to char! ((shift code 6) and #"^(1F)" or #"^(C0)")
					 to char! ((code and #"^(3F)") or #"^(80)")
				 ]
			 ]
			 code <= 65535 [					                         		;-- c <= FFFFh
			   append out-str join "" [
			     to char! ((shift code 12) and #"^(0F)" or #"^(E0)")
			     to char! ((shift code 6) and #"^(3F)" or #"^(80)")
			     to char! (code and #"^(3F)" or #"^(80)")
			   ]
			 ]
			 code <= 1114111 [						                        ;-- c <= 10FFFFh
			   append out-str join "" [
			     to char! ((shift code 18) & ^"(07)" or #"^(F0)")
					 to char! ((shift code 12) and #"^(3F)" or #"^(80)")
					 to char! ((shift code 6)  and #"^(3F)" or #"^(80)")
					 to char! (code and #"^(3F)" or #"^(80)")
				 ]
			 ]                         ;-- Codepoints above U+10FFFF are ignored"
		 ]
	 ]
   out-str 
  ]
  
  ;; create the test "dialect"
  
  set '***start-run***              :start-test-run
  set '***start-run-quiet***        :start-test-run-quiet
  set '~~~start-file~~~             :start-file
  set '===start-group===            :start-group
  set '--test--                     :start-test
  set '--compile                    :compile
  set '--compile-red                :compile
  set '--compile-dll          		:compile-dll
  set '--compile-this               :compile-from-string
  set '--compile-this-red           :compile-from-string
  set '--compile-and-run            :compile-and-run
  set '--compile-and-run-red        :compile-and-run 
  set '--compile-and-run-this       :compile-and-run-from-string
  set '--compile-and-run-this-red   :compile-and-run-from-string
  set '--compile-run-print          :compile-run-print
  set '--compile-run-print-red      :compile-run-print
  set '--compiled?                  :compiled?
  set '--run                        :run
  set '--add-to-run-totals          :add-to-run-totals
  set '--run-unit-test              :run-unit-test
  set '--run-unit-test-quiet        :run-unit-test-quiet
  set '--run-script                 :run-script
  set '--run-script-quiet           :run-script-quiet
  set '--run-test-file              :run-test-file
  set '--run-test-file-red          :run-test-file
  set '--run-test-file-quiet        :run-test-file-quiet
  set '--run-test-file-quiet-red    :run-test-file-quiet
  set '--assert                     :assert
  set '--assert-msg?                :assert-msg?
  set '--assert-printed?            :assert-printed?
  set '--assert-red-printed?        :assert-printed?
  set '--clean                      :clean-compile-from-string
  set '===end-group===              :end-group
  set '~~~end-file~~~               :end-file
  set '***end-run***                :end-test-run
  set '***end-run-quiet***          :end-test-run-quiet
  set '--setup-temp-files			:setup-temp-files
  set '--delete-temp-files			:delete-temp-files
  set '--seperate-log-file			:seperate-log-file	
]
REBOL [
  Title:   "Simple testing framework for Red and Red/System programs"
	Author:  "Peter W A Wood"
	File: 	 %quick-test.r
	Version: 0.12.0
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

comment {
	This script makes some assumptions about the directory structure in which 
	files are stored. They are:
    	this script is stored in Red/quick-test/
    	the Red & Red/System compiler is stored in Red/
    	the default dir for tests is Red/system/tests/
    	
    	The default test dirs can be overriden by setting qt/tests-dir before
    	tests are processed
    	The default script header for code supplied as string is Red [], this 
    	can be overriden by setting qt/script-header
    	The default location of the compiler binary is Red/build/bin, this can
    	be overriden by setting qt/bin-compiler
}

qt: make object! [
  
  ;;;;;;;;;;; Setup ;;;;;;;;;;;;;;
  ;; set the base-dir to ....Red/
  base-dir: system/script/path
  base-dir: copy/part base-dir find base-dir "quick-test"
  ;; set the red/system runnable dir
  runnable-dir: dirize base-dir/quick-test/runnable
  ;; set the default base dir for tests
  tests-dir: dirize base-dir/system/tests
  
  ;; set the version number
  version: system/script/header/version
  
  ;; switch for binary compiler usage
  binary?: false

  ;; check if call-show? is enabled for call
  either (not value? 'call-show?) [call-show?: 'wait] [call-show?: 'show]
  call*: to path! 'call
  append call* :call-show?
  append call* 'output
  
  ;; default binary compiler path
  bin-compiler: base-dir/build/bin/red
  
  ;; default script header to be inserted into code supplied in string form
  script-header: "Red []"
  
  ;; set temporary files names
  ;;  use Red/quick-test/runnable for temp files
  comp-echo: runnable-dir/comp-echo.txt
  comp-r: runnable-dir/comp.r
  test-src-file: runnable-dir/qt-test-comp.red
  
  ;; set log file 
  log-file: join system/script/path "quick-test.log"

  ;; make runnable directory if needed
  make-dir runnable-dir
  
  ;; windows ?
  windows-os?: system/version/4 = 3
  
  ;; use Cheyenne call with REBOL v2.7.8 on Windows (re: 'call bug on Windows 7)
  if all [
    windows-os?
    system/version/3 = 8              
  ][
		do %call.r					               
		set 'call :win-call
	]
	
	;; script header parse rules - assumes parsing without /all
	red?: false
	red-header: ["red" any " " "[" to end (red?: true)]
	red-system-header: ["red/system" any " " "[" to end (red?: false)]
	red?-rule: [(red?: false) any [red-system-header | red-header | skip]]
	script-header-rule: [
		(no-script-header?: true) 
		any [ 
				[["red/system" | "red"] any " " "[" (no-script-header?: false)]
			|
				skip
		]
	]

	;;;;;;;;; End Setup ;;;;;;;;;;;;;;
  
  comp-output: copy ""                 ;; output captured from compile
  output: copy ""                      ;; output captured from pgm exec
  exe: none                            ;; filepath to executable
  source-file?: true                   ;; true = running  test file
                                       ;; false = runnning test script
				  

  summary-template: ".. - .................................................. / "
  
  data: make object! [
    title: copy ""
    no-tests: 0
    no-asserts: 0
    passes: 0
    failures: 0
    reset: does [
      title: copy ""
      no-tests: 0
      no-asserts: 0
      passes: 0
      failures: 0
    ]
  ]
  
  file: make data []
  test-run: make data []
  _add-file-to-run-totals: does [
    test-run/no-tests: test-run/no-tests + file/no-tests
    test-run/no-asserts: test-run/no-asserts + file/no-asserts
    test-run/passes: test-run/passes + file/passes
    test-run/failures: test-run/failures + file/failures
  ]
  _signify-failure: does [
    ;; called when a compiler or runtime error occurs
    file/failures: file/failures + 1           
    file/no-tests: file/no-tests + 1
    file/no-asserts: file/no-asserts + 1
    test-run/failures: test-run/failures + 1           
    test-run/no-tests: test-run/no-tests + 1
    test-run/no-asserts: test-run/no-asserts + 1
  ]
  
  ;; group data
  group-name: copy ""
  group?: false
  group-name-not-printed: true
  _init-group: does [
    group?: false
    group-name-not-printed: true
    group-name: copy ""
  ]
  
  ;; test data
  test-name: copy ""
  _init-test: does [
    test-name: copy ""
  ]
  
  ;; print diversion function
  _save-print: :print
  print-output: copy ""
  _quiet-print: func [val] [
    append print-output join "" [reduce val "^/"]
  ]
        
  	compile: func [
  		src [file!]
  		/bin
  		/lib
  	  		target [string!]	
  	  	/local
  	  		comp                          	;; compilation script
  	  		cmd                           	;; compilation cmd
  	  		exe								;; executable name
  ][
    clear comp-output
    
    ;; workout executable name
    either find/last/tail src "/" [
      exe: copy find/last/tail src "/"
    ][
      exe: copy src
    ]
    exe: copy/part exe find exe "."
    either lib [
      switch/default target [
        "Windows"	[exe: join exe [".dll"]]
        "Darwin"   	[exe: join exe [".dylib"]]
      ][
      	  exe: join exe [".so"]
      ]
      exe
    ][     
      if windows-os? [
        exe: join exe [".exe"]
      ]
    ]
    
    ;; find the path to the src
    if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    
    ;; red/system or red
    red?: false
    parse read src red?-rule
 
    ;; compose and write compilation script
    either binary? [
    	if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    	either lib [
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe
    					  " -dlib -t " target " "
    					  to-local-file src
    		]
    	][
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe " "
    					  to-local-file src	
    		]  		
    	]
    	comp-output: make string! 1024
    	do call* cmd comp-output
    ][
    	comp: mold compose/deep [
    	  REBOL []
    	  halt: :quit
    	  echo (comp-echo)
    	  do/args (reduce base-dir/red.r) (join " -o " [
    	  	  	  reduce runnable-dir/:exe " ###lib###***src***" 
    	  ])
    	]
    	either lib [
    		replace comp "###lib###" join "-dlib -t " [target " "]
    	][
    		replace comp "###lib###" ""
    	]
    
    	replace comp "***src***"  clean-path src
    	write comp-r comp

    	;; compose command line and call it
    	cmd: join to-local-file system/options/boot [" -sc " comp-r]
    	do call* cmd make string! 1024	;; redirect output to anonymous
    											;; buffer
    ]
    
    ;; collect compiler output & tidy up
    if exists? comp-echo [
    	comp-output: read comp-echo
    	delete comp-echo
    ]
    if exists? comp-r [delete comp-r]
    either compile-ok? [
      exe
    ][
      none
    ]    
  ]
  
  compile-and-run: func [src /error /pgm] [
    source-file?: true
    either exe: compile src [
      either error [
        run/error  exe
      ][
      	  either pgm [
      	  	  run/pgm exe
      	  ][
      	  	  run exe
      	  ]
      ]
    ][
      compile-error src
      output: "Compilation failed"
    ]
  ]
    
  compile-and-run-from-string: func [src /error] [
    source-file?: false
    either exe: compile-from-string src [
      either error [
        run/error  exe
      ][
        run exe
      ]
    ][
      
      compile-error "Supplied source"
      output: "Compilation failed"
    ]
  ]
  
  compile-dll: func [
    lib-src [file!]
    target	[string!]
    /local
    	dll
  ][
    ;; compile the lib into the runnable dir
    if not dll: compile/lib lib-src target [
      compile-error lib-src
      output: "Lib compilation failed"  
    ]
    dll
  ]
  
  compile-from-string: func [src][
    ;-- add a default header if not provided
    parse src script-header-rule
    if no-script-header? [
    	insert src join script-header "^/"
    ]
    write test-src-file src
    compile test-src-file                  ;; returns path to executable or none
  ]
  
  compile-error: func [
    src [file! string!]
  ][
    print join "^/" [src " - compiler error^/"]
    print comp-output
    print newline
    clear output                           ;; clear the output from previous test
    _signify-failure
  ]
  
  compile-ok?: func [] [
    either find comp-output "output file size :" [true] [false]
  ] 
  
  compile-run-print: func [src [file!] /error][
  	  either error [
  	  	  compile-and-run/error src
  	  ][
  	  	  compile-and-run src
    ]
    if output <> "Compilation failed" [print output]
  ]
  
  compiled?: func [
    src [string!]
  ][
    exe: compile-from-string src
    clean-compile-from-string
    qt/compile-ok?
  ]
  
  run: func [
    prog [file!]
    ;;/args                         ;; not yet needed
      ;;parms [string!]             ;; not yet needed
    /error                          ;; run time error expected
    /pgm							;; a program not a test
    /local
    exec [string!]                  ;; command to be executed
  ][
    exec: to-local-file runnable-dir/:prog
    ;;exec: join "" compose/deep [(exec either args [join " " parms] [""])]
    clear output
    do call* exec output
    if all [red? windows-os?] [output: qt/utf-16le-to-utf-8 output]
    if all [
      source-file?
      not pgm
      any [
      	  all [
      	   none <> find output "Runtime Error"
      	   not error
      	  ]
      	  none = find output "Passed"
      ]
    ][	
    print "signify failure"
      _signify-failure
    ]
  ]
  
  run-unit-test: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd make string! 1024
  ]
  
  run-unit-test-quiet: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    test-name: find/last/tail src "/"
    test-name: copy/part test-name find test-name "."
    prin [ "running " test-name #"^(0D)"]
    clear output
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd output
    if find output "Error:" [_signify-failure]
    add-to-run-totals
    write/append log-file output
    file/title: test-name
    replace file/title "-test" ""
    _print-summary file
  ]
  
  run-script: func [
    src [file!]
    /local
     filename                     ;; filename of script 
     script                       ;; %runnable/filename
  ][
    if not filename: copy find/last/tail src "/" [filename: copy src]
    script: runnable-dir/:filename
    write to file! script read join tests-dir [src]
    if error? try [do script] [_signify-failure]
  ]
  
  run-script-quiet: func [
  	src [file!]
  ][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-script src
    add-to-run-totals
    print: :_save-print
    write/append log-file print-output
    _print-summary file
  ]
  
  run-test-file: func [
  	src [file!]
  ][
    file/reset
    unless file/title: find/last/tail to string! src "/" [file/title: src]
    replace file/title "-test.reds" ""
    replace file/title "-test.red" ""
    compile-run-print src
    add-to-run-totals
  ]
  
  run-test-file-quiet: func [
  	src [file!]
  	][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-test-file src
    print: :_save-print
    write/append log-file print-output
    _print-summary file
    output: copy ""
  ]
  
  add-to-run-totals: func [
    /local
      tests
      
      asserts
      passes
      failures
      rule
      digit
      number
  ][
    digit: charset [#"0" - #"9"]
    number: [some digit]
    ws: charset [#"^-" #"^/" #" "]
    whitespace: [some ws]
    rule: [
      thru "Number of Tests Performed:" whitespace copy tests number
      thru "Number of Assertions Performed:" whitespace copy asserts number
      thru "Number of Assertions Passed:" whitespace copy passed number
      thru "Number of Assertions Failed:" whitespace copy failures number
      to end
    ]
    if parse/all output rule [
      file/no-tests: file/no-tests + to integer! tests
      file/no-asserts: file/no-asserts + to integer! asserts
      file/passes: file/passes + to integer! passed
      file/failures: file/failures + to integer! failures
      _add-file-to-run-totals
    ]
  ]
  
  _start: func [
    data [object!]
    leader [string!]
    title [string!]
  ][
    print [leader title]
    data/title: title
    data/no-tests: 0
    data/no-asserts: 0
    data/passes: 0
    data/failures: 0
    _init-group
  ]

  start-test-run: func [
    title [string!]
  ][
    _start test-run "***Starting***" title
    prin newline
  ]
  
  start-test-run-quiet: func [
    title [string!]
      ][
    _start test-run "" title
    prin newline
    write log-file rejoin ["***Starting*** " title newline]
  ]
  
  start-file: func [
    title [string!]
  ][
    _start file "~~~started test~~~" title
  ]
  
  start-group: func[
    title [string!]
  ][
   group-name: title
   group?: true
  ]
  
  start-test: func[
    title [string!]
  ][
    _init-test
    test-name: title
    file/no-tests: file/no-tests + 1
  ]
    
  assert: func [
    assertion [logic!]
  ][
    file/no-asserts: file/no-asserts + 1
    either assertion [
      file/passes: file/passes + 1
    ][
      file/failures: file/failures + 1
      if group? [
        if group-name-not-printed [
          print ""
          print ["===group===" group-name]
        ]
      ]
      print ["---test---" test-name "FAILED**************"]
    ]
  ]
  
  assert-msg?: func [msg][
    assert found? find qt/comp-output msg
  ]
  
  assert-printed?: func [msg] [
    assert found? find qt/output msg
  ]
  
  clean-compile-from-string: does [
    if exists? test-src-file [delete test-src-file]
    if all [exe exists? exe][delete exe]
]
  
  end-group: does [
    _init-group
  ]
  
  _end: func [
    data [object!]
    leader [string!]
  ][
    print [leader data/title]
    print ["No of tests  " data/no-tests]
    print ["No of asserts" data/no-asserts]
    print ["Passed       " data/passes]
    print ["Failed       " data/failures]
    if data/failures > 0 [print "***TEST FAILURES***"]
    print ""
  ]
  
  end-file: func [] [
    _end file "~~~finished test~~~" 
    _add-file-to-run-totals
  ]
  
  end-test-run: func [] [
      print ""
    _end test-run "***Finished***"
  ]
  
  end-test-run-quiet: func [] [
    print: :_quiet-print
    print-output: copy ""
    end-test-run
    print: :_save-print
    write/append log-file print-output
    prin newline
    _print-summary test-run
  ]
  
  _print-summary: func [
    data [object!]
    /local
      print-line
  ][
    print-line: copy summary-template
    print-line: skip print-line 5
    remove/part print-line length? data/title
    insert print-line data/title
    print-line: skip tail print-line negate (3 + length? mold data/passes)
    remove/part print-line length? mold data/passes
    insert print-line data/passes
    append print-line data/no-asserts
    print-line: head print-line
    either data/no-asserts = data/passes [
      replace print-line ".." "ok"
    ][
      replace/all print-line "." "*"
      append print-line " **"
    ]
    print print-line
  ]
  
  make-if-needed?: func [
    {This function is used by the Red run-all scripts to build the auto files
     when necessary.} 
    auto-test-file [file!]
    make-file [file!]
    /lib-test
    /local
      stored-length   ; the length of the make... .r file used to build auto tests
      stored-file-length
      digit
      number
      rule
  ][
    auto-test-file: join tests-dir auto-test-file
    make-file: join tests-dir make-file
    
    stored-file-length: does [
      parse/all read auto-test-file rule
      stored-length
    ]
    digit: charset [#"0" - #"9"]
    number: [some digit]
    rule: [
      thru ";make-length:" 
      copy stored-length number (stored-length: to integer! stored-length)
      to end
    ]
    
    if not exists? make-file [return]
   
    if any [
      not exists? auto-test-file
      stored-file-length <> length? read make-file
      0:00 < difference modified? make-file modified? auto-test-file
    ][
      print ["Making" auto-test-file " - it will take a while"]
      do make-file
    ]
  ]
  
  setup-temp-files: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    comp-echo: join runnable-dir ["comp-echo" f ".txt"]
  	comp-r: join runnable-dir ["comp" f ".r"]
  	test-src-file: join runnable-dir ["qt-test-comp" f ".red"]
  ]
  
  delete-temp-files: does [
  	  if exists? comp-echo [delete comp-echo]
  	  if exists? comp-r [delete comp-r]
  	  if exists? test-src-file [delete test-src-file]  
  ]
  
  seperate-log-file: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    log-file: join base-dir ["quick-test/quick-test" f ".log"]
  ]
  
  utf-16le-to-utf-8: func [
    {Translates a utf-16LE encoded string to an utf-8 encoded one
     the algorithm is copied from lexer.r                         }
    in-str [string!]
    /local
      out-str
      code
  ][
   out-str: copy ""
   foreach [low high] to binary! in-str [
     code: high * 256 + low
     case [
       code <= 127  [
         append out-str to char! code					            ;-- c <= 7Fh
       ]
       code <= 2047 [							                        ;-- c <= 07FFh
         append out-str join "" [ 
           to char! ((shift code 6) and #"^(1F)" or #"^(C0)")
					 to char! ((code and #"^(3F)") or #"^(80)")
				 ]
			 ]
			 code <= 65535 [					                         		;-- c <= FFFFh
			   append out-str join "" [
			     to char! ((shift code 12) and #"^(0F)" or #"^(E0)")
			     to char! ((shift code 6) and #"^(3F)" or #"^(80)")
			     to char! (code and #"^(3F)" or #"^(80)")
			   ]
			 ]
			 code <= 1114111 [						                        ;-- c <= 10FFFFh
			   append out-str join "" [
			     to char! ((shift code 18) & ^"(07)" or #"^(F0)")
					 to char! ((shift code 12) and #"^(3F)" or #"^(80)")
					 to char! ((shift code 6)  and #"^(3F)" or #"^(80)")
					 to char! (code and #"^(3F)" or #"^(80)")
				 ]
			 ]                         ;-- Codepoints above U+10FFFF are ignored"
		 ]
	 ]
   out-str 
  ]
  
  ;; create the test "dialect"
  
  set '***start-run***              :start-test-run
  set '***start-run-quiet***        :start-test-run-quiet
  set '~~~start-file~~~             :start-file
  set '===start-group===            :start-group
  set '--test--                     :start-test
  set '--compile                    :compile
  set '--compile-red                :compile
  set '--compile-dll          		:compile-dll
  set '--compile-this               :compile-from-string
  set '--compile-this-red           :compile-from-string
  set '--compile-and-run            :compile-and-run
  set '--compile-and-run-red        :compile-and-run 
  set '--compile-and-run-this       :compile-and-run-from-string
  set '--compile-and-run-this-red   :compile-and-run-from-string
  set '--compile-run-print          :compile-run-print
  set '--compile-run-print-red      :compile-run-print
  set '--compiled?                  :compiled?
  set '--run                        :run
  set '--add-to-run-totals          :add-to-run-totals
  set '--run-unit-test              :run-unit-test
  set '--run-unit-test-quiet        :run-unit-test-quiet
  set '--run-script                 :run-script
  set '--run-script-quiet           :run-script-quiet
  set '--run-test-file              :run-test-file
  set '--run-test-file-red          :run-test-file
  set '--run-test-file-quiet        :run-test-file-quiet
  set '--run-test-file-quiet-red    :run-test-file-quiet
  set '--assert                     :assert
  set '--assert-msg?                :assert-msg?
  set '--assert-printed?            :assert-printed?
  set '--assert-red-printed?        :assert-printed?
  set '--clean                      :clean-compile-from-string
  set '===end-group===              :end-group
  set '~~~end-file~~~               :end-file
  set '***end-run***                :end-test-run
  set '***end-run-quiet***          :end-test-run-quiet
  set '--setup-temp-files			:setup-temp-files
  set '--delete-temp-files			:delete-temp-files
  set '--seperate-log-file			:seperate-log-file	
]
REBOL [
  Title:   "Simple testing framework for Red and Red/System programs"
	Author:  "Peter W A Wood"
	File: 	 %quick-test.r
	Version: 0.12.0
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

comment {
	This script makes some assumptions about the directory structure in which 
	files are stored. They are:
    	this script is stored in Red/quick-test/
    	the Red & Red/System compiler is stored in Red/
    	the default dir for tests is Red/system/tests/
    	
    	The default test dirs can be overriden by setting qt/tests-dir before
    	tests are processed
    	The default script header for code supplied as string is Red [], this 
    	can be overriden by setting qt/script-header
    	The default location of the compiler binary is Red/build/bin, this can
    	be overriden by setting qt/bin-compiler
}

qt: make object! [
  
  ;;;;;;;;;;; Setup ;;;;;;;;;;;;;;
  ;; set the base-dir to ....Red/
  base-dir: system/script/path
  base-dir: copy/part base-dir find base-dir "quick-test"
  ;; set the red/system runnable dir
  runnable-dir: dirize base-dir/quick-test/runnable
  ;; set the default base dir for tests
  tests-dir: dirize base-dir/system/tests
  
  ;; set the version number
  version: system/script/header/version
  
  ;; switch for binary compiler usage
  binary?: false

  ;; check if call-show? is enabled for call
  if (not value? 'call-show?) [call-show?: 'wait]
  call*: to path! 'call
  append call* :call-show?
  append call* 'output
  
  ;; default binary compiler path
  bin-compiler: base-dir/build/bin/red
  
  ;; default script header to be inserted into code supplied in string form
  script-header: "Red []"
  
  ;; set temporary files names
  ;;  use Red/quick-test/runnable for temp files
  comp-echo: runnable-dir/comp-echo.txt
  comp-r: runnable-dir/comp.r
  test-src-file: runnable-dir/qt-test-comp.red
  
  ;; set log file 
  log-file: join system/script/path "quick-test.log"

  ;; make runnable directory if needed
  make-dir runnable-dir
  
  ;; windows ?
  windows-os?: system/version/4 = 3
  
  ;; use Cheyenne call with REBOL v2.7.8 on Windows (re: 'call bug on Windows 7)
  if all [
    windows-os?
    system/version/3 = 8              
  ][
		do %call.r					               
		set 'call :win-call
	]
	
	;; script header parse rules - assumes parsing without /all
	red?: false
	red-header: ["red" any " " "[" to end (red?: true)]
	red-system-header: ["red/system" any " " "[" to end (red?: false)]
	red?-rule: [(red?: false) any [red-system-header | red-header | skip]]
	script-header-rule: [
		(no-script-header?: true) 
		any [ 
				[["red/system" | "red"] any " " "[" (no-script-header?: false)]
			|
				skip
		]
	]

	;;;;;;;;; End Setup ;;;;;;;;;;;;;;
  
  comp-output: copy ""                 ;; output captured from compile
  output: copy ""                      ;; output captured from pgm exec
  exe: none                            ;; filepath to executable
  source-file?: true                   ;; true = running  test file
                                       ;; false = runnning test script
				  

  summary-template: ".. - .................................................. / "
  
  data: make object! [
    title: copy ""
    no-tests: 0
    no-asserts: 0
    passes: 0
    failures: 0
    reset: does [
      title: copy ""
      no-tests: 0
      no-asserts: 0
      passes: 0
      failures: 0
    ]
  ]
  
  file: make data []
  test-run: make data []
  _add-file-to-run-totals: does [
    test-run/no-tests: test-run/no-tests + file/no-tests
    test-run/no-asserts: test-run/no-asserts + file/no-asserts
    test-run/passes: test-run/passes + file/passes
    test-run/failures: test-run/failures + file/failures
  ]
  _signify-failure: does [
    ;; called when a compiler or runtime error occurs
    file/failures: file/failures + 1           
    file/no-tests: file/no-tests + 1
    file/no-asserts: file/no-asserts + 1
    test-run/failures: test-run/failures + 1           
    test-run/no-tests: test-run/no-tests + 1
    test-run/no-asserts: test-run/no-asserts + 1
  ]
  
  ;; group data
  group-name: copy ""
  group?: false
  group-name-not-printed: true
  _init-group: does [
    group?: false
    group-name-not-printed: true
    group-name: copy ""
  ]
  
  ;; test data
  test-name: copy ""
  _init-test: does [
    test-name: copy ""
  ]
  
  ;; print diversion function
  _save-print: :print
  print-output: copy ""
  _quiet-print: func [val] [
    append print-output join "" [reduce val "^/"]
  ]
        
  	compile: func [
  		src [file!]
  		/bin
  		/lib
  	  		target [string!]	
  	  	/local
  	  		comp                          	;; compilation script
  	  		cmd                           	;; compilation cmd
  	  		exe								;; executable name
  ][
    clear comp-output
    
    ;; workout executable name
    either find/last/tail src "/" [
      exe: copy find/last/tail src "/"
    ][
      exe: copy src
    ]
    exe: copy/part exe find exe "."
    either lib [
      switch/default target [
        "Windows"	[exe: join exe [".dll"]]
        "Darwin"   	[exe: join exe [".dylib"]]
      ][
      	  exe: join exe [".so"]
      ]
      exe
    ][     
      if windows-os? [
        exe: join exe [".exe"]
      ]
    ]
    
    ;; find the path to the src
    if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    
    ;; red/system or red
    red?: false
    parse read src red?-rule
 
    ;; compose and write compilation script
    either binary? [
    	if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    	either lib [
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe
    					  " -dlib -t " target " "
    					  to-local-file src
    		]
    	][
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe " "
    					  to-local-file src	
    		]  		
    	]
    	comp-output: make string! 1024
    	do call* cmd comp-output
    ][
    	comp: mold compose/deep [
    	  REBOL []
    	  halt: :quit
    	  echo (comp-echo)
    	  do/args (reduce base-dir/red.r) (join " -o " [
    	  	  	  reduce runnable-dir/:exe " ###lib###***src***" 
    	  ])
    	]
    	either lib [
    		replace comp "###lib###" join "-dlib -t " [target " "]
    	][
    		replace comp "###lib###" ""
    	]
    
    	replace comp "***src***"  clean-path src
    	write comp-r comp

    	;; compose command line and call it
    	cmd: join to-local-file system/options/boot [" -sc " comp-r]
    	do call* cmd make string! 1024	;; redirect output to anonymous
    											;; buffer
    ]
    
    ;; collect compiler output & tidy up
    if exists? comp-echo [
    	comp-output: read comp-echo
    	delete comp-echo
    ]
    if exists? comp-r [delete comp-r]
    either compile-ok? [
      exe
    ][
      none
    ]    
  ]
  
  compile-and-run: func [src /error /pgm] [
    source-file?: true
    either exe: compile src [
      either error [
        run/error  exe
      ][
      	  either pgm [
      	  	  run/pgm exe
      	  ][
      	  	  run exe
      	  ]
      ]
    ][
      compile-error src
      output: "Compilation failed"
    ]
  ]
    
  compile-and-run-from-string: func [src /error] [
    source-file?: false
    either exe: compile-from-string src [
      either error [
        run/error  exe
      ][
        run exe
      ]
    ][
      
      compile-error "Supplied source"
      output: "Compilation failed"
    ]
  ]
  
  compile-dll: func [
    lib-src [file!]
    target	[string!]
    /local
    	dll
  ][
    ;; compile the lib into the runnable dir
    if not dll: compile/lib lib-src target [
      compile-error lib-src
      output: "Lib compilation failed"  
    ]
    dll
  ]
  
  compile-from-string: func [src][
    ;-- add a default header if not provided
    parse src script-header-rule
    if no-script-header? [
    	insert src join script-header "^/"
    ]
    write test-src-file src
    compile test-src-file                  ;; returns path to executable or none
  ]
  
  compile-error: func [
    src [file! string!]
  ][
    print join "^/" [src " - compiler error^/"]
    print comp-output
    print newline
    clear output                           ;; clear the output from previous test
    _signify-failure
  ]
  
  compile-ok?: func [] [
    either find comp-output "output file size :" [true] [false]
  ] 
  
  compile-run-print: func [src [file!] /error][
  	  either error [
  	  	  compile-and-run/error src
  	  ][
  	  	  compile-and-run src
    ]
    if output <> "Compilation failed" [print output]
  ]
  
  compiled?: func [
    src [string!]
  ][
    exe: compile-from-string src
    clean-compile-from-string
    qt/compile-ok?
  ]
  
  run: func [
    prog [file!]
    ;;/args                         ;; not yet needed
      ;;parms [string!]             ;; not yet needed
    /error                          ;; run time error expected
    /pgm							;; a program not a test
    /local
    exec [string!]                  ;; command to be executed
  ][
    exec: to-local-file runnable-dir/:prog
    ;;exec: join "" compose/deep [(exec either args [join " " parms] [""])]
    clear output
    do call* exec output
    if all [red? windows-os?] [output: qt/utf-16le-to-utf-8 output]
    if all [
      source-file?
      not pgm
      any [
      	  all [
      	   none <> find output "Runtime Error"
      	   not error
      	  ]
      	  none = find output "Passed"
      ]
    ][	
    print "signify failure"
      _signify-failure
    ]
  ]
  
  run-unit-test: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd make string! 1024
  ]
  
  run-unit-test-quiet: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    test-name: find/last/tail src "/"
    test-name: copy/part test-name find test-name "."
    prin [ "running " test-name #"^(0D)"]
    clear output
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd output
    if find output "Error:" [_signify-failure]
    add-to-run-totals
    write/append log-file output
    file/title: test-name
    replace file/title "-test" ""
    _print-summary file
  ]
  
  run-script: func [
    src [file!]
    /local
     filename                     ;; filename of script 
     script                       ;; %runnable/filename
  ][
    if not filename: copy find/last/tail src "/" [filename: copy src]
    script: runnable-dir/:filename
    write to file! script read join tests-dir [src]
    if error? try [do script] [_signify-failure]
  ]
  
  run-script-quiet: func [
  	src [file!]
  ][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-script src
    add-to-run-totals
    print: :_save-print
    write/append log-file print-output
    _print-summary file
  ]
  
  run-test-file: func [
  	src [file!]
  ][
    file/reset
    unless file/title: find/last/tail to string! src "/" [file/title: src]
    replace file/title "-test.reds" ""
    replace file/title "-test.red" ""
    compile-run-print src
    add-to-run-totals
  ]
  
  run-test-file-quiet: func [
  	src [file!]
  	][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-test-file src
    print: :_save-print
    write/append log-file print-output
    _print-summary file
    output: copy ""
  ]
  
  add-to-run-totals: func [
    /local
      tests
      
      asserts
      passes
      failures
      rule
      digit
      number
  ][
    digit: charset [#"0" - #"9"]
    number: [some digit]
    ws: charset [#"^-" #"^/" #" "]
    whitespace: [some ws]
    rule: [
      thru "Number of Tests Performed:" whitespace copy tests number
      thru "Number of Assertions Performed:" whitespace copy asserts number
      thru "Number of Assertions Passed:" whitespace copy passed number
      thru "Number of Assertions Failed:" whitespace copy failures number
      to end
    ]
    if parse/all output rule [
      file/no-tests: file/no-tests + to integer! tests
      file/no-asserts: file/no-asserts + to integer! asserts
      file/passes: file/passes + to integer! passed
      file/failures: file/failures + to integer! failures
      _add-file-to-run-totals
    ]
  ]
  
  _start: func [
    data [object!]
    leader [string!]
    title [string!]
  ][
    print [leader title]
    data/title: title
    data/no-tests: 0
    data/no-asserts: 0
    data/passes: 0
    data/failures: 0
    _init-group
  ]

  start-test-run: func [
    title [string!]
  ][
    _start test-run "***Starting***" title
    prin newline
  ]
  
  start-test-run-quiet: func [
    title [string!]
      ][
    _start test-run "" title
    prin newline
    write log-file rejoin ["***Starting*** " title newline]
  ]
  
  start-file: func [
    title [string!]
  ][
    _start file "~~~started test~~~" title
  ]
  
  start-group: func[
    title [string!]
  ][
   group-name: title
   group?: true
  ]
  
  start-test: func[
    title [string!]
  ][
    _init-test
    test-name: title
    file/no-tests: file/no-tests + 1
  ]
    
  assert: func [
    assertion [logic!]
  ][
    file/no-asserts: file/no-asserts + 1
    either assertion [
      file/passes: file/passes + 1
    ][
      file/failures: file/failures + 1
      if group? [
        if group-name-not-printed [
          print ""
          print ["===group===" group-name]
        ]
      ]
      print ["---test---" test-name "FAILED**************"]
    ]
  ]
  
  assert-msg?: func [msg][
    assert found? find qt/comp-output msg
  ]
  
  assert-printed?: func [msg] [
    assert found? find qt/output msg
  ]
  
  clean-compile-from-string: does [
    if exists? test-src-file [delete test-src-file]
    if all [exe exists? exe][delete exe]
]
  
  end-group: does [
    _init-group
  ]
  
  _end: func [
    data [object!]
    leader [string!]
  ][
    print [leader data/title]
    print ["No of tests  " data/no-tests]
    print ["No of asserts" data/no-asserts]
    print ["Passed       " data/passes]
    print ["Failed       " data/failures]
    if data/failures > 0 [print "***TEST FAILURES***"]
    print ""
  ]
  
  end-file: func [] [
    _end file "~~~finished test~~~" 
    _add-file-to-run-totals
  ]
  
  end-test-run: func [] [
      print ""
    _end test-run "***Finished***"
  ]
  
  end-test-run-quiet: func [] [
    print: :_quiet-print
    print-output: copy ""
    end-test-run
    print: :_save-print
    write/append log-file print-output
    prin newline
    _print-summary test-run
  ]
  
  _print-summary: func [
    data [object!]
    /local
      print-line
  ][
    print-line: copy summary-template
    print-line: skip print-line 5
    remove/part print-line length? data/title
    insert print-line data/title
    print-line: skip tail print-line negate (3 + length? mold data/passes)
    remove/part print-line length? mold data/passes
    insert print-line data/passes
    append print-line data/no-asserts
    print-line: head print-line
    either data/no-asserts = data/passes [
      replace print-line ".." "ok"
    ][
      replace/all print-line "." "*"
      append print-line " **"
    ]
    print print-line
  ]
  
  make-if-needed?: func [
    {This function is used by the Red run-all scripts to build the auto files
     when necessary.} 
    auto-test-file [file!]
    make-file [file!]
    /lib-test
    /local
      stored-length   ; the length of the make... .r file used to build auto tests
      stored-file-length
      digit
      number
      rule
  ][
    auto-test-file: join tests-dir auto-test-file
    make-file: join tests-dir make-file
    
    stored-file-length: does [
      parse/all read auto-test-file rule
      stored-length
    ]
    digit: charset [#"0" - #"9"]
    number: [some digit]
    rule: [
      thru ";make-length:" 
      copy stored-length number (stored-length: to integer! stored-length)
      to end
    ]
    
    if not exists? make-file [return]
   
    if any [
      not exists? auto-test-file
      stored-file-length <> length? read make-file
      0:00 < difference modified? make-file modified? auto-test-file
    ][
      print ["Making" auto-test-file " - it will take a while"]
      do make-file
    ]
  ]
  
  setup-temp-files: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    comp-echo: join runnable-dir ["comp-echo" f ".txt"]
  	comp-r: join runnable-dir ["comp" f ".r"]
  	test-src-file: join runnable-dir ["qt-test-comp" f ".red"]
  ]
  
  delete-temp-files: does [
  	  if exists? comp-echo [delete comp-echo]
  	  if exists? comp-r [delete comp-r]
  	  if exists? test-src-file [delete test-src-file]  
  ]
  
  seperate-log-file: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    log-file: join base-dir ["quick-test/quick-test" f ".log"]
  ]
  
  utf-16le-to-utf-8: func [
    {Translates a utf-16LE encoded string to an utf-8 encoded one
     the algorithm is copied from lexer.r                         }
    in-str [string!]
    /local
      out-str
      code
  ][
   out-str: copy ""
   foreach [low high] to binary! in-str [
     code: high * 256 + low
     case [
       code <= 127  [
         append out-str to char! code					            ;-- c <= 7Fh
       ]
       code <= 2047 [							                        ;-- c <= 07FFh
         append out-str join "" [ 
           to char! ((shift code 6) and #"^(1F)" or #"^(C0)")
					 to char! ((code and #"^(3F)") or #"^(80)")
				 ]
			 ]
			 code <= 65535 [					                         		;-- c <= FFFFh
			   append out-str join "" [
			     to char! ((shift code 12) and #"^(0F)" or #"^(E0)")
			     to char! ((shift code 6) and #"^(3F)" or #"^(80)")
			     to char! (code and #"^(3F)" or #"^(80)")
			   ]
			 ]
			 code <= 1114111 [						                        ;-- c <= 10FFFFh
			   append out-str join "" [
			     to char! ((shift code 18) & ^"(07)" or #"^(F0)")
					 to char! ((shift code 12) and #"^(3F)" or #"^(80)")
					 to char! ((shift code 6)  and #"^(3F)" or #"^(80)")
					 to char! (code and #"^(3F)" or #"^(80)")
				 ]
			 ]                         ;-- Codepoints above U+10FFFF are ignored"
		 ]
	 ]
   out-str 
  ]
  
  ;; create the test "dialect"
  
  set '***start-run***              :start-test-run
  set '***start-run-quiet***        :start-test-run-quiet
  set '~~~start-file~~~             :start-file
  set '===start-group===            :start-group
  set '--test--                     :start-test
  set '--compile                    :compile
  set '--compile-red                :compile
  set '--compile-dll          		:compile-dll
  set '--compile-this               :compile-from-string
  set '--compile-this-red           :compile-from-string
  set '--compile-and-run            :compile-and-run
  set '--compile-and-run-red        :compile-and-run 
  set '--compile-and-run-this       :compile-and-run-from-string
  set '--compile-and-run-this-red   :compile-and-run-from-string
  set '--compile-run-print          :compile-run-print
  set '--compile-run-print-red      :compile-run-print
  set '--compiled?                  :compiled?
  set '--run                        :run
  set '--add-to-run-totals          :add-to-run-totals
  set '--run-unit-test              :run-unit-test
  set '--run-unit-test-quiet        :run-unit-test-quiet
  set '--run-script                 :run-script
  set '--run-script-quiet           :run-script-quiet
  set '--run-test-file              :run-test-file
  set '--run-test-file-red          :run-test-file
  set '--run-test-file-quiet        :run-test-file-quiet
  set '--run-test-file-quiet-red    :run-test-file-quiet
  set '--assert                     :assert
  set '--assert-msg?                :assert-msg?
  set '--assert-printed?            :assert-printed?
  set '--assert-red-printed?        :assert-printed?
  set '--clean                      :clean-compile-from-string
  set '===end-group===              :end-group
  set '~~~end-file~~~               :end-file
  set '***end-run***                :end-test-run
  set '***end-run-quiet***          :end-test-run-quiet
  set '--setup-temp-files			:setup-temp-files
  set '--delete-temp-files			:delete-temp-files
  set '--seperate-log-file			:seperate-log-file	
]
#' Load a bunch of dependencies by filename
#' 
#' This is useful for reducing pollution in the global namespace,
#' and not loading multiple files twice unnecessarily.
#'
#' @export
#' @param ... see examples.
#' @param envir environment. The parent environment to use when calling
#'   \code{base::source} to fetch dependencies.
#' @param local logical. If \code{TRUE} and \code{envir} is missing,
#'   it will set \code{envir = parent.frame()}.
#' @examples
#' \dontrun{
#' helper_fn <- define('some/dir/helper_fn')
#' define(c('some/dir/helper_fn', 'some/other_dir/library_fn'), function(helper_fn, library_fn) { ... }
#' helper_fns <<- define('some/dir/helper_fn1', 'some/otherdir/helper_fn2')
#' helper_fns[[1]]('do something'); helper_fns[[2]]('do something else')
#' }
define <- (function() {
  number_of_required_arguments <- function(fn) {
    function_has_variable_number_of_arguments <- '...' %in% names(formals(fn))
    if (function_has_variable_number_of_arguments) return(NA_real_)
    function_arguments <- formals(fn)
    required_arguments <- sapply(function_arguments, class) == 'name'
    sum(required_arguments)
  }

  process_function_with_no_dependencies <- function(fn) {
    number_of_arguments <- number_of_required_arguments(fn)
    if (number_of_arguments == 0) fn()
    else if (number_of_arguments == 1) fn(define)
    else stop("Ramd::define only processes functions with <= 1 ",
              "arguments if no dependencies are given, but the ",
              "passed function has ", number_of_required_arguments, 
              " required arguments")
  }

  flatten <- function(lists) {    
    atomic_vector <- unlist(c(lists))
    delimited_string <- paste(atomic_vector, collapse = ' ')
    strsplit(delimited_string, '[^-a-zA-Z0-9.-_`:\\\\\\/]+')[[1]]
  }

  parse_dependencies <- function(arguments) {
    cd <- current_directory()
    if (any(sapply(arguments, class) != 'character'))
      stop("Ramd::define only accepts atomic character vectors for ",
           "specifying dependencies")
    dependencies <- unlist(c(arguments))
    if ('Ramd.no_flatten' %in% names(.Options) &&
        getOption('Ramd.no_flatten')) dependencies
    else flatten(dependencies)
  }

  fetch_dependencies <- function(arguments, envir) {
    dependency_names <- parse_dependencies(arguments)
    dependencies <- lapply(dependency_names, load_dependency, envir = envir)
    names(dependencies) <- dependency_names
    dependencies
  }

  verify_number_of_required_arguments_matches_number_of_dependencies <-
    function(fn, number_of_dependencies) {
      num_of_required_arguments <- number_of_required_arguments(fn)
      if (is.na(num_of_required_arguments)) return(TRUE)
      if (num_of_required_arguments != number_of_dependencies)
        stop("Ramd::define was not able to load dependencies because ",
             number_of_dependencies, " dependenc",
             # Pluralization, for fun!
             if (number_of_dependencies == 1) 'y was' else 'ies were',
             " passed in but the given function has ",
             num_of_required_arguments, " required argument",
             if (num_of_required_arguments == 1) '' else 's')
      TRUE
    }

  function(..., envir = parent.env(topenv()), local) {
    if (!missing(local) && isTRUE(local)) {
      envir <- parent.frame()
    }

    arguments <- list(...)
    if ('packages' %in% names(arguments)) {
      if (length(arguments) == 1)
        stop("Ramd::define does more than just load packages, ",
             "please provide some dependencies or a function. ",
             "To just load packages, use Ramd::packages")
      packages(arguments$packages)
      arguments <- arguments[names(arguments) != 'packages']
    }

    fn <- arguments[[length(arguments)]]
    valid_function <- is.function(fn)
    if (valid_function) {
      dependencies <- head(arguments, -1)
      if (length(dependencies) == 0)
        return (process_function_with_no_dependencies(fn))
    } else dependencies <- arguments

    if (valid_function)
      verify_number_of_required_arguments_matches_number_of_dependencies(
        fn, length(unlist(dependencies)))

    dependencies <- fetch_dependencies(dependencies, envir = envir)
    if (valid_function) do.call(fn, unname(dependencies))
    else dependencies
  }

})()
`%||%` <- function(x, y) if (is.null(x)) y else x


# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Attempt to memoize a function using the memoise package.
#' 
#' This function will load the \code{memoise} package if it is
#' available, or do nothing otherwise.
#'
#' (Blame Hadley for the spelling of memoise.)
#'
#' @param fn function. The function to memoize.
#' @return nothing, but \code{try_memoize} will use non-standard
#'   evaluation to memoize in the calling environment.
#' @name try_memoize
try_memoize <- function(fn) {
  if ('memoise' %in% installed.packages()) {
    require(memoise)
    eval.parent(substitute(memoise(fn)))
  }
  fn
}

# A reference class that implements a stack data structure.
shtack <- setRefClass('stack', list(elements = 'list'), methods = list(
  clear      = function()  { elements <<- list() },
  empty      = function()  { length(elements) == 0 },
  push       = function(x) { elements[[length(elements) + 1]] <<- x },
  peek       = function(n = 1)  {
    if (isTRUE(n)) return(elements)
    els <- seq(length(elements), length(elements) - n + 1)
    if (length(els) == 1) elements[[els]]
    else elements[els]
  },
  pop        = function()  {
    if (length(elements) == 0) stop("director:::stack is empty")
    tmp <- elements[[length(elements)]]
    elements[[length(elements)]] <<- NULL
    tmp
  },
  pop_all    = function()  { tmp <- elements; elements <<- list(); tmp }
))                                                                      

#' Whether or not a directory is an idempotent resource.
#'
#' By definition, this means the directory contains a file with the same name
#' (ignoring extension) as the directory.
#'
#' @param dir character. The directory to check.
#' @return \code{TRUE} or \code{FALSE} according as the directory is idempotent.
#'   There is no checking to ensure the directory exists.
#' @examples
#' \dontrun{
#'   # If we have a directory foo containing foo.R, then
#'   is.idempotent_directory('foo')
#'   # is TRUE, otherwise it's FALSE.
#' }
is.idempotent_directory <- function(dir) {
  # TODO: (RK) Case insensitivity in OSes that don't respect it, i.e. Windows?
  # TODO: (RK) File extensions besides .r and .R?
  extensionless_exists(file.path(dir, basename(dir)))
}

#' Determine whether an R file exists regardless of case of extension.
#'
#' @param filename character. The filename to test (possibly without extension).
#' @return \code{TRUE} or \code{FALSE} if the filename exists regardless of 
#'   R extension.
#' @examples
#' \dontrun{
#'  # Assume we have a file \code{"foo.R"}. The following all return \code{TRUE}.
#'  extensionless_exists('foo.R')
#'  extensionless_exists('foo.r')
#'  extensionless_exists('foo')
#' }
extensionless_exists <- function(filename) {
  file.exists(paste0(strip_r_extension(filename), '.r')) ||
  file.exists(paste0(strip_r_extension(filename), '.R')) 
  # Don't use the any + sapply trick because we can skip the latter check if the
  # former succeeds.
}

#' Strip R extension.
#'
#' @param filename character. The filename to strip.
#' @return the filename without the '.r' or '.R' at the end.
strip_r_extension <- function(filename) {
  stopifnot(is.character(filename))
  gsub("\\.[rR]$", "", filename)
}

#' Strip a root file path from an absolute filename.
#'
#' @param root character. The root path.
#' @param filename character. The full file name.
#' @return the stripped file path.
#' @examples
#' \dontrun{
#'   stopifnot("test" == strip_root("foo/bar/test", "test"))
#' }
strip_root <- function(root, filename) {
  stopifnot(is.character(root) && is.character(filename))
  if (substring(filename, 1, nchar(root)) == root) {
    filename <- substring(filename, nchar(root) + 1, nchar(filename)) 
    gsub("^\\/*", "", filename)
  } else filename
}

#' Convert an idempotent resource name to a non-idempotent resource name.
#'
#' @param filename character. The filename to convert.
#' @return the non-idempotent filename.
drop_idempotence <- function(filename) {
  if (basename(dirname(filename)) == basename(filename))
    dirname(filename)
  else filename
}

#' Convert a filename to a resource name.
#'
#' @param filename character. The filename.
#' @return the resource name (i.e., stripped of idempotence and extension).
resource_name <- function(filename) {
  drop_idempotence(strip_r_extension(filename))
}

#' Create a resource cache key from a resource key.
#'
#' This is the key under whose director cache the info about the resource
#' as of previous execution will be stored.
#'
#' @param resource_key character. The resource key.
#' @return a cache key, currently just \code{"resource_cache/"} followed by
#'    the \code{resource_key}.
resource_cache_key <- function(resource_key) {
 file.path('resource_cache', resource_key)
}

#' Get all helper files associated with an idempotent resource directory.
#'
#' @param path character. The *absolute* path of the idempotent resource.
#' @return a character list of relative helper paths.
#' @examples
#' \dontrun{
#'   # If we have a directory structure given by \code{"model/model.R"},
#'   # \code{"model/constants.R"}, \code{"model/functions.R"}, then the
#'   # below will return \code{c("constants.R", "functions.R")}.
#'   get_helpers("model")
#' }
get_helpers <- function(path) {
  helper_files <- list.files(path, pattern = '\\.[rR]$') # TODO: (RK) Recursive helpers?
  same_file <- which(vapply(helper_files, 
    function(f) strip_r_extension(f) == basename(path), logical(1)))
  helper_files <- helper_files[-same_file]
}

#' Whether or not any substring of a string is any of a set of strings.
#'
#' @param string character.
#' @param set_of_strings character.
#' @return logical
#' @examples
#' stopifnot(director:::any_is_substring_of('test', c('blah', 'te', 'woo'))) # TRUE
#' stopifnot(!director:::any_is_substring_of('test', c('blah', 'woo'))) # FALSE
any_is_substring_of <- function(string, set_of_strings) {
  any(vapply(set_of_strings,
             function(x) substring(string, 1, nchar(x)) == x, logical(1)))
}

# Stolen from testthat:::colourise
.fg_colours <- 
  structure(c("0;30", "0;34", "0;32", "0;36", "0;31", "0;35", "0;33",
  "0;37", "1;30", "1;34", "1;32", "1;36", "1;31", "1;35", "1;33",
  "1;37"), .Names = c("black", "blue", "green", "cyan", "red",
  "purple", "brown", "light gray", "dark gray", "light blue", "light green",
  "light cyan", "light red", "light purple", "yellow", "white"))
.bg_colours <- 
  structure(c("40", "41", "42", "43", "44", "45", "46", "47"), .Names = c("black",
  "red", "green", "brown", "blue", "purple", "cyan", "light gray"
  ))

colourise <- function (text, fg = "black", bg = NULL) {
  term <- Sys.getenv()["TERM"]
  colour_terms <- c("xterm-color", "xterm-256color", "screen",
      "screen-256color")
  if (!any(term %in% colour_terms, na.rm = TRUE)) return(text)
  col_escape <- function(col) paste0("\033[", col, "m")
  col <- .fg_colours[tolower(fg)]
  if (!is.null(bg)) col <- paste0(col, .bg_colours[tolower(bg)], sep = ";")
  init <- col_escape(col)
  reset <- col_escape("0")
  paste0(init, text, reset)
}



require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.basenames <- function(path,recursive=FALSE) {    
    grn.files <- list.files(path, pattern = "_Grn.idat$", recursive = recursive, 
                            ignore.case = TRUE, full.names = TRUE)
    red.files <- list.files(path, pattern = "_Red.idat$", recursive = recursive, 
                            ignore.case = TRUE, full.names = TRUE)
    intersect(sub("_Grn.idat$", "", grn.files), 
              sub("_Red.idat$", "", red.files))
}

meffil.probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

meffil.read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

meffil.rg.to.mu <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

meffil.extract.controls <- function(basename, probes=meffil.probe.info()) {
    msg("sample file", basename)
    rg <- meffil.read.rg(basename)
    extract.controls(rg, probes)
}

meffil.background.correct <- function(rg, probes=meffil.probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target %in% c("M","U") & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1

        addresses <- probes$address[which(probes$type == "control" & probes$dye == dye)]
        xc <- rg[[dye]][addresses]
        xc[which(xc <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        bg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), c(xf,xc)) + offset
        names(bg) <- c(names(xf), names(xc))
        bg
    })
}

meffil.dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}


meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=meffil.probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- meffil.read.rg(basename)
    rg.correct <- meffil.background.correct(rg, probes)
    rg.correct <- meffil.dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- meffil.rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

meffil.preprocess.control.matrix <- function(control.matrix) {
    control.matrix <- control.matrix[-grep("^intensity.bc", rownames(control.matrix)),]
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    t(scale(control.matrix))
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=meffil.probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("preprocessing the control matrix")
    control.matrix <- meffil.preprocess.control.matrix(control.matrix)

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}

meffil.normalize.sample <- function(object, probes=meffil.probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- meffil.read.rg(object$basename)
    rg.correct <- meffil.background.correct(rg, probes)
    rg.correct <- meffil.dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- meffil.rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-select.normalization.subsets(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=meffil.probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}


extract.controls <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$G[which(probes.G$target == "BISULFITE CONVERSION I"
                               & probes.G$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ext %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ext %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.Rp <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.Rp,na.rm=T)/mean(spec1.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.Gp <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.Gp,na.rm=T)/mean(spec1.R,na.rm=T)
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normC + normG)/(normA + normT)

    rg.bg <- meffil.background.correct(rg, probes)
    addresses <- probes.R$address[which(probes.R$target %in% c("NORM_A", "NORM_T"))]
    intensity.bc.R <- mean(rg.bg$R[addresses], na.rm = TRUE)
    addresses <- probes.G$address[which(probes.G$target %in% c("NORM_G", "NORM_C"))]
    intensity.bc.G <- mean(rg.bg$G[addresses], na.rm = TRUE)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio,
      intensity.bc.G=intensity.bc.G,
      intensity.bc.R=intensity.bc.R)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    ratios <- control.matrix["intensity.bc.G",]/control.matrix["intensity.bc.R",]
    reference <- which.min(abs(ratios-1))
    intensity <- (control.matrix["intensity.bc.G",] + control.matrix["intensity.bc.R",])[reference]/2
    list(R=intensity/control.matrix["intensity.bc.R",sample.idx],
         G=intensity/control.matrix["intensity.bc.G",sample.idx])
}


define.quantile.probe.sets <- function(probes=meffil.probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

select.normalization.subsets <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles + t(residuals(fits))
}

compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


########################
#Functions for calculating
#sufficient statistics
#
########################
legendre_Pl_array<-function(m,y){
  pf<-polynomial.functions(legendre.polynomials(m,normalized=F))
  lv<-sapply(X=1:(m+1),FUN=function(x){
    pf[[x]](y)
  })
  return(t(lv)*sqrt(2))
}

legendre_Pl_array<-function(m,y){
  pf<-polynomial.functions(legendre.polynomials(m,normalized=T))
  lv<-sapply(X=1:(m+1),FUN=function(x){
    pf[[x]](y) #*sqrt(2*(x-1)+1)
  })
  return(t(lv)*sqrt(2))
}


edge.means<-function(dat,edgelist,m,cores){
  n<-dim(dat)[1]
  nedge<- dim(edgelist)[1]
  if(nedge==0) return(array(dim=c(m,m,0)))
  me<-mclapply(
    1:nedge,
    function(e){
      ge<-edgelist[e,]
      s<-ge[1];t<-ge[2]
      tcrossprod(legendre_Pl_array(m,2*dat[,s]-1)[-1,,drop=F],
                 legendre_Pl_array(m,2*dat[,t]-1)[-1,,drop=F])/n
    },
    mc.cores=cores)
  return(array(unlist(me),dim=c(m,m,nedge)))
}

node.means<-function(dat,m,cores){
  if(is.vector(dat)){
    dat<-matrix(dat,length(dat),1)
  }
  d=dim(dat)[2]
  me<-mclapply(
    1:d,
    function(v){
      rowMeans(legendre_Pl_array(m,2*dat[,v]-1)[-1,,drop= F])
    },
    mc.cores=cores
  )
  return(matrix(unlist(me),nrow=d,byrow=T ))
}## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}

textareaInput <- function(inputId, label, value="", placeholder="", rows=2){
  tagList(
    div(strong(label), style="margin-top: 5px;"),
    tags$style(type="text/css", "textarea {width:100%; margin-top: 5px;}"),
    tags$textarea(id = inputId, placeholder = placeholder, rows = rows, value))
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='', selectize=FALSE, size=3)),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(id='sheetControlTab',
                 tabPanel('Type', value='sheetTabType',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='point'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='identity'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping', value='sheetTabMapping',

                          fluidRow(
                            column(4,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL, selectize=FALSE, size=15)
                                   ),
                            column(8,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='', inline=TRUE)
                                                    ),

                                   uiOutput('mapOrSetUI')
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters', value='sheetTabFilters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize', value='sheetTabCustomize',
                          textareaInput(inputId = 'plotTitle', label="Plot Title", value="",
                                        placeholder = 'Enter Plot Title here', rows = 2),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    colorInput('textColor', 'Font Color'),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    colorInput('rectColor', 'Border Color'),
                                                    colorInput('rectFill', 'Fill'),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    colorInput('lineColor', 'Line Color'),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   ),
                                   conditionalPanel('output.ggElementType=="character"',
                                                    uiOutput('charSetting')
                                   )
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))



####################################################
## Project saving and loading
####################################################
shrink <- function(x){
  if(is.list(x) && !is.data.frame(x)){
    if(is.reactivevalues(x)){
      x <- lapply(reactiveValuesToList(x), function(y){
        if(typeof(y)!='closure') shrink(y) else NULL
      })
      attr(x, 'wasReavtive') <- TRUE
    } else {
      ## x is an ordinary list
      ## need to preserve attributes
      attrs <- attributes(x)
      x <- lapply(x, shrink)
      attributes(x) <- attrs
    }
  } else {
    if(typeof(x)!='closure') x else NULL
  }
  x
}

wasReactivevalues <- function(x){
  !is.null(attr(x, 'wasReavtive'))
}

output$downloadProject <- downloadHandler(
  filename = function() { 'MyProject.sData' },
  content = function(file) {
    isolate({

      allData <- list(pp=shrink(projProperties),
                      dl=lapply(datList, function(d){
                        list('staticProperties'=d[['staticProperties']],
                             'dynamicProperties'=shrink(d[['dynamicProperties']]))
                      }),
                      sl=lapply(sheetList, function(d){
                        list('dynamicProperties'=shrink(d[['dynamicProperties']]))
                      }),
                      docl=shrink(docList))
      save(allData, file=file)

    })
  }
)


loadProject <- function(file, replaceOrMerge='replace'){
  load(file)

  if(replaceOrMerge=='replace'){
    for(n in names(datList)) datList[[n]] <<- NULL; projProperties[['activeDat']] <<- NULL
    for(n in names(sheetList)) sheetList[[n]] <<- NULL; projProperties[['activeSheet']] <<- NULL
    for(n in names(docList)) docList[[n]] <<- NULL; projProperties[['activeDoc']] <<- NULL
  }

  for(n in names(allData$pp)){
    if(is.null(projProperties[[n]]) || projProperties[[n]] != allData$pp[[n]]){
      projProperties[[n]] <<- allData$pp[[n]]
    }
  }

  for(di in names(allData$dl)){
    if(is.null(datList[[di]])){ # new data
      datList[[di]] <<- DatClass$new('staticProperties'=allData$dl[[di]][['staticProperties']])
      datList[[di]][['dynamicProperties']] <<- reactiveValues()

    }
    for(n in names(allData$dl[[di]][['dynamicProperties']])){
      x <- allData$dl[[di]][['dynamicProperties']][[n]]
      if(n=='fieldsList'){
        if(is.null(datList[[di]][['dynamicProperties']][[n]])) datList[[di]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(wasReactivevalues(x[[n1]])){
            if(is.null(datList[[di]][['dynamicProperties']][[n]][[n1]])) datList[[di]][['dynamicProperties']][[n]][[n1]] <<- reactiveValues()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              datList[[di]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
            }
          } else {
            datList[[di]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        datList[[di]][['dynamicProperties']][[n]] <<- x
      }
    }
    datList[[di]]$setDatDependencies()
  }

  for(si in names(allData$sl)){
    if(is.null(sheetList[[si]])){ # new sheet
      sheetList[[si]] <<- createNewSheetObj(withPlotLayer=FALSE)
      setSheetReactives(si)
    }
    for(n in names(allData$sl[[si]][['dynamicProperties']])){
      x <- allData$sl[[si]][['dynamicProperties']][[n]]
      if(n=='layerList'){
        if(is.null(sheetList[[si]][['dynamicProperties']][[n]])) sheetList[[si]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(wasReactivevalues(x[[n1]])){
            if(is.null(sheetList[[si]][['dynamicProperties']][[n]][[n1]]))
              sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- createNewLayer()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              if(n2=='aesList'){
                names3 <- names(x[[n1]][[n2]])
                for(n3 in names3){
                  if(wasReactivevalues(x[[n1]][[n2]][[n3]])){
                    names4 <- names(x[[n1]][[n2]][[n3]])
                    for(n4 in names4){
                      sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]][[n4]] <<- x[[n1]][[n2]][[n3]][[n4]]
                    }
                    setAesReactives(si,n1,n3)
                  } else {
                    sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]] <<- x[[n1]][[n2]][[n3]]
                  }
                }
              } else {
                sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
              }
            }
          } else {
            sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        sheetList[[si]][['dynamicProperties']][[n]] <<- x
      }
    }
  }

  for(di in names(allData$docl)){
    if(is.null(docList[[di]])){ # new doc
      docList[[di]] <<- reactiveValues()

    }
    for(n in names(allData$docl[[di]])){
      x <- allData$docl[[di]][[n]]
      docList[[di]][[n]] <<- x
    }
  }

  ## update all UI
  sapply(unique(c(names(input), names(updateInput))), triggerUpdateInput)
  updateTabsetPanel(session, 'mainNavBar', selected='Visualize')
}

observe({
  inFile <- input[['loadProject']]
  isolate({
    if (!is.null(inFile)){
      loadProject(file=inFile$datapath, replaceOrMerge=input[['loadProjectAction']])
    }
  })

})

observe({
  v <- input$openSampleProj
  isolate({
    file <- paste('samples', input[['sampleProj']], sep='/')
    if(v && file.exists(file)){
      loadProject(file=file, 'replace')
    }
  })
})
## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}

textareaInput <- function(inputId, label, value="", placeholder="", rows=2){
  tagList(
    div(strong(label), style="margin-top: 5px;"),
    tags$style(type="text/css", "textarea {width:100%; margin-top: 5px;}"),
    tags$textarea(id = inputId, placeholder = placeholder, rows = rows, value))
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='', selectize=FALSE, size=3)),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(id='sheetControlTab',
                 tabPanel('Type', value='sheetTabType',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter')),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping', value='sheetTabMapping',

                          fluidRow(
                            column(4,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL, selectize=FALSE, size=15)
                                   ),
                            column(8,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='', inline=TRUE)
                                                    ),

                                   uiOutput('mapOrSetUI')
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters', value='sheetTabFilters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize', value='sheetTabCustomize',
                          textareaInput(inputId = 'plotTitle', label="Plot Title", value="",
                                        placeholder = 'Enter Plot Title here', rows = 2),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    colorInput('textColor', 'Font Color'),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    colorInput('rectColor', 'Border Color'),
                                                    colorInput('rectFill', 'Fill'),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    colorInput('lineColor', 'Line Color'),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   ),
                                   conditionalPanel('output.ggElementType=="character"',
                                                    uiOutput('charSetting')
                                   )
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))


## switching data source
observe({
  v <- input$datList
  isolate({
    if(!isEmpty(input$datList)) projProperties[['activeDat']] <<- v
  })
})
observe({
  updateInput[['activeDat']]
  updateSelectInput(session, 'datList', choices=(datListNames()),
                    selected=isolate(projProperties[['activeDat']]))
})


## modify dat source name
observe({
  v <- input$datName
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      if(!isEmpty(v) && isEmpty(datListNames()[v])){
        ## the second condition makes sure v is different
        ## update doc's rmd
        oldName <- paste('`', datList[[currentDat]][['dynamicProperties']][['name']], '`', sep='')
        newName <- paste('`', v, '`', sep='')
        sapply(names(docList), function(currentDoc){
          docList[[currentDoc]][['rmd']] <<- gsub(oldName, newName, docList[[currentDoc]][['rmd']], fixed=TRUE)
          NULL
        })
        triggerUpdateInput('docRmd')

        datList[[currentDat]][['dynamicProperties']][['name']] <<- v
      }
    }
  })

})
observe({
  updateInput[['datName']]
  currentDat <- projProperties[['activeDat']]
  s <- if(!isEmpty(currentDat)){
    isolate(datList[[currentDat]][['dynamicProperties']][['name']])
  } else ''
  updateTextInput(session, 'datName', value=null2String(s))
})

## Selecting fields
observe({
  activeField <- input$fieldsList
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      datList[[currentDat]][['dynamicProperties']][['activeField']] <<- activeField
    }
  })

})
observe({
  updateInput[['activeField']]
  currentDat <- projProperties[['activeDat']]
  s <- if(!isEmpty(currentDat)){
    isolate(datList[[currentDat]][['dynamicProperties']][['activeField']])
  } else ''
  choices <- if(!isEmpty(currentDat)) datList[[currentDat]][['fieldNames']]()
  updateSelectizeInput(session, "fieldsList", choices=null2String(choices),
                       selected=null2String(s))
})

## modify field name
observe({
  v <- (input$fieldName) #make.names
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      currentField <- (datList[[currentDat]][['dynamicProperties']][['activeField']])
      if(!isEmpty(currentField)){
        if(!isEmpty(v) && isEmpty((datList[[currentDat]][['fieldNames']]())[v])){
          datList[[currentDat]][['dynamicProperties']][['fieldsList']][[currentField]][['name']] <<- v
          if(v!=input$fieldName) triggerUpdateInput('fieldName')
        }
      }
    }
  })

})
observe({
  updateInput[['fieldName']]
  currentDat <- projProperties[['activeDat']]
  s <- ''
  if(!isEmpty(currentDat)){
    currentField <- datList[[currentDat]][['dynamicProperties']][['activeField']]
    if(!isEmpty(currentField)){
      s <- isolate(datList[[currentDat]][['dynamicProperties']][['fieldsList']][[currentField]][['name']])
    }
  }
  updateTextInput(session, 'fieldName', value=null2String(s))
})

## Manipulating set of measures
observe({
  newMeasures <- input$measures
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      datList[[currentDat]][['dynamicProperties']][['measures']] <<- newMeasures
    }
  })
})
observe({
  updateInput[['measures']]
  currentDat <- projProperties[['activeDat']]
  s <- if(!isEmpty(currentDat)){
    isolate(datList[[currentDat]][['dynamicProperties']][['measures']])
  } else ''
  choices <- if(!isEmpty(currentDat)) datList[[currentDat]][['fieldNames']]()
  updateSelectizeInput(session, "measures", choices=null2String(choices),
                       selected=null2String(s))
})

## Add data source from text file
observe({
  # input$file1 will be NULL initially. After the user selects
  # and uploads a file, it will be a data frame with 'name',
  # 'size', 'type', and 'datapath' columns. The 'datapath'
  # column will contain the local filenames where the data can
  # be found.
  inFile <- input[['file']]
  isolate({
    if (!is.null(inFile)){
      dat  <- fread(inFile$datapath, header="auto", sep="auto")
      fileN <- paste('file_',newGuid(),sep='')
      existingNames <- names(datListNames())
      ## make sure the new name is different
      newName <- make.unique(c(existingNames, inFile$name), sep='_')[length(existingNames)+1]

      datList[[fileN]] <<- createNewDatClassObj(dat, name=newName,
                                                nameOriginal=inFile$name, type='file')
      projProperties[['activeDat']] <<- fileN
      triggerUpdateInput('activeDat')
    }
  })

})

output$uploadingTextFile <- reactive({
  TRUE
})
outputOptions(output, "uploadingTextFile", suspendWhenHidden=FALSE)

output$datPreview <- renderDataTable({
  currentDat <- projProperties[['activeDat']]
  if(!isEmpty(currentDat)){
    datPrev <- copy(datList[[currentDat]][['datR']]())  # use of copy is necessary since setnames modify by reference
    setnames(datPrev, names(datList[[currentDat]][['fieldNames']]()))
    datPrev
  }
})


## Text file import calibration

#   observe({
#     hh <- input[['header']]; ss <- input[['sep']]; qq <- input[['quote']]
#     if(uploadingData){
#       inFile <- isolate(input[['file']])
#
#       if (!is.null(inFile)){
#
#         dat  <- read.csv(inFile$datapath, header=hh, sep=ss, quote=qq)
#         fileN <- isolate(input$datList)
#         datList[[fileN]] <<- dat
#
#         defaultMeasures <- colnames(dat)[apply(dat,2,is.numeric)]
#         updateSelectizeInput(session, "measures", choices=colnames(dat), selected=defaultMeasures)
#
#         output$datPreview <- renderDataTable({
#           (dat)
#         })
#
#         metaDataSources[[fileN]][['data']] <<- dat
#         metaDataSources[[fileN]][['measures']] <<- defaultMeasures
#
#       }
#     }
#   })



####################################################
## Project saving and loading
####################################################
shrink <- function(x){
  if(is.list(x) && !is.data.frame(x)){
    if(is.reactivevalues(x)){
      x <- lapply(reactiveValuesToList(x), function(y){
        if(typeof(y)!='closure') shrink(y) else NULL
      })
      attr(x, 'wasReavtive') <- TRUE
    } else {
      x <- lapply(x, shrink)
    }
  } else {
    if(typeof(x)!='closure') x else NULL
  }
  x
}

output$downloadProject <- downloadHandler(
  filename = function() { 'MyProject.sData' },
  content = function(file) {
    isolate({

      allData <- list(pp=shrink(projProperties),
                      dl=lapply(datList, function(d){
                        list('staticProperties'=d[['staticProperties']],
                             'dynamicProperties'=shrink(d[['dynamicProperties']]))
                      }),
                      sl=lapply(sheetList, function(d){
                        list('dynamicProperties'=shrink(d[['dynamicProperties']]))
                      }),
                      docl=shrink(docList))
      save(allData, file=file)

    })
  }
)


loadProject <- function(file, replaceOrMerge='replace'){
  load(file)

  if(replaceOrMerge=='replace'){
    for(n in names(datList)) datList[[n]] <<- NULL; projProperties[['activeDat']] <<- NULL
    for(n in names(sheetList)) sheetList[[n]] <<- NULL; projProperties[['activeSheet']] <<- NULL
    for(n in names(docList)) docList[[n]] <<- NULL; projProperties[['activeDoc']] <<- NULL
  }

  for(n in names(allData$pp)){
    if(is.null(projProperties[[n]]) || projProperties[[n]] != allData$pp[[n]]){
      projProperties[[n]] <<- allData$pp[[n]]
    }
  }

  for(di in names(allData$dl)){
    if(is.null(datList[[di]])){ # new data
      datList[[di]] <<- DatClass$new('staticProperties'=allData$dl[[di]][['staticProperties']])
      datList[[di]][['dynamicProperties']] <<- reactiveValues()

    }
    for(n in names(allData$dl[[di]][['dynamicProperties']])){
      x <- allData$dl[[di]][['dynamicProperties']][[n]]
      if(n=='fieldsList'){
        if(is.null(datList[[di]][['dynamicProperties']][[n]])) datList[[di]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(datList[[di]][['dynamicProperties']][[n]][[n1]])) datList[[di]][['dynamicProperties']][[n]][[n1]] <<- reactiveValues()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              datList[[di]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
            }
          } else {
            datList[[di]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        datList[[di]][['dynamicProperties']][[n]] <<- x
      }
    }
    datList[[di]]$setDatDependencies()
  }

  for(si in names(allData$sl)){
    if(is.null(sheetList[[si]])){ # new sheet
      sheetList[[si]] <<- createNewSheetObj(withPlotLayer=FALSE)
      setSheetReactives(si)
    }
    for(n in names(allData$sl[[si]][['dynamicProperties']])){
      x <- allData$sl[[si]][['dynamicProperties']][[n]]
      if(n=='layerList'){
        if(is.null(sheetList[[si]][['dynamicProperties']][[n]])) sheetList[[si]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(sheetList[[si]][['dynamicProperties']][[n]][[n1]]))
              sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- createNewLayer()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              if(n2=='aesList'){
                names3 <- names(x[[n1]][[n2]])
                for(n3 in names3){
                  if(is.reactivevalues(x[[n1]][[n2]][[n3]])){
                    names4 <- names(x[[n1]][[n2]][[n3]])
                    for(n4 in names4){
                      if(typeof(x[[n1]][[n2]][[n3]][[n4]]) != 'closure')
                        sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]][[n4]] <<- x[[n1]][[n2]][[n3]][[n4]]
                    }
                    setAesReactives(si,n1,n3)
                  } else {
                    sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]] <<- x[[n1]][[n2]][[n3]]
                  }
                }
              } else {
                sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
              }
            }
          } else {
            sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        sheetList[[si]][['dynamicProperties']][[n]] <<- x
      }
    }
  }

  for(di in names(allData$docl)){
    if(is.null(docList[[di]])){ # new doc
      docList[[di]] <<- reactiveValues()

    }
    for(n in names(allData$docl[[di]])){
      x <- allData$docl[[di]][[n]]
      docList[[di]][[n]] <<- x
    }
  }

  ## update all UI
  sapply(unique(c(names(input), names(updateInput))), triggerUpdateInput)
  updateTabsetPanel(session, 'mainNavBar', selected='Visualize')
}

observe({
  inFile <- input[['loadProject']]
  isolate({
    if (!is.null(inFile)){
      loadProject(file=inFile$datapath, replaceOrMerge=input[['loadProjectAction']])
    }
  })

})

observe({
  v <- input$openSampleProj
  isolate({
    file <- paste('samples', input[['sampleProj']], sep='/')
    if(v && file.exists(file)){
      loadProject(file=file, 'replace')
    }
  })
})
#' Prepare the datapoll
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   if (!(NROW (H) %in% dim(HP)))
     stop ("The number of species in H and HP don't match")
   if (!(NROW (P) %in% dim(HP)))
     stop ("The number of species in P and HP don't match")
   if (!all(rownames(HP) %in% rownames (H)))
     stop ("The species names H and HP don't match")
   if (!all(rownames(HP) %in% rownames (P)))
     stop ("The species names P and HP don't match")
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}
#' Prepare the datapoll
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   if (!(NROW (H) %in% dim(HP)))
     stop ("The number of species in H and HP don't match")
   if (!(NROW (P) %in% dim(HP)))
     stop ("The number of species in P and HP don't match")
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}


####################################################
## Project saving and loading
####################################################
output$downloadProject <- downloadHandler(
  filename = function() { 'MyProject.sData' },
  content = function(file) {
    isolate({
      for(di in names(datList)){
        datList[[di]]$removeDatDependencies()
      }
      allData <- list(pp=reactiveValuesToList(projProperties),
                      dl=datList,
                      sl=sheetList,
                      docl=docList)
      save(allData, file=file)
      for(di in names(datList)){
        datList[[di]]$setDatDependencies()
      }
    })
  }
)


loadProject <- function(file, replaceOrMerge='replace'){
  load(file)

  if(replaceOrMerge=='replace'){
    for(n in names(datList)) datList[[n]] <<- NULL; projProperties[['activeDat']] <<- NULL
    for(n in names(sheetList)) sheetList[[n]] <<- NULL; projProperties[['activeSheet']] <<- NULL
    for(n in names(docList)) docList[[n]] <<- NULL; projProperties[['activeDoc']] <<- NULL
  }

  for(n in names(allData$pp)){
    if(is.null(projProperties[[n]]) || projProperties[[n]] != allData$pp[[n]]){
      projProperties[[n]] <<- allData$pp[[n]]
    }
  }

  for(di in names(allData$dl)){
    if(is.null(datList[[di]])){ # new data
      datList[[di]] <<- DatClass$new('staticProperties'=allData$dl[[di]][['staticProperties']])
      datList[[di]][['dynamicProperties']] <<- reactiveValues()

    }
    for(n in names(allData$dl[[di]][['dynamicProperties']])){
      x <- allData$dl[[di]][['dynamicProperties']][[n]]
      if(n=='fieldsList'){
        if(is.null(datList[[di]][['dynamicProperties']][[n]])) datList[[di]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(datList[[di]][['dynamicProperties']][[n]][[n1]])) datList[[di]][['dynamicProperties']][[n]][[n1]] <<- reactiveValues()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              datList[[di]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
            }
          } else {
            datList[[di]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        datList[[di]][['dynamicProperties']][[n]] <<- x
      }
    }
    datList[[di]]$setDatDependencies()
  }

  for(si in names(allData$sl)){
    if(is.null(sheetList[[si]])){ # new sheet
      sheetList[[si]] <<- createNewSheetObj(withPlotLayer=FALSE)
    }
    for(n in names(allData$sl[[si]][['dynamicProperties']])){
      x <- allData$sl[[si]][['dynamicProperties']][[n]]
      if(n=='layerList'){
        if(is.null(sheetList[[si]][['dynamicProperties']][[n]])) sheetList[[si]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(sheetList[[si]][['dynamicProperties']][[n]][[n1]]))
              sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- createNewLayer()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              if(n2=='aesList'){
                names3 <- names(x[[n1]][[n2]])
                for(n3 in names3){
                  if(is.reactivevalues(x[[n1]][[n2]][[n3]])){
                    names4 <- names(x[[n1]][[n2]][[n3]])
                    for(n4 in names4){
                      if(typeof(x[[n1]][[n2]][[n3]][[n4]]) != 'closure')
                        sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]][[n4]] <<- x[[n1]][[n2]][[n3]][[n4]]
                    }
                    setAesReactives(si,n1,n3)
                  } else {
                    sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]] <<- x[[n1]][[n2]][[n3]]
                  }
                }
              } else {
                sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
              }
            }
          } else {
            sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        sheetList[[si]][['dynamicProperties']][[n]] <<- x
      }
    }
  }
  setSheetReactives()

  for(di in names(allData$docl)){
    if(is.null(docList[[di]])){ # new doc
      docList[[di]] <<- reactiveValues()

    }
    for(n in names(allData$docl[[di]])){
      x <- allData$docl[[di]][[n]]
      docList[[di]][[n]] <<- x
    }
  }

  ## update all UI
  sapply(unique(c(names(input), names(updateInput))), triggerUpdateInput)
  updateTabsetPanel(session, 'mainNavBar', selected='Visualize')
}

observe({
  inFile <- input[['loadProject']]
  isolate({
    if (!is.null(inFile)){
      loadProject(file=inFile$datapath, replaceOrMerge=input[['loadProjectAction']])
    }
  })

})

observe({
  v <- input$openSampleProj
  isolate({
    file <- paste('samples', input[['sampleProj']], sep='/')
    if(v && file.exists(file)){
      loadProject(file=file, 'replace')
    }
  })
})

source('helpers.r', local=TRUE)

shinyServer(function(input, output, session) {

  sessionEnv <- environment()
  projProperties <- reactiveValues('activeDat'='')
  sessionProperties <- reactiveValues()
  updateInput <- reactiveValues('activeDat'=0,'datName'=0,'activeField'=0,'fieldName'=0,'measures'=0,
                                'activeSheet'=0,'sheetName'=0,'sheetDatId'=0,'combineMeasures'=0,
                                'sheetColumns'=0,'sheetRows'=0,'sheetOutput'=0,'sheetPlotLayer'=0,
                                'sheetLayerAes'=0,'aesField'=0,'aesAggregate'=0,'aesAggFun'=0,'aesDiscrete'=0,
                                'layerGeom'=0,'layerStatType'=0,'layerYFun'=0,
                                'layerPositionType'=0, 'layerPositionWidth'=0, 'layerPositionHeight'=0,
                                'activeDoc'=0,'docName'=0,'docRmd'=0,'rmdOuputFormat'=0,
                                'customizeItem'=0, 'plotXlab'=0, 'plotYlab'=0, 'plotTitle'=0,
                                'textFamily'=0, 'textFace'=0, 'textColor'=0,'textSize'=0, 'textHjust'=0, 'textVjust'=0,
                                'textAngle'=0, 'textLineheight'=0)

  triggerUpdateInput <- function(inputId){
    if(is.null(updateInput[[inputId]])) updateInput[[inputId]] <- 0
    updateInput[[inputId]] <- updateInput[[inputId]] + 1
  }

  datList <- list()
  makeReactiveBinding('datList')
  datListNames <- reactive({
    if(length(datList)){
      x <- names(datList)
      names(x) <- sapply(datList, function(y) y[['dynamicProperties']][['name']])
      x
    } else c('')
  })

  docList <- list()
  makeReactiveBinding('docList')
  docListNames <- reactive({
    if(length(docList)){
      x <- names(docList)
      names(x) <- sapply(docList, function(y) y[['name']])
      x
    } else c('')
  })
  addDoc <- function(){
    newDoc <- paste("Doc_",newGuid(),sep="")
    existingNames <- names(docListNames())
    ## make sure the new name is different
    newName <- make.unique(c(existingNames, 'Doc'), sep='_')[length(existingNames)+1]

    docObj <- reactiveValues('name'=newName, 'rmdOuputFormat'='pdf_document')
    docList[[newDoc]] <<- docObj
    projProperties[['activeDoc']] <- newDoc
  }
  isolate(addDoc())



  sheetList <- list()
  makeReactiveBinding('sheetList')

  sheetListNames <- reactive({
    if(length(sheetList)){
      x <- names(sheetList)
      names(x) <- sapply(sheetList, function(y) y[['dynamicProperties']][['name']])
      x
    } else c('')
  })
  setAesReactives <- function(currentSheet, currentLayer, currentAes){
      sheetList[[currentSheet]][['dynamicProperties'
                                 ]][['layerList']][[currentLayer]][['aesList']][[currentAes]][['canFieldBeContinuous']] <<- reactive({
                                   aes <- sheetList[[currentSheet]][['dynamicProperties'
                                                                     ]][['layerList']][[currentLayer]][['aesList']][[currentAes]]
                                   measures <- sheetList[[currentSheet]][['measuresR']]()
                                   field <- aes[['aesField']]
                                   if(isEmpty(field)){
                                     field <- sheetList[[currentSheet]][['dynamicProperties'
                                               ]][['layerList']][['Plot']][['aesList']][[currentAes]][['aesField']]
                                   }
                                   aes[['aesAggregate']] || (!isEmpty(field) && field %in% measures)
                                 })
  }
  addSheet <- function(){
    newSheet <- paste("Sheet_",newGuid(),sep="")
    existingNames <- names(sheetListNames())
    ## make sure the new name is different
    newName <- make.unique(c(existingNames, 'Sheet'), sep='_')[length(existingNames)+1]

    sheetObj <- createNewSheetObj(newName)
    sheetList[[newSheet]] <<- sheetObj
    projProperties[['activeSheet']] <- newSheet

    for(currentLayer in names(sheetObj[['dynamicProperties']][['layerList']])){
      for(currentAes in names(sheetObj[['dynamicProperties']][['layerList']][[currentLayer]][['aesList']])){
        setAesReactives(newSheet, currentLayer, currentAes)
      }
    }
  }
  isolate(addSheet())



  ## create sheet reactives and defaults
  setSheetReactives <- function(){#browser()
    for(currentSheet1 in names(sheetList)){
      isolate(local({
        currentSheet <- currentSheet1

        if(isFieldUninitialized(sheetList[[currentSheet]],'layerNames')){
          sheetList[[currentSheet]][['layerNames']] <<- reactive({
            sl <- isolate(sheetList)
            if(!isEmpty(sl[[currentSheet]][['dynamicProperties']][['layerList']])){
              names(sl[[currentSheet]][['dynamicProperties']][['layerList']])
            } else c()
          })
        }


        if(isFieldUninitialized(sheetList[[currentSheet]],'fieldNames')){
          sheetList[[currentSheet]][['fieldNames']] <<- reactive({
            sl <- isolate(sheetList)
            dl <- isolate(datList)
            currentDat <- sl[[currentSheet]][['dynamicProperties']][['datId']]
            combineMeasures <- sl[[currentSheet]][['dynamicProperties']][['combineMeasures']]

            if(!isEmpty(currentDat)){
              currentDatObj <- dl[[currentDat]]
              if(combineMeasures) currentDatObj[['moltenNames']]() else currentDatObj[['fieldNames']]()
            }
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'measuresR')){
          sheetList[[currentSheet]][['measuresR']] <<- reactive({
            sl <- isolate(sheetList)
            dl <- isolate(datList)
            currentDat <- sl[[currentSheet]][['dynamicProperties']][['datId']]
            combineMeasures <- sl[[currentSheet]][['dynamicProperties']][['combineMeasures']]

            if(!isEmpty(currentDat)){
              currentDatObj <- dl[[currentDat]]
              if(combineMeasures) c(MoltenMeasuresName) else currentDatObj[['dynamicProperties']][['measures']]
            }
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'datR')){
          sheetList[[currentSheet]][['datR']] <<- reactive({
            sl <- isolate(sheetList)
            dl <- isolate(datList)
            currentDat <- sl[[currentSheet]][['dynamicProperties']][['datId']]
            combineMeasures <- sl[[currentSheet]][['dynamicProperties']][['combineMeasures']]

            if(!isEmpty(currentDat)){
              currentDatObj <- dl[[currentDat]]
              if(combineMeasures) currentDatObj[['moltenDat']]() else currentDatObj[['datR']]()
            }
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'tableR')){
          sheetList[[currentSheet]][['tableR']] <<- reactive({
            sl <- isolate(sheetList)
            tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
                       (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )
          })
        }



        if(isFieldUninitialized(sheetList[[currentSheet]],'plotCore')){
          ## Helpful ggplot references:
          ## http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/
          ## http://www.ling.upenn.edu/~joseff/rstudy/summer2010_ggplot2_intro.html
          ## http://learnr.wordpress.com/2009/03/17/ggplot2-barplots/
          ## http://sape.inf.usi.ch/quick-reference/ggplot2
          ## http://ggplot2.org/book/

          ## http://stackoverflow.com/questions/20249653/insert-layer-underneath-existing-layers-in-ggplot2-object

          ## current solutions:
          ## http://blog.ouseful.info/2011/08/03/working-visually-with-the-ggplot2-web-interface/  (no support for saving project)
          ## Deducer


          sheetList[[currentSheet]][['plotCore']] <<- reactive({
            sl <- isolate(sheetList)
            layerList <- sl[[currentSheet]][['dynamicProperties']][['layerList']]
            cc <- empty2NULL(sl[[currentSheet]][['dynamicProperties']][['columns']])
            rr <- empty2NULL(sl[[currentSheet]][['dynamicProperties']][['rows']])
            datSheet <- sl[[currentSheet]][['datR']]()
            validate(need(!isEmpty(datSheet), label='Data'))

            gg <- NULL
            for(i in c('bar','line','point')) update_geom_defaults(i, list(colour = "darkblue", fill = "darkblue"))

            aes.base <- layerList[['Plot']][['aesList']]
            for(currentLayer in names(layerList)){
              layer.current <- layerList[[currentLayer]]

              stat <- empty2NULL(layer.current[['statType']])
              geom <- empty2NULL(layer.current[['geom']])
              fun.y <- empty2NULL(layer.current[['yFun']])
              position <- empty2NULL(layer.current[['layerPositionType']])
              pWidth <- empty2NULL(layer.current[['layerPositionWidth']])
              pHeight <- empty2NULL(layer.current[['layerPositionHeight']])

              if(!is.null(geom) && !is.null(stat) && !is.null(position)){
                ## get effective aesthetics taking into account of inheritance
                aes.current <- layer.current[['aesList']][isolate(unlist(layer.current[['aesChoices']], use.names=FALSE))]
                aes.current <- sapply(names(aes.current), function(n){
                  temp <- reactiveValuesToList(aes.current[[n]]) # converting to list so we can modify it
                  if(are.vectors.different(temp[['aesMapOrSet']],'set')){
                    temp[['aesField']] <- ifempty(temp[['aesField']], empty2NULL(aes.base[[n]][['aesField']]))
                    if(!is.null(temp[['aesField']])){
                      if(temp[['aesAggregate']]){
                        temp[['aesFieldOriginal']] <- temp[['aesField']]
                        temp[['aesField']] <- paste(temp[['aesFieldOriginal']], temp[['aesAggFun']], sep='_')
                      }
                    }
                  }
                  temp
                }, simplify=FALSE)
                aes.current <- aes.current[sapply(aes.current,
                     function(x) {
                       isSetting <- !are.vectors.different(x[['aesMapOrSet']],'set')
                       (isSetting && !isEmpty(x[['aesValue']])) || (!isSetting && !isEmpty(x[['aesField']]))
                     })]

                borderColor <- aes.current[['aesBorderColor']]
                aes.current[['aesBorderColor']] <- NULL
                if(geom %in% c('bar','area','boxplot')){
                  aes.current[['aesFill']] <- aes.current[['aesColor']]
                  aes.current[['aesColor']] <- borderColor
                }

                ## aesthetics validation
                validate(
                  need(!is.null(aes.current[['aesX']]), label='X')
                )
                if(stat=='identity'){
                  validate(
                    need(!is.null(aes.current[['aesY']]), label='Y')
                  )
                }
                if(geom=='text'){
                  validate(
                    need(!is.null(aes.current[['aesLabel']]), label='Label')
                  )
                }
                if(geom=='boxplot' && stat=='identity'){
                  validate(
                    need(!is.null(aes.current[['aesYmin']]), label='Y Min')
                  )
                  validate(
                    need(!is.null(aes.current[['aesYmax']]), label='Y Max')
                  )
                  validate(
                    need(!is.null(aes.current[['aesLower']]), label='Y Lower')
                  )
                  validate(
                    need(!is.null(aes.current[['aesMiddle']]), label='Y Middle')
                  )
                  validate(
                    need(!is.null(aes.current[['aesUpper']]), label='Y Upper')
                  )
                }
                if(position=='fill'){
                  validate(
                    need(!is.null(aes.current[['aesYmax']]), label='Y Max')
                  )
                }

                i.map <- sapply(aes.current, function(x) are.vectors.different(x[['aesMapOrSet']],'set'))
                aes.map <- aes.current[i.map]
                aes.set <- aes.current[!i.map]

                ## aggregate data for layer
                datLayer <- datSheet
                aes.toAgg <- aes.map[sapply(aes.map, function(x) x[['aesAggregate']])]
                if(length(aes.toAgg)){
                  # get rid of duplicates to avoid aggregating the same field the same way twice
                  dups <- duplicated(sapply(aes.toAgg, function(x) x[['aesField']]))
                  aes.toAgg <- aes.toAgg[!dups]

                  # some validation
                  agg.fields <- sapply(aes.toAgg, function(x) x[['aesFieldOriginal']])
                  overlaps <- intersect(agg.fields, c(rr,cc))
                  validate(need(isEmpty(overlaps), 'Can not aggregate fields used in faceting.'))

                  # build the j-expression from string; there may be a better way
                  agg.str <- sapply(aes.toAgg, function(x) paste(x[['aesAggFun']], '(', x[['aesFieldOriginal']], ')', sep=''))
                  agg.str <- paste(sapply(aes.toAgg, function(x) x[['aesField']]), agg.str, sep='=', collapse=', ')
                  agg.str <- paste0('list(', agg.str, ')')
                  agg.exp <- parse(text=agg.str)[[1]]
                  groupBy <- unique(c(rr,cc,sapply(aes.map[sapply(aes.map, function(x) !(x[['aesAggregate']]))],
                                                   function(x) x[['aesField']])))
                  datLayer <- eval(bquote(datSheet[, .(agg.exp), by=.(groupBy)]))

                  if(currentLayer=='Plot'){
                    ## add to dataList
                    outDf <- datLayer
                    isolate({
                      sheetNameDat <- convertSheetNameToDatName(sheetList[[currentSheet]][['dynamicProperties']][['name']])
                      if(is.null(datList[[currentSheet]])){
                        datList[[currentSheet]] <<- createNewDatClassObj(outDf, name=sheetNameDat, type='sheet')
                      } else {
                        datList[[currentSheet]][['dynamicProperties']][['dat']] <<- outDf
                        datList[[currentSheet]][['dynamicProperties']][['measures']] <<- intersect(datList[[currentSheet]][['dynamicProperties']][['measures']],
                                                                                                   getDefaultMeasures(outDf))
                        ## add new fields, delete outdated fields, leave common fields alone since they might have user customizations
                        newFields <- getDefaultFieldsList(outDf)
                        oldList <- names(datList[[currentSheet]][['dynamicProperties']][['fieldsList']])
                        newList <- names(newFields)
                        for(n in setdiff(newList, oldList)){
                          datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- newFields[[n]]
                        }
                        for(n in setdiff(oldList, newList)){
                          datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- NULL
                        }
                      }
                    })
                  }
                }


                ## get ready to ggplot
                if(stat=='summary'){ # need to re-point all the other aesthetics to ..y..
                  sapply(setdiff(names(aes.map), 'aesY'),
                         function(x){
                           if(aes.map[[x]][['aesField']]==aes.map[['aesY']][['aesField']]){
                             aes.map[[x]][['aesField']] <<- InternalY
                           }
                         })
                }


                ## list of set values
                aes.set.args <- list()
                if(length(aes.set)){
                  aes.set.args <- lapply(aes.set,
                                     function(x) {
                                       x[['aesValue']]
                                     }
                  )
                  names(aes.set.args) <- tolower(substring(names(aes.set), 4)) # get rid of the 'aes' prefix
                }

                aes.args <- lapply(aes.map,
                                   function(x) {
                                     if(x[['canFieldBeContinuous']]()){
                                       paste(ifelse(x[['aesDiscrete']], 'as.factor(', 'as.numeric('),
                                             x[['aesField']], ')', sep='')
                                     } else {
                                       x[['aesField']]
                                     }
                                   }
                                   )
                names(aes.args) <- tolower(substring(names(aes.map), 4)) # get rid of the 'aes' prefix

                aess <- do.call('aes_string', aes.args)
                position <- do.call(paste('position', position, sep='_'),
                                    list(width=pWidth, height=pHeight))
                #browser()
                if(is.null(gg)) gg <- ggplot()
                gg <- gg + do.call(paste('geom',geom,sep='_'),
                                   c(aes.set.args, list(mapping=aess, data=datLayer, stat=stat, fun.y=fun.y, position=position)))

              }
            }
            if(!is.null(gg)){
              if(!isEmpty(cc) || !isEmpty(rr)){
                gg <- gg + facet_grid(as.formula(paste(names2formula(rr), names2formula(cc), sep=" ~ ")))
              }
              gg <- gg + theme_bw()
            }
            gg
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'plotR')){
          sheetList[[currentSheet]][['plotR']] <<- reactive({
            sl <- isolate(sheetList)
            layerList <- sl[[currentSheet]][['dynamicProperties']][['layerList']]
            aes.base <- layerList[['Plot']][['aesList']]

            fieldNames <- sl[[currentSheet]][['fieldNames']]()

            gg <- sl[[currentSheet]][['plotCore']]()
            if(!is.null(gg)){
              themeElementCalls <-
                sapply(sheetList[[currentSheet]][['dynamicProperties']][['formatting']],
                       simplify = FALSE, USE.NAMES = TRUE,
                       function(cus){
                         eleBlank <- attr(cus, 'elementBlank')
                         if(!is.null(eleBlank) && eleBlank) return(element_blank())
                         if(!isEmpty(cus)){
                           cus1 <- cus[!sapply(cus, isEmpty)]
                           names(cus1) <- tolower(substring(names(cus1), 5)) # get rid of the 4-char prefix like 'text', 'rect', etc.
                           switch(attr(cus, 'type'),
                                  'unit'=if(!isEmpty(cus1$x) && !isEmpty(cus1$units)) do.call('unit', cus1),
                                  'character'=if(!isEmpty(cus1$mainvalue)){
                                    if(cus1$mainvalue!='custom_'){
                                      cus1$mainvalue
                                    } else {
                                      c(cus1$altvalue1, cus1$altvalue2)
                                    }
                                  },
                                  do.call(attr(cus, 'type'), cus1))
                         }
                       })
              themeElementCalls <- themeElementCalls[!sapply(themeElementCalls, is.null)]


              gg <- gg + xlab(sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']]) +
                ylab(sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']]) +
                ggtitle(sheetList[[currentSheet]][['dynamicProperties']][['plotTitle']])
              if(length(themeElementCalls)){
                gg <- gg + do.call('theme', themeElementCalls)
              }

            }
            gg
          })
        }

      }))
    }
  }

  observe({
    setSheetReactives()
  }, priority=10)



  isDatBasedonSheet <- function(datId, sheetId){
    if(!is.null(datList[[datId]])){
      while(datList[[datId]][['staticProperties']][['type']] == 'sheet'){
        if(datId==sheetId) return(TRUE)
        datId <- sheetList[[datId]][['dynamicProperties']][['datId']]
      }
    }
    FALSE
  }





  source('data.r', local=TRUE)
  source('sheets.r', local=TRUE)
  source('sheetsCustomize.r', local=TRUE)
  source('project.r', local=TRUE)
  source('docs.r', local=TRUE)

  observe({
    v <- input$importFonts
    isolate({
      if(!is.null(v) && v==1){  # so it's executed the first time the button is clicked
        if(!require(extrafont)) install.packages('extrafont')
        extrafont::font_import(prompt=FALSE) # this only needs run once but takes a long time
        # todo: alert user
      }
    })
  })

})


####by Heather E. Wheeler 20140602####
"%&%" = function(a,b) paste(a,b,sep="")
args <- commandArgs(trailingOnly=T)
date <- Sys.Date() 
###############################################
### Directories & Variables
 
cri = T #on cri cluster?
if(cri) precri = "/group/im-lab/" else precri = '/'

my.dir <- precri %&% "nas40t2/hwheeler/PrediXcan_CV/GTEx_2014-06013_release/"
 
#tissue <- "Nerve - Tibial" ###check GTEx_Analysis_2014-06-13.SampleTissue.annot for available tissues###
tissue <- "Thyroid"
tis <- "GTEx-Thy"
Nk <- 15 ##number of peer factors to calculate, recommend 25% of sample size, but no more than 100, GTEx included 15 in pilot analyses
 
################################################
### Functions & Libraries
 
#library(SNPRelate)
library(peer)
library(preprocessCore)
#library(GenABEL)
##if can't install GenABEL
source(my.dir %&% 'GenABEL/R/ztransform.R')
source(my.dir %&% 'GenABEL/R/rntransform.R')
 
################################################
sam <- read.table(my.dir %&% "GTEx_Analysis_2014-06-13.SampleTissue.annot",header=T,sep="\t") 
### above file includes SAMPID and SMTSD from: 
### /group/im-lab/nas40t2/haky/Data/dbGaP/GTEx/41400/gtex/exchange/GTEx_phs000424/exchange/analysis_releases/GTEx_Analysis_2014-06-13/sample_annotations/GTEx_Data_2014-06-13_Annotations_SampleAttributesDS.txt
sample <- subset(sam,SMTSD == tissue) ### pull sample list of chosen tissue###
 
expidlist <- scan("GTEx_Analysis_2014-06-13.RNA-seq.ID.list","character")
expgenelist <- scan("GTEx_Analysis_2014-06-13.RNA-seq.GENE.list","character")
exp <- scan("GTEx_Analysis_2014-06-13.RNA-seq.GENExID")
expdata <- matrix(exp, ncol=length(expidlist), byrow=T)
t.expdata <- t(expdata)
rownames(t.expdata) <- expidlist
colnames(t.expdata) <- expgenelist

gencodefile <- my.dir %&% "gencode.v18.genes.patched_contigs.summary.protein"
gencode <- read.table(gencodefile) ##split into 10 files, call each from run_1_CV_GTEx_polyscore_PrediXcan_subset*.sh
rownames(gencode) <- gencode[,5]
t.expdata <- t.expdata[,intersect(colnames(t.expdata),rownames(gencode))] ###pull protein coding gene expression data

tissue.exp <- t.expdata[intersect(rownames(t.expdata),sample$SAMPID),] ###pull expression data for chosen tissue###
expsamplelist <- rownames(tissue.exp) ###samples with exp data###
substr.expsamplelist <- substr(expsamplelist,1,10) ###to match with genotype data###
 
famfile <- my.dir %&% "GTEx_Analysis_2014-06-13_OMNI_2.5M_5M_451Indiv_Pheno_2for5M_1for2.5M.fam"
fam <- read.table(famfile)
gtsamplelist <- fam$V1
substr.gtsamplelist <- substr(gtsamplelist,1,10) ###to match with exp data###
rownames(fam) <- substr.gtsamplelist
samplelist <- intersect(substr.gtsamplelist,substr.expsamplelist)
nsample <- length(samplelist)
tissue.exp.substr <- tissue.exp
for(id in samplelist){  ####take mean of exp for samples with >1 RNA Seq dataset
        matchexp <- tissue.exp.substr[substr(rownames(tissue.exp.substr),1,10)==id,]
        if(is.array(matchexp)=='TRUE'){
                expmean <- colMeans(matchexp)
                for(i in rownames(matchexp)){
                        tissue.exp.substr[i,] <- expmean
                }
        }
}


rownames(tissue.exp.substr) <- substr.expsamplelist ###change rownames of tissue.exp to match with genotypes###
exp.w.geno <- tissue.exp.substr[samplelist,] ###get expression of samples with genotypes###
explist <- subset(colMeans(exp.w.geno), colMeans(exp.w.geno)>0) ###pull genes with mean expression > 0###
explist <- names(explist)
exp.w.geno <- exp.w.geno[,explist]
 

###get first 3 PCs from genos, as in GTEx
pc.matrix<-read.table(my.dir %&% "GTEx_Analysis_2014-06-13_OMNI_2.5M_5M_451Indiv_PostImput_20genotPCs.txt",header=T)
pcs3 <- pc.matrix[,3:5]
pclist <- substr(pc.matrix[,1],1,10)
rownames(pcs3) <- pclist
pcs <- as.matrix(pcs3[samplelist,])

###pull gender, used as cov in GTEx
famsubset <- fam[samplelist,]
gender <- famsubset$V5
names(gender)<-rownames(famsubset)

###quantile normalize and transform to standard normal exp.w.geno matrix, as in GTEx###
t.exp.w.geno <- t(exp.w.geno)

rowtable<-function(x) length(table(x))>2 ##function to determine if more than 2 exp levels per gene
nonbin<-apply(t.exp.w.geno,1,rowtable) ##apply to matrix
t.exp.w.geno <- t.exp.w.geno[nonbin,] ##remove binary genes from matrix

qn.t.exp.w.geno <- normalize.quantiles(t.exp.w.geno) ##quantile normalize
rn.qn.t.exp.w.geno <- apply(qn.t.exp.w.geno,1,"rntransform") ##rank transform to normality & transposes, not sure why?##

###Now we can create the model object, ### from https://github.com/PMBio/peer/wiki/Tutorial

model = PEER()

###set the observed data,

PEER_setPhenoMean(model,as.matrix(rn.qn.t.exp.w.geno))

dim(PEER_getPhenoMean(model))

###(NULL response means no error here), say we want to infer K=20 hidden confounders,

PEER_setNk(model,Nk)

PEER_getNk(model)

####and perform the inference. ###for Nk=20 and GTEx-NT, it took 323 iterations, for Nk=15 and GTEx-NT, it took 37 iterations

PEER_update(model)

factors = PEER_getX(model)
rownames(factors) <- rownames(exp.w.geno)
write.table(factors,file <- tis %&% "." %&% Nk %&% ".PEER.factors." %&% date %&% ".txt", quote=F)
weights = PEER_getW(model)
precision = PEER_getAlpha(model)
residuals = PEER_getResiduals(model)

pdf(file= tis %&% "." %&% Nk %&% ".PEER.factors.plotmodel." %&% date %&% ".pdf")
PEER_plotModel(model)
dev.off()

adj.exp.matrix<-matrix(NA,nrow=dim(rn.qn.t.exp.w.geno)[1],ncol=dim(rn.qn.t.exp.w.geno)[2])

for(i in 1:dim(rn.qn.t.exp.w.geno)[2]){
	res <- summary(lm(rn.qn.t.exp.w.geno[,i] ~ factors + pcs + gender, na.action=na.exclude))
	resid <- residuals(res)
	adj.exp.matrix[,i] <- resid
}

colnames(adj.exp.matrix) <- rownames(t.exp.w.geno)
rownames(adj.exp.matrix) <- colnames(t.exp.w.geno)

write.table(adj.exp.matrix, file= tis %&% ".exp.adj." %&% Nk %&% "PEERfactors.3PCs.gender.IDxGENE", quote=F, row.names=F, col.names=F)
write(colnames(adj.exp.matrix), file = tis %&% ".exp.adj." %&% Nk %&% "PEERfactors.3PCs.gender.GENE.list", ncolumns=1)
write(rownames(adj.exp.matrix), file = tis %&% ".exp.adj." %&% Nk %&% "PEERfactors.3PCs.gender.ID.list", ncolumns=1)
#' @title Pobieranie danych o szkołach.
#' @description
#' Funkcja pobiera z bazy dane o szkołach - o ich typie i specyfice, nazwie, adresowe
#' i o lokalizacji.
#' @param lata wektor liczb całkowitych - lata, których mają dotyczyć dane (dla każdej
#' szkoły zwrócone zostaną tylko najświeższe dane w ramach tego okresu)
#' @param typySzkol opcjonalny wektor tekstowy z typami szkół, które mają zostać zwrócone
#' (lub NULL - zwraca informacje o wszystkich szkołach)
#' @param idOke wartość logiczna (domyślnie FALSE) - czy dołączać kody OKE szkół?
#' @param daneAdresowe wartość logiczna (domyślnie FALSE) - czy dołączać nazwę i dane
#' adresowe?
#' @return data frame
#' @import dplyr
#' @import ZPD
#' @export
pobierz_dane_szkol = function(lata, typySzkol = NULL, idOke = FALSE,
                              daneAdresowe = FALSE) {
  stopifnot(is.numeric(lata)        , length(lata) > 0,
            is.character(typySzkol) | is.null(typySzkol),
            is.logical(idOke)       , length(idOke) == 1,
            is.logical(daneAdresowe), length(daneAdresowe) == 1
  )
  stopifnot(idOke %in% c(TRUE, FALSE),
            daneAdresowe %in% c(TRUE, FALSE))

  if (length(typySzkol) == 1) typySzkol = rep(typySzkol, 2)  # brzydkie, ale za to 4 wiersze dalej zadziała
  szkoly = pobierz_szkoly(polacz())
  szkoly = filter_(szkoly, ~ rok %in% lata)
  szkoly = select_(szkoly, ~ -wojewodztwo, ~ -powiat, ~ -gmina)
  if (!is.null(typySzkol)) szkoly = filter_(szkoly, ~ typ_szkoly %in% typySzkol)
  if (!idOke) szkoly = select_(szkoly, ~ -id_szkoly_oke)
  if (!daneAdresowe) szkoly = select_(szkoly, ~ -nazwa_szkoly, ~ -adres, ~ -miejscowosc,
                                      ~ -pna, ~ -poczta, ~ -wielkosc_miejscowosci,
                                      ~ -teryt_szkoly, ~ -rodzaj_gminy)
  szkoly = collect(szkoly)
  szkoly = group_by_(szkoly, ~ id_szkoly)
  szkoly = mutate_(szkoly, .dots=list(max_rok = "max(rok)"))
  szkoly = filter_(szkoly, ~ rok == max_rok)
  szkoly = select_(szkoly, ~ -max_rok)
  szkoly = as.data.frame(szkoly)

  typyWWynikach = typySzkol %in% szkoly$typ_szkoly
  if (any(!typyWWynikach)) warning("Nie znaleziono żadnych szkół typu/ów: ",
                                   paste0(typySzkol[!typyWWynikach], collapse=", "), ".")

  for (i in names(szkoly)[unlist(lapply(szkoly, is.character))]) {
    Encoding(szkoly[, i]) = "UTF-8"
  }
  attributes(szkoly)$lata = lata
  return(szkoly)
}
library = function (...)
    suppressMessages(base::library(..., warn.conflicts = FALSE, quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.table(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

pander.table = function (x, ...)
    pander(`rownames<-`(rbind(x), NULL), ...)

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

melt = function (...) {
    args = list(...)
    result = reshape2::melt(...)
    varnames = if ('varnames' %in% names(args))
        args$varnames
    else if ('variable.name' %in% names(args))
        args$variable.name
    else
        'variable'

    result[, varnames] = sapply(result[, varnames], as.character)
    result
}
assign('melt', melt, globalenv())

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
#!/usr/bin/Rscript

library(fields)
library(GGally)
library(ggplot2)
library(igraph)
library(mapproj)
library(maps)
library(pander)
library(plyr)
library(RColorBrewer)
library(reshape2)
library(scales)
library(vegan)
source('custom-plot-functions.r')

Sys.setlocale("LC_TIME", "C") #Needed for identical()
Sys.setlocale("LC_COLLATE", "C")

## Get case data

dataDir <- '.'

tmpf <- function(){
  fn <- file.path(dataDir, 'PEDvweeklyreport-state-ts-01-08-14.csv')
  ret <- read.csv(fn)
  ret[1:9, c('CA', 'MD', 'NE', 'WY')] <- 0
  key <- order(colnames(ret)[-c(1:2)])
  ret <- cbind(ret[, c(1:2)], ret[, -c(1:2)][, key])
  ret$Unk <- NULL
  target <- structure(list(week = structure(c(20L, 29L, 32L, 8L, 12L),
.Label = c("10/13/2013", "10/20/2013", "10/27/2013", "10/6/2013",
"11/10/2013", "11/17/2013", "11/24/2013", "11/3/2013", "12/1/2013",
"12/15/2013", "12/22/2013", "12/29/2013", "12/8/2013", "4/15/2013",
"4/22/2013", "4/29/2013", "5/13/2013", "5/20/2013", "5/27/2013",
"5/6/2013", "6/10/2013", "6/16/2013", "6/23/2013", "6/3/2013",
"6/30/2013", "7/14/2013", "7/21/2013", "7/28/2013", "7/7/2013",
"8/11/2013", "8/18/2013", "8/25/2013", "8/4/2013", "9/1/2013",
"9/15/2013", "9/22/2013", "9/29/2013", "9/8/2013"), class = "factor"),
totalNumberSwineAccessions = c(17L, 34L, 26L, 90L, 134L), CA = c(0, 0,
0, 0, 1), CO = c(1L, 1L, 0L, 0L, 0L), IA = c(8L, 6L, 2L, 38L, 54L), IL
= c(0L, 1L, 0L, 1L, 14L), IN = c(3L, 2L, 1L, 1L, 3L), KS = c(0L, 4L,
3L, 6L, 4L), KY = c(0L, 0L, 0L, 0L, 0L), MD = c(0, 0, 0, 0, 0), MI =
c(0L, 0L, 0L, 2L, 0L), MN = c(1L, 2L, 2L, 7L, 20L), MO = c(0L, 0L, 0L,
2L, 4L), NC = c(0L, 3L, 4L, 14L, 18L), NE = c(0, 0, 0, 0, 2), NY =
c(0L, 0L, 0L, 0L, 0L), OH = c(0L, 2L, 1L, 5L, 5L), OK = c(0L, 11L,
10L, 10L, 2L), PA = c(1L, 0L, 3L, 1L, 0L), SD = c(0L, 0L, 0L, 0L, 3L),
TN = c(0L, 0L, 0L, 1L, 1L), TX = c(0L, 0L, 0L, 1L, 1L), WI = c(0L, 0L,
0L, 1L, 0L ), WY = c(0, 0, 0, 0, 1)), .Names = c("week",
"totalNumberSwineAccessions", "CA", "CO", "IA", "IL", "IN", "KS",
"KY", "MD", "MI", "MN", "MO", "NC", "NE", "NY", "OH", "OK", "PA",
"SD", "TN", "TX", "WI", "WY" ), row.names = c(4L, 13L, 20L, 30L, 38L),
class = "data.frame")
  stopifnot(identical(target, ret[c(4,13,20,30,38),]))
  ret
}
caseData <- tmpf()

unwanted <- c('week', 'totalNumberSwineAccessions', 'Unk')
ind <- which(!colnames(caseData) %in% unwanted)
observed <- caseData[, ind]

## Get cross correlations

n <- ncol(observed)
CC <- matrix(nrow=n, ncol=n)

getcc <- function(x,y, lag=1){
    foo <- ccf(x, y, plot=FALSE)
    ind <- which(foo$lag == lag)
    foo$acf[ind]
}

for(i in seq_len(n)){
    for(j in seq_len(n)){
        ## CC[i,j] will be high if deviations from the mean in series i
        ## are shifted to the left of similar deviations to the mean in series j
        ## i.e. i's deviations are indicative of j's future deviations
        CC[i,j] <- getcc(observed[,j], observed[,i])
    }
}

colnames(CC) <- rownames(CC) <- colnames(observed)

check_cc_directionality <- function(){
    t <- 1:100 * .25
    x <- sin(t)
    ## y is shifted to the right
    y <- sin(t-1)

    xylag1 <- getcc(x, y)
    yxlag1 <- getcc(y,x)
    main <- paste('getcc(x, y) ==', round(xylag1,2),
                  '; getcc(y,x) == ', round(yxlag1,2))
    if(xylag1 > yxlag1){
        conc <- 'left arg delayed by lag'
    } else{
        conc <- 'right arg delayed by lag'
    }
    plot(x~t, type='l', ylab='f(t)', main=main, sub=conc)
    lines(y~t, col=2)
    legend('topright', col=1:2, legend=c('x', 'y'), lty=1)
}

png('direction-check.png')
check_cc_directionality()
dev.off()

## Get shared-border neighborhoods

nbEdgelist <- read.csv(file.path(dataDir, 'state_neighbors_fips.txt'), header=FALSE)
data(state.fips)
g <- graph.data.frame(nbEdgelist, directed=FALSE)
g <- simplify(g)
key <- match(V(g)$name, state.fips$fips)
abb <- state.fips$abb[key]
V(g)$name <- as.character(abb)
vids <- which(V(g)$name %in% colnames(caseData))
g2 <- induced.subgraph(g, vids)
nms <- colnames(observed)
nhood <- as.matrix(g2[nms,nms])

## Get shipment flows

epO <- ep <- read.csv(file.path(dataDir, 'shipment-flows-origins-on-rows-dests-on-columns.csv'),row.names=1)
key <- match(colnames(observed), colnames(ep))
ep <- ep[key, key]
rownames(ep) <- colnames(ep)

### assertions based on inspection of original .xls file
stopifnot(ep['CA', 'IL'] == 9415)
stopifnot(ep['MI', 'KS'] == 6)
stopifnot(ep['IL', 'IA'] == 1424813)
stopifnot(ep['KY', 'IA'] == 17658)
stopifnot(ep['MO', 'IA'] == 2389932)
stopifnot(ep['OK', 'CA'] == 16762)
stopifnot(ep['MO', 'CA'] == 645)

epl <- log10(ep +1)
epl <- data.matrix(epl)
## We discard the within-state flows because they do not enter into
## the analysis. Thus it is mostly a matter of how the plots will
## look, and because the original spreadsheet had no data on
## within-state flows (they were added for some other analyses based
## on an assumption of 90% of total flow), there's no good reason to
## include them in the plot.
diag(epl) <- NA

key <- match(colnames(ep), colnames(CC))
CC <- CC[key,key]



## Get great circle distance

key <- match(colnames(CC), state.abb)

cx <- state.center$x[key]
cy <- state.center$y[key]

n <- ncol(CC)
centerDists <- matrix(nrow=n, ncol=n)

# Calculates the geodesic distance between two points specified by radian latitude/longitude using the
# Haversine formula (hf)
# source: http://www.r-bloggers.com/great-circle-distance-calculations-in-r/
gcd.hf <- function(long1, lat1, long2, lat2) {
      R <- 6371 # Earth mean radius [km]
        delta.long <- (long2 - long1)
        delta.lat <- (lat2 - lat1)
        a <- sin(delta.lat/2)^2 + cos(lat1) * cos(lat2) * sin(delta.long/2)^2
        c <- 2 * asin(min(1,sqrt(a)))
        d = R * c
        return(d) # Distance in km
  }

deg2rad <- function(deg) return(deg*pi/180)

getCenterDist <- function(state1,state2){
    long1 <- deg2rad(cx[state1])
    long2 <- deg2rad(cx[state2])
    lat1 <- deg2rad(cy[state1])
    lat2 <- deg2rad(cy[state2])
    gcd.hf(long1, lat1, long2, lat2)
}

for(i in seq_len(n)){
    for(j in seq_len(n)){
        centerDists[i,j] <- getCenterDist(i, j)
    }
}

colnames(centerDists) <- rownames(centerDists) <- colnames(CC)

## hypothesis tesing

getMat <- function(x) switch(x, 'shipment'=epl, 'cor'=CC,
                             'gcd'=-centerDists, 'sharedBord'=nhood)

doTest <- function(M1, M2, symmetrize=FALSE, ...){
    x <- getMat(M1)
    y <- getMat(M2)
    if(symmetrize){
        x <- (x + t(x))*0.5
        y <- (y + t(y))*0.5
    }
    mantel(x, y, ...)
}

mats <- c('shipment', 'cor', 'gcd', 'sharedBord')
methods <- c('spearman', 'pearson')
symmetrize <- c(TRUE, FALSE)
des <- expand.grid(M1=mats, M2=mats, method=methods, symmetrize=symmetrize, stringsAsFactors=FALSE)
des <- des[des$M1 != des$M2, ]
des$permutations <- 10000

res <- list()
for(i in seq_len(nrow(des))){
    print(i)
    res[[i]] <- do.call(doTest, as.list(des[i,]))
}

des$r <- sapply(res, '[[', 'statistic')
des$pValues <- sapply(res, '[[', 'signif')

sink('mantel-table.txt')
pander(des)
sink()

doPartialTest <- function(M1, M2, M3, symmetrize=FALSE, ...){
    x <- getMat(M1)
    y <- getMat(M2)
    z <- getMat(M3)
    if(symmetrize){
        x <- (x + t(x))*0.5
        y <- (y + t(y))*0.5
    }
    mantel.partial(x, y, z, ...)
}

desp <- data.frame(M1='shipment', M2='cor', M3='gcd', symmetrize=c(TRUE, FALSE),
                   permutations=1000, stringsAsFactors=FALSE)

resp <- list()
for(i in seq_len(nrow(desp))){
    print(i)
    resp[[i]] <- do.call(doPartialTest, as.list(desp[i,]))
}

desp$r <- sapply(resp, '[[', 'statistic')
desp$pValues <- sapply(resp, '[[', 'signif')

sink('mantel-partial-table.txt')
pander(desp)
sink()


save.image(file='mantel-testing-checkpoint1.RData')




## plotting

### jflowmap
projection <- 'azequalarea'
orientation <- c(30.82,-98.57,0)
#scale of 1 does not allow good edge-bundling with this projection
scale <- 100

adjmatrix <- data.matrix(epO[state.abb, state.abb])
diag(adjmatrix) <- 0
g <- graph.adjacency(adjmatrix, mode='directed', weighted='flow')
stopifnot(colnames(adjmatrix) == V(g)$name)
V(g)$PEDVpositive <- V(g)$name %in% colnames(CC)
key <- match(V(g)$name, state.abb)
proj <- mapproject(x=state.center$x[key], y=state.center$y[key],
                   projection=projection, orientation=orientation)
V(g)$x <- proj$x*scale
V(g)$y <- proj$y*scale
adjmatrix <- getMat('cor')
diag(adjmatrix) <- 0
g2 <- graph.adjacency(adjmatrix, mode='directed', weighted='crossCorrelation')
E(g2)$ccShifted <- E(g2)$crossCorrelation + 1
g3 <- graph.union(g, g2)
adjmatrix <- (adjmatrix + t(adjmatrix))/2
g2 <- graph.adjacency(adjmatrix, mode='undirected', weighted='symCC')
#g3 <- graph.union(g3, g2)
#V(g3)$name <- paste('US', V(g3)$name, sep='-')
g3 <- delete.vertices(g3, c('AK', 'HI'))
write.graph(g3, file='swine-flows-CC.xml', format='graphml')

scl <- 1.8
png(file='us-background.png', width=535*scl, height=283*scl)
par(mai=rep(0,4))
map('state', mar=rep(0,4), projection=projection, orientation=orientation,
    resolution=0, myborder=0, col='dark grey', lwd=3)
bbox <- par('usr')*scale
# uncomment to verify bbox
#do.call(rect, c(as.list(bbox[c(1,3,2,4)]/scale), lwd=30))
dev.off()

# bbox as read by jflowmap
paste(bbox[1], -bbox[4], bbox[2]-bbox[1], bbox[4]-bbox[3], sep=',')

## choropleths

theme_clean <- function (base_size=12) {
  theme_grey(base_size) %+replace% theme(
      axis.title = element_blank (),
      axis.text = element_blank (),
      panel.background = element_blank (),
      panel.grid = element_blank (),
      axis.ticks.length = unit (0,"cm"),
      axis.ticks.margin = unit (0,"cm"),
      panel.margin = unit (0,"lines"),
      plot.margin = unit(c(0,0,0,0),"lines"),
      complete =TRUE)
}

state_map <- map_data("state")

## use data from cumulative burden analysis to ensure consistency

get_map_data <- function(){
    load('pedv-cum.RData')
    key <- match(mg$State, state.abb)
    ret <- data.frame(label=mg$State, state=tolower(state.name[key]),
                           Cases=mg$cases, Inventory=mg$inventory2012,
                           x=mg$stateLong, y=mg$stateLat)
    ret$Cases <- ifelse(ret$Cases == 0, NA, ret$Cases)
    ret
}

map_data <- get_map_data()
## manually position some state labels
i <- which(map_data$label=='NH')
dy <- 1.4
map_data$x[i] <- -68.08
map_data$y[i] <- map_data$y[map_data$label=='VT'] - 1.3
ii <- which(map_data$label=='MA')
map_data$x[ii] <- map_data$x[i]
map_data$y[ii] <- map_data$y[i] - dy
ii <- which(map_data$label=='RI')
map_data$x[ii] <- map_data$x[i] - 0.3
map_data$y[ii] <- map_data$y[i] - 2*dy
i <- which(map_data$label=='DE')
map_data$x[i] <- map_data$x[i] + 2
map_data$y[i] <- map_data$y[i] - 1
ii <- which(map_data$label=='NJ')
map_data$x[ii] <- map_data$x[i] + 1.2
map_data$y[ii] <- map_data$y[ii] - 1.2
i <- which(map_data$label=='CT')
map_data$x[i] <- map_data$x[ii] + 0.5
map_data$y[i] <- map_data$y[i] - 1.7
i <- which(map_data$label=='MD')
map_data$x[i] <- map_data$x[ii] - 1.8
map_data$y[i] <- map_data$y[i] - 3

get_endpoints <- function(state){
    i1 <- which(map_data$label==state)
    i2 <- which(state.abb==state)
    data.frame(x=state.center$x[i2], y=state.center$y[i2],
               xend=map_data$x[i1] - 1.5, yend=map_data$y[i1] + 0.3)
}

g <- make_choropleth(fill_var='Cases')
ggsave(filename='cases-choropleth.pdf', plot=g, width=8.6/2.54, height=8.6/2.54)
g <- make_choropleth('Inventory')
ggsave(filename='inventory-choropleth.pdf', plot=g, width=8.6/2.54, height=8.6/2.54)

### ggPairs

mats2 <- mats[1:3]
getData <- function(matName, sym, rankv){
    dists <- getMat(matName)
    if(sym){
        dists <- (dists + t(dists))/2
    }
    ret <- as.vector(as.dist(dists))
    if(rankv){
        ret <- rank(ret)
    }
    return(ret)
}
tmpf <- function(x, ...){
    sapply(mats2, getData, sym=x, ...)
}
tmpff <- function(x) {
    lapply(c(undirected=TRUE, directed=FALSE), tmpf, rankv=x)
}
matData <- lapply(c(ranked=TRUE, original=FALSE), tmpff)

theme_set(theme_classic())
theme_update(panel.grid.major=element_blank(), panel.grid.minor=element_blank(),
             axis.ticks=element_blank(), panel.border=element_blank(),
             axis.line=element_blank())


pm <- makePlotMat(dfl=matData, type='directed', transform='ranked')
pdf(file='ggpairs-spearman-directed.pdf', width=8.6/2.54, height=8.6/2.54) 
print(pm)
dev.off()

pm <- makePlotMat(dfl=matData, type='undirected', transform='ranked')
pdf(file='ggpairs-spearman-undirected.pdf', width=8.6/2.54, height=8.6/2.54) 
print(pm)
dev.off()

pm <- makePlotMat(dfl=matData, type='directed', transform='original',
                  labelBreaks=TRUE, gridLabelSize=2.0)
plotMatDirectedPearson <- pm
pdf(file='ggpairs-pearson-directed.pdf', width=9.5/2.54, height=6.6/2.54) 
print(pm)
dev.off()

pm <- makePlotMat(dfl=matData, type='undirected', transform='original',
                  labelBreaks=TRUE)
pdf(file='ggpairs-pearson-undirected.pdf', width=11.4/2.54, height=1.2*8.6/2.54) 
print(pm)
dev.off()

### diagnostics

df <- data.frame(epl=unclass(as.dist(epl)), CC=unclass(as.dist(CC)))
m <- lm(CC~epl, data=df)
pdf('diagnostics.pdf')
plot(m)
dev.off()

## image plots

pdf('cors-heatmap.pdf')
orderings <- heatmap(data.matrix(epl), scale='none')
dev.off()

makeImagePlot <- function(M, orderings, ...){
    x <- data.matrix(M)[orderings$rowInd, orderings$colInd]
    x <- t(x)
    col <- brewer.pal(9, 'Blues')
    nc <- ncol(x)
    nr <- nrow(x)
    xi <- 1:nr
    yi <- 1:nc
    names(xi) <- colnames(x)
    names(yi) <- rownames(x)
    image.plot.ebo(x=xi, y=yi, z=x, horizontal=FALSE,col=col, graphics.reset=TRUE, ...)
}


pdf('matrices.pdf', width=8.7/2.54, height=12/2.54)
layout(matrix(1:2, ncol=1))
par(mar=c(4,4.5,.5,.5))
makeImagePlot(M=data.matrix(epl), orderings=orderings, xlab='Destination', ylab='Source',
              legend.args=list(text=expression(paste(Log[10], '(transport flow)')),
                  line=2.9, side=4), panelLab='A')
par(mar=c(4,4.5,1,.5))
CCnoDiag <- CC
diag(CCnoDiag) <- NA
makeImagePlot(M=data.matrix(CCnoDiag), orderings=orderings, xlab='Leading state', ylab='Lagging state', 
              legend.args=list(text='Cross correlation', line=2.9, side=4), panelLab='B')
dev.off()

### time series

mts <- melt(caseData, id='week')
keepers <- c('MN', 'KS',
             'IL', 'OK',
             'IA', 'NC')
test <- mts$variable %in% keepers
mts <- mts[test, ]
mts$variable <- factor(mts$variable, levels=keepers)
mts$x <- as.Date(as.character(mts$week), format='%m/%d/%Y')
labdf <- ddply(mts, 'variable', summarize, minx=x[1], maxy=max(value))
labdf$minx[labdf$variable == 'OK'] <- as.Date('2013-11-01')

tmpf <- function(df){
    g <- ggplot(df, aes(x=x, y=value, group=variable))
    g <- g + geom_hline(yintercept=0, size=0.5, col='grey')
    g <- g + geom_step(direction="vh")
    g <- g + facet_wrap(~variable, ncol=2, scales='free_y')
    g <- g + scale_x_date()
    g <- g + scale_y_discrete(breaks=pretty_breaks(n=2))
    g <- g + xlab('2013-2014 Date') + ylab('Cases')
    g <- g + theme_classic()
    g <- g + theme(strip.background = element_blank(),
                   strip.text.x = element_blank())
    g <- g + theme(plot.margin=unit(c(0,2,2,0),"mm"))
    g <- g + geom_text(data=labdf, hjust=0, vjust=1,
                       aes(x=minx, y=maxy, label=variable))
    g <- g + theme(axis.title.x = element_text(vjust=-0.5))
}

g <- tmpf(mts)
ggsave('ts.pdf', width=8.6/2.54, height=6/2.54)

### composite time series and scatterplot matrix

tmpf <- function(){
    grid.newpage()
    lay <- grid.layout(1,2, widths=unit(c(8.6,8.6), 'cm'),
                       heights=unit(c(6), 'cm'))
    pushViewport(viewport(layout=lay))
    pushViewport(viewport(layout.pos.col=1, layout.pos.row=1))
    myPrintGGpairs(plotMatDirectedPearson, newpage=FALSE)
    grid.text(label="A", x=unit(0, "npc") - unit(1.5, "lines"),
              y=unit(1, "npc"), just= "left")
    popViewport()
    pushViewport(viewport(layout.pos.col=2, layout.pos.row=1))
    print(g, newpage=FALSE)
    grid.text(label="B", x=unit(0, "npc"), y=unit(1, "npc"), just= "left")
    popViewport()
}

cairo_ps(filename = 'plotMatrixWithTimeSeries.eps', width = 19/2.54, height = 6.4/2.54)
tmpf()
dev.off()

cairo_pdf(filename = 'plotMatrixWithTimeSeries.pdf', width = 19/2.54, height = 6.4/2.54)
tmpf()
dev.off()




####################################################
## Reshaping data
####################################################


## Sheet input interdependence
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
    if(!isEmpty(currentLayer)){
      markType <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']]
      stat <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']]
      isolate({
        # control stat choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']] <<-
          StatChoices[sapply(StatChoices, function(n) !is.null(getAesChoices(geom=markType, stat=n)))]
        # control aesthetics choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']] <<-
          getAesChoices(markType, stat)
      })
    }

    cc <- sheetList[[currentSheet]][['dynamicProperties']][['columns']]
    rr <- sheetList[[currentSheet]][['dynamicProperties']][['rows']]
    mDat <- sheetList[[currentSheet]][['datR']]()
    fields <- sheetList[[currentSheet]][['fieldNames']]()
    measures <- sheetList[[currentSheet]][['measuresR']]()

    cc1 <- ''; rr1 <- ''; cChoices <- ''; rChoices <- ''
    outTable <- NULL; outDf <- NULL;
    cc.measures <- ''; cc.dims <- '';
    rr.measures <- ''; rr.dims <- ''
    if(!is.null(fields)){
      dims <- setdiff.c(fields, measures)
      cc1 <- intersect(cc,dims); rr1 <- intersect(rr,dims)
      #         cc.measures <- intersect(cc1,measures); rr.measures <- intersect(rr1,measures)
      #         cc.dims <- setdiff(cc1,cc.measures); rr.dims <- setdiff(rr1,rr.measures)

      #         cc1 <- c(cc.dims,cc.measures); rr1 <- c(rr.dims,rr.measures)

      all.x <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesX']][['aesField']])
      all.y <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesY']][['aesField']])

      cChoices <- setdiff.c(dims, c(all.x, all.y, rr1))
      rChoices <- setdiff.c(dims, c(all.x, all.y, cc1))
      if(!isEmpty(currentLayer)){
        isolate({
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesX']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesY']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
        })
      }


      if(!is.null(mDat)){
        outType <- (sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
        if(outType=='table'){
          #             if(combineMeasures && !is.null(facets)){
          #               outTable <- cast(mDat, facets, sum)
          #               outDf <- as.data.frame(outTable)
          #             }

        } else {

        }

        if(!is.null(outDf)){
          ## add to dataList
          isolate({
            sheetNameDat <- convertSheetNameToDatName(sheetList[[currentSheet]][['dynamicProperties']][['name']])
            if(is.null(datList[[currentSheet]])){
              datList[[currentSheet]] <<- createNewDatClassObj(outDf, name=sheetNameDat, type='sheet')
            } else {
              datList[[currentSheet]][['dynamicProperties']][['dat']] <<- outDf
              datList[[currentSheet]][['dynamicProperties']][['measures']] <<- intersect(datList[[currentSheet]][['dynamicProperties']][['measures']],
                                                                                         getDefaultMeasures(outDf))
              ## add new fields, delete outdated fields, leave common fields alone since they might have user customizations
              newFields <- getDefaultFieldsList(outDf)
              oldList <- names(datList[[currentSheet]][['dynamicProperties']][['fieldsList']])
              newList <- names(newFields)
              for(n in setdiff(newList, oldList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- newFields[[n]]
              }
              for(n in setdiff(oldList, newList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- NULL
              }
            }
          })
        }
      }

    }
    isolate({
      #       sheetList[[currentSheet]][['dynamicProperties']][['dat']] <<- mDat
      #       sheetList[[currentSheet]][['dynamicProperties']][['cMeasures']] <<- cc.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['cDims']] <<- cc.dims
      #       sheetList[[currentSheet]][['dynamicProperties']][['rMeasures']] <<- rr.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['rDims']] <<- rr.dims
      if(are.vectors.different(cc1, sheetList[[currentSheet]][['dynamicProperties']][['columns']])){
        triggerUpdateInput('sheetColumns')
      }
      if(are.vectors.different(rr1, sheetList[[currentSheet]][['dynamicProperties']][['rows']])){
        triggerUpdateInput('sheetRows')
      }
      sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- cc1
      sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- rr1
      sheetList[[currentSheet]][['dynamicProperties']][['colChoices']] <<- cChoices
      sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']] <<- rChoices
      sheetList[[currentSheet]][['dynamicProperties']][['outputTable']] <<- outTable
      sheetList[[currentSheet]][['dynamicProperties']][['outputDataframe']] <<- outDf
    })
  }
}, priority=1)




## Switching sheet
observe({
  v <- input$sheetList
  isolate({
    if(!isEmpty(v)) projProperties[['activeSheet']] <<- v
  })

})
observe({
  updateInput[['activeSheet']]
  updateSelectInput(session, 'sheetList', choices=(sheetListNames()),
                    selected=isolate(projProperties[['activeSheet']]))
})


## modify sheet name
observe({
  v <- input$sheetName
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      if(!isEmpty(v) && isEmpty(sheetListNames()[v])){
        ## the second condition makes sure v is different
        ## update doc's rmd
        oldName <- paste('`', sheetList[[currentSheet]][['dynamicProperties']][['name']], '`', sep='')
        newName <- paste('`', v, '`', sep='')
        sapply(names(docList), function(currentDoc){
          docList[[currentDoc]][['rmd']] <<- gsub(oldName, newName, docList[[currentDoc]][['rmd']], fixed=TRUE)
          NULL
        })
        triggerUpdateInput('docRmd')

        sheetList[[currentSheet]][['dynamicProperties']][['name']] <<- v
      }
    }
  })

})
observe({
  updateInput[['sheetName']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['name']])
  } else ''
  updateTextInput(session, 'sheetName', value=null2String(s))
})

## link sheet name to corresponding data name
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    s <- sheetList[[currentSheet]][['dynamicProperties']][['name']]
    isolate({
      if(!is.null(datList[[currentSheet]])){
        datList[[currentSheet]][['dynamicProperties']][['name']] <<- convertSheetNameToDatName(s)
        triggerUpdateInput('datName')
      }
    })
  }
})

## Selecting data for sheet
observe({
  v <- input$sheetDatList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['datId']] <<- v
  })

})
observe({
  updateInput[['sheetDatId']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['datId']])
  } else ''
  choices <- datListNames()
  choices <- choices[!sapply(choices, isDatBasedonSheet, sheetId=currentSheet)]
  updateSelectInput(session, 'sheetDatList', choices=null2String(choices),
                    selected=null2String(s))
})

## whether use molten data?
observe({
  v <- input$combineMeasures
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']] <<- as.logical(v)
    }
  })

})
observe({
  updateInput[['combineMeasures']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']])
  } else FALSE
  updateCheckboxInput(session, 'combineMeasures', value=null2String(s))
})

## Manipulating columns
observe({
  v <- input$columns
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- v
  })

})
observe({
  updateInput[['sheetColumns']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['columns']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['colChoices']]} else ''
  updateSelectizeInput(session, 'columns', choices=null2String(choices), selected=null2String(s))
})

## Manipulating rows
observe({
  v <- input$rows
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- v
  })

})
observe({
  updateInput[['sheetRows']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['rows']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']]} else ''
  updateSelectizeInput(session, 'rows', choices=null2String(choices), selected=null2String(s))
})

## Manipulating output type
observe({
  v <- input$outputTypeList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['outputType']] <<- v
  })

})
observe({
  updateInput[['sheetOutput']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
  } else ''
  updateSelectInput(session, 'outputTypeList', selected=null2String(s))
})

## Selecting ggplot layer for sheet
observe({
  v <- input$layerList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- v
    }
  })
})
observe({
  updateInput[['sheetPlotLayer']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
  } else ''
  choices <- if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['layerNames']]()
  updateSelectInput(session, 'layerList', choices=null2String(choices),
                    selected=null2String(s))
})

## Selecting aesthetic
observe({
  v <- input$aesList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) {
        currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['sheetLayerAes']]
  currentSheet <- projProperties[['activeSheet']]
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']])
    }
  }

  updateSelectInput(session, 'aesList', choices=null2String(choices),
                    selected=null2String(s))
})

## set aes map or set option
observe({
  v <- input$aesMapOrSet
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']] <<- v

            ## set default value
            if(v=='set' && isEmpty(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<-
                switch(currentAes,
                       'aesLabel'='My Label', 'aesFamily'='Times', 'aesFontface'='plain',
                       'aesColor'=, 'aesBorderColor'='',
                       'aesSize'=8, 'aesLineheight'=1,
                       0
                )

              triggerUpdateInput('aesValue')
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesMapOrSet']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- 'map'
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        s1 <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        if(!are.vectors.different('set', s1)) s <- 'set'
      }
    }
  }
  updateRadioButtons(session, 'aesMapOrSet', selected=s)
})

## map or set UI
output$mapOrSetUI <- renderUI({
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        useMapping <- are.vectors.different('set',
                                            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        isolate({
          aes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]]
          if(useMapping){
            s <- null2String(aes[['aesField']])
            choices <- if(currentAes %in% c('aesX','aesY')) {
              aes[['fieldChoices']]
            } else {
              sheetList[[currentSheet]][['fieldNames']]()
            }
            if(!(s %in% choices)) choices[s]=s ## this is needed when s="", otherwise selected will defaults to the first value

            aggFun <- null2String(aes[['aesAggFun']])
            aggFunchoices <- YFunChoices
            if(!(aggFun %in% aggFunchoices)) aggFunchoices[aggFun]=aggFun

            fluidRow(
              column(4,
                     selectizeInput(inputId='aesField', label='Field',
                                    choices=choices, selected=s, multiple=FALSE,
                                    options = list(create = TRUE))
              ),
              column(4,
                     checkboxInput(inputId='aesAggregate', label='Aggregate Field',
                                   value=aes[['aesAggregate']]),
                     conditionalPanel('input.aesAggregate==true',
                                      selectizeInput(inputId='aesAggFun', label='By',
                                                     choices=aggFunchoices,
                                                     selected=aggFun, multiple=FALSE,
                                                     options = list(create = TRUE))
                     )

              ),
              column(4,
                     conditionalPanel('output.canAesFieldBeContinuous==true',
                                      radioButtons('aesDiscrete', 'Treat Field as',
                                                   choices=c('Continuous'='continuous',
                                                             'Discrete'='discrete'),
                                                   selected=ifelse(aes[['aesDiscrete']], 'discrete', 'continuous'),
                                                   inline=FALSE)
                     )


              )
            )
          } else {
            switch(currentAes,
                   'aesLabel'=textInput('aesValue', '', value=aes[['aesValue']]),
                   'aesFontface'=selectInput('aesValue','',choices=FontFaceChoices, selected=aes[['aesValue']]),
                   'aesFamily'=selectInput('aesValue','',choices=FontFamilyChoices, selected=aes[['aesValue']]),
                   'aesColor'=, 'aesBorderColor'=colorInput('aesValue', '', value=aes[['aesValue']]),
                   'aesShape'=, 'aesLineType'=numericInput('aesValue', 'Value', value=aes[['aesValue']], step=1),
                   numericInput('aesValue', 'Value', value=aes[['aesValue']], step=0.1)
            )
          }
        })
      }
    }
  }
})

## set aesValue
observeEvent(input$aesValue,
             {
  v <- input$aesValue
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<- v
      }
    }
  }
})


## set aes field
observe({
  v <- input$aesField
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']] <<- v

              ## set default field properties
              if(isEmpty(v) && currentLayer != 'Plot'){
                v <- null2String(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']][['aesList']][[currentAes]][['aesField']])
              }
              is.measure <- v %in% sheetList[[currentSheet]][['measuresR']]()
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']] <<-
                is.measure  ## just for capturing this information to customize choices for agg fun
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- is.measure
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- if(is.measure) 'sum' else 'length'
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- !is.measure
              sapply(c('aesAggregate','aesAggFun','aesDiscrete'), triggerUpdateInput)

              ## set default xlab, ylab
              if(!isEmpty(v)){
                fieldNames <- sheetList[[currentSheet]][['fieldNames']]()
                i.match <- match(v, fieldNames)
                if(!is.na(i.match)){
                  fieldName <- names(fieldNames)[i.match]
                  switch(currentAes,
                         'aesX'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']] <<- fieldName
                           triggerUpdateInput('plotXlab')
                         },
                         'aesY'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']] <<- fieldName
                           triggerUpdateInput('plotYlab')
                         }
                         )

                }
              }

            }
          }
        }
      }
    })
  }

})


output$canAesFieldBeContinuous <- reactive({
  ans <- FALSE
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        ans <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['canFieldBeContinuous']]()
      }
    }
  }
  ans
})
outputOptions(output, "canAesFieldBeContinuous", suspendWhenHidden=FALSE)

## set aes aggregate
observe({
  v <- input$aesAggregate
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- v
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesAggregate']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- FALSE
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']])

        }
      }
    }
    updateCheckboxInput(session, 'aesAggregate', value=s)
  })

})


## set aes agg fun
observe({
  v <- input$aesAggFun
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['aesAggFun']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- ''
    choices <- YFunChoices
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']]
          is.measure <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']]
          if(!is.null(is.measure) && !is.measure) choices <- AggFunChoicesDimension
        }
      }
    }

    if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
    updateSelectizeInput(session, 'aesAggFun', choices=null2String(choices), selected=null2String(s))
  })
})

## set aes discrete
observe({
  v <- input$aesDiscrete
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            isDiscrete <- (v=='discrete')
            if(currentAes %in% c('aesX', 'aesY')){
              ## can't mix discrete with continuous scales on x or y, so need to keep all layers the same
              for(layer in names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])){
                sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
              }
            } else {
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesDiscrete']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- 'discrete'
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          d <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']])
          if(!isEmpty(d) && !d){
            s <- 'continuous'
          }

        }
      }
    }
    updateRadioButtons(session, 'aesDiscrete', selected=s)
  })
})

## set Mark Type / geom
observe({
  v <- input$markList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']] <<- v
          # set default stat type & position
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<-
            switch(v, 'boxplot'='boxplot', 'identity')
          triggerUpdateInput('layerStatType')
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<-
            switch(v, 'bar'='dodge', 'identity')
          triggerUpdateInput('layerPositionType')
        }
      }
    }
  })
})
observe({
  updateInput[['layerGeom']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']])
      #choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geomChoices']])
    }
  }
  updateSelectInput(session, 'markList', selected=null2String(s))
})

## set Stat Type
observe({
  v <- input$statTypeList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){

          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerStatType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']])
    }
  }

  updateSelectInput(session, 'statTypeList', choices=null2String(choices), selected=null2String(s))
})

## set y fun
observe({
  v <- input$yFunList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerYFun']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']])
    }
  }
  choices <- YFunChoices
  if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
  updateSelectizeInput(session, 'yFunList', choices=null2String(choices), selected=null2String(s))
})



## set PositionType
observe({
  v <- input$layerPositionType
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']])
    }
  }
  updateSelectizeInput(session, 'layerPositionType', selected=null2String(s))
})

## set Position Height
observe({
  v <- empty2NULL(as.numeric(input$layerPositionHeight))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionHeight']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']])
    }
  }
  updateTextInput(session, 'layerPositionHeight', value=null2String(s))
})

## set Position Width
observe({
  v <- empty2NULL(as.numeric(input$layerPositionWidth))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionWidth']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']])
    }
  }
  updateTextInput(session, 'layerPositionWidth', value=null2String(s))
})




tabS <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
                   (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )
canLatexPNG <- tryCatch(length(make.png(tabS)), error=function(e) FALSE)


output$sheetOutput <- renderUI({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    switch(sheetList[[currentSheet]][['dynamicProperties']][['outputType']],
           'table'=if(canLatexPNG) imageOutput('sheetOutputTable') else {
             tags$div(
               HTML(paste(capture.output(Hmisc::html(sheetList[[currentSheet]][['tableR']]())), collapse=" "))
             )
           },
           'plot'=plotOutput('ggplot'))
  }

})


output$sheetOutputTable <- renderImage(if(canLatexPNG) {
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    tab <- sheetList[[currentSheet]][['tableR']]()

    if(!is.null(tab)){
      #width  <- session$clientData$output_test_width
      #height <- session$clientData$output_test_height

      # For high-res displays, this will be greater than 1
      pixelratio <- session$clientData$pixelratio
      fileName <- make.png(tab, resolution=72*pixelratio)
      pngFile <- readPNG(fileName)

      # Return a list containing the filename
      list(src = normalizePath(fileName),
           width = dim(pngFile)[2],
           height = dim(pngFile)[1],
           alt = "Output not available")
    }
  }
}, deleteFile = TRUE)

# x <- tabular( (Species + 1) ~ (n=1) + Format(digits=3)*
#                 (Sepal.Length + Sepal.Width)*(mean + Justify(r)*sd), data=iris )
# tags$div(
#   HTML(paste(capture.output(Hmisc::html(x)), collapse=" "))
# )

## Reshaped output
output$reshapedDat <- renderTable({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['outputTable']]}
})

output$ggplot <- renderPlot({
  if(input$autoRefresh=='refresh'){
    currentSheet <- projProperties[['activeSheet']]
    if(!isEmpty(currentSheet)){
      sheetList[[currentSheet]][['plotR']]()
    }
  } else {
    gg <- last_plot()
    if(!is.null(gg)) gg <- gg  + theme_grey()
    gg
  }

})



## add Layer
observe({
  v <- input$addLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        existingNames <- names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])
        layerName <- make.unique(c(existingNames, 'Overlay'), sep='_')[length(existingNames)+1]

        newLayer <- createNewLayer()
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]] <<- newLayer
        sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- layerName

        #copy from Plot layer
        plotLayer <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']]
        names1 <- names(plotLayer)
        for(n1 in names1){
          if(n1=='aesList'){
            names2 <- names(plotLayer[[n1]])
            for(n2 in names2){
              names3 <- names(plotLayer[[n1]][[n2]])
              for(n3 in names3){
                if(n3 != 'aesField' && typeof(plotLayer[[n1]][[n2]][[n3]]) != 'closure'){#
                  sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]][[n2]][[n3]] <<- plotLayer[[n1]][[n2]][[n3]]
                }
              }
              setAesReactives(currentSheet, layerName, n2)
            }
          } else {
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]] <<- plotLayer[[n1]]
          }
        }

      }
    }
  })
})
## delete Layer
observe({
  v <- input$deleteLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer) && currentLayer!='Plot'){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- 'Plot'
        }
      }
    }
  })
})
## bring Layer to top
observe({
  v <- input$bringToTop
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          temp <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]]
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- temp
        }
      }
    }
  })
})

## add sheet
observe({
  v <- input$addSheet
  isolate({
    if(v){
      addSheet()
    }
  })
})
## delete sheet
observe({
  v <- input$deleteSheet
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        sheets <- names(sheetList)
        i <- match(currentSheet, sheets)
        sheetList[[currentSheet]] <<- NULL
        projProperties[['activeSheet']] <<- ifelse(length(sheets)>i, sheets[i+1],
                                                   ifelse(i>1, sheets[i-1], ''))
      }
    }
  })
})

#!/usr/bin/Rscript

source("plot.r")

doConfidence <- function() {
    numPoints <- 10

    x <- rnorm(numPoints)
    y <- rnorm(numPoints)

    plotWithConfidence(x, y, abs(y/10.0), pdfFile="conf.pdf")
}

doBoxPlot <- function() {
    numPoints <- 10000

    x <- rnorm(numPoints)
    y <- rnorm(numPoints)

    plotBoxes(x, y, pdfFile="box.pdf")
}

doConfidenceContinous <- function() {
    x1 <- seq(0,10,0.01)
    x <- x1
    for (i in 1:31) {
        x <- c(x,x1)
    }

    numPoints <- length(x)

    y <- x*x + rnorm(numPoints)

    outMean <- tapply(y, x, mean)
    outSD <- tapply(y, x, sd)
    out <- data.frame(x = names(outMean), mean = outMean, sd = outSD, row.names = NULL)

    confLevel <- 0.99
    numReplications <- 32

    plotWithConfidenceContinous(x1, out$mean, 10.0 * qnorm(1.0 - (1.0 - confLevel)/2.0) * out$sd/sqrt(numReplications), pdfFile = "confContinous.pdf")
}

doBoxPlot()
doConfidence()
doConfidenceContinous()
source("colors.r")

#
# OUTLINE
#

# every plot function in this file makes IMHO nice formatted plots in four steps

# 1. Plot an empty plot, to inform R about ranges of data (grid needs this)
# 2. Plot background and grid
# 3. Plot data
# 4. Plot axes, box and titles

################################################################################

# Helper function for leaving out unused margins
doMargins <- function(mainTitle, xTitle, yTitle) {
  margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)
}

################################################################################

# Helper function for plotting axes and title on top of plot
doBoxTitleAndAxes <- function(mainTitle, xTitle, yTitle, xLabels=NULL, yLabels=NULL) {
  box(col = thillux_grey[1], bty="l")
  title(main=mainTitle, col=thillux_grey[1], xlab=xTitle, ylab=yTitle)
  axis(1, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1], labels=xLabels)
  axis(2, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
}

################################################################################

# Helper function for creating PDF devices
doOpenPDF <- function(pdfFile, pdfTitle) {
  pdfFilePath = "out.pdf"
  if(!is.null(pdfFile)) {
    pdfFilePath = pdfFile
  }
  pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)
}

################################################################################

# Helper function for plotting background and grid, before plotting on top of it
doPlotBackgroundAndGrid <- function() {
  u <- par("usr")
  rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)
  par(col.lab=thillux_grey[1])
  grid(col=thillux_grey[1], lty=3, lwd=0.5)
}

################################################################################

plotHistogram <- function(dataArray,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot",
    breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      border=colorScheme[1,1],
      breaks=breaks,
      cex=1,
      col=colorScheme[1,2],
      lty=1,
      main='',
      xlab='',
      ylab=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotHistogramNormal <- function(dataArray,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot",
    breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    h$counts <- h$counts/sum(h$counts)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      freq=FALSE,
      lty=1,
      cex=1)

    x <- seq(min(-10.0, min(dataArray) * 0.5) , max(max(dataArray) * 1.5, 100), length=10000)
    y <- dnorm(x, mean=mean(dataArray), sd=sd(dataArray))

    par(new=TRUE)

    plot(x,y,
         axes=FALSE,
         col=colorScheme[2,2],
         lwd=3,
         main='',
         type="l",
         xlab='',
         xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
         ylab=''
    )

    polygon(x, y,
            col=colorScheme[2,2],
            border=colorScheme[2][1],
            ylab='',
            xlab='',
            main=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQNormal <- function(dataArray,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqnorm(dataArray, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    qqline(sort(dataArray), ylab='',
      xlab='', col=colorScheme[2,2], lwd=2)

    par(new=TRUE)

    qq <- qqnorm(sort(dataArray), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      axes=FALSE,
      bg=colorScheme[1,1],
      cex=1,
      col=colorScheme[1,2],
      lty=1,
      lwd=1,
      main=NULL,
      pch=21,
      type="b",
      xlab='',
      ylab=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQ <- function(dataArray1, dataArray2,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqplot(dataArray1, dataArray2, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    qq <- qqplot(sort(dataArray1), sort(dataArray2), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      axes=FALSE,
      bg=colorScheme[1,1],
      cex=1,
      col=colorScheme[1,2],
      lty=1,
      lwd=1,
      main=NULL,
      pch=21,
      type="b",
      xlab='',
      ylab=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotPoints <- function(dataArray1, dataArray2,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(dataArray1, dataArray2,
      axes=FALSE,
      bg=colorScheme[1,1],
      cex=1,
      col=colorScheme[1,2],
      lty=1,
      lwd=1,
      main=NULL,
      pch=21,
      type="p",
      xlab='',
      ylab=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotSmoothLine <- function(dataArray1, dataArray2,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(smooth.spline(dataArray1, dataArray2),
      axes=FALSE,
      bg=colorScheme[1,1],
      cex=1,
      col=colorScheme[1,2],
      lty=1,
      lwd=1,
      main=NULL,
      pch=21,
      type="l",
      xlab='',
      ylab=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidence <- function(xData, yData, e,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot",
    connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    deltaX <- abs(diff(range(xData))) / 15.0
    deltaY <- abs(diff(range(c(yData+e,yData-e)))) / 15.0
    xLim <- range(xData) + c(-deltaX, deltaX)
    yLim <- range(c(yData+e,yData-e)) + c(-deltaY, deltaY)

    plot(xData, yData,
      ann=FALSE,
      axes=FALSE,
      bty="n",
      main='',
      type="n",
      xlab='',
      xlim=xLim,
      ylab='',
      ylim=yLim
    )

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    arrowLength <- abs(diff(range(xData)))/25.0
    arrowTipLength <- abs(diff(range(yData)))/50.0

    rect(xData - arrowLength, yData - e, xData + arrowLength, yData + e, col=colorScheme[1,2], border=FALSE)

    segments(xData - arrowLength, yData - e, xData + arrowLength, yData - e, lend=1, col=colorScheme[1,1])
    segments(xData - arrowLength, yData + e, xData + arrowLength, yData + e, lend=1, col=colorScheme[1,1])

    segments(xData - arrowLength/2.0, yData, xData+arrowLength/2.0, yData, col=colorScheme[1,1], lwd = 1.0)

    if (connectionLines) {
      frame <- data.frame(xData,yData)
      frame <- frame[order(xData),]
      lines(frame$xData, frame$yData, col=colorScheme[1,2],lty=2)
    }

    # draw circle outlines
    rVert <- pmin(e/2.0, arrowTipLength)
    rHor <- arrowLength/5.0

    for (i in 1 : length(xData)) {
      mid1X <- xData[i] - arrowLength
      mid1Y <- yData[i] + e[i] - rVert[i]

      mid2X <- xData[i] - arrowLength
      mid2Y <- yData[i] - e[i] + rVert[i]

      mid3X <- xData[i] + arrowLength
      mid3Y <- yData[i] + e[i] - rVert[i]

      mid4X <- xData[i] + arrowLength
      mid4Y <- yData[i] - e[i] + rVert[i]

      deg <- 90 : 180
      xCircle1 <- mid1X + rHor * cos(deg/180.0 * pi)
      yCircle1 <- mid1Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle1, yCircle1, col=colorScheme[1,1])

      deg <- 180 : 270
      xCircle2 <- mid2X + rHor * cos(deg/180.0 * pi)
      yCircle2 <- mid2Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle2, yCircle2, col=colorScheme[1,1])

      polygon(c(xCircle1, xCircle2), c(yCircle1, yCircle2), col = colorScheme[1,2], border = FALSE)

      deg <- 0 : 90
      xCircle3 <- mid3X + rHor * cos(deg/180.0 * pi)
      yCircle3 <- mid3Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle3, yCircle3, col=colorScheme[1,1])

      deg <- 270 : 360
      xCircle4 <- mid4X + rHor * cos(deg/180.0 * pi)
      yCircle4 <- mid4Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle4, yCircle4, col=colorScheme[1,1])

      polygon(c(xCircle3, xCircle4), c(yCircle3, yCircle4), col = colorScheme[1,2], border = FALSE)
    }

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidenceContinous <- function(xData, yData, e,
    mainTitle=NULL,
    xTitle=NULL,
    yTitle=NULL,
    pdfFile=NULL,
    pdfTitle="thillux plot",
    connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    deltaX <- abs(diff(range(xData))) / 15.0
    deltaY <- abs(diff(range(c(yData+e,yData-e)))) / 15.0
    xLim <- range(xData) + c(-deltaX, deltaX)
    yLim <- range(c(yData+e,yData-e)) + c(-deltaY, deltaY)

    plot(xData, yData,
      ann=FALSE,
      axes=FALSE,
      bty="n",
      main='',
      type="n",
      xlab='',
      xlim=xLim,
      ylab='',
      ylim=yLim
    )

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    polygon(c(sort(xData),rev(sort(xData))),c(yData + e, rev(yData-e)), col=colorScheme[1,2], border=FALSE)

    lines(xData, yData + e, col=colorScheme[1,1])
    lines(xData, yData - e, col=colorScheme[1,1])

    lines(xData,yData,col=colorScheme[2,1])

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotBox <- function(xData, yData,
                    mainTitle=NULL,
                    xTitle=NULL,
                    yTitle=NULL,
                    pdfFile=NULL,
                    pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(xData, yData,
      ann=FALSE,
      axes=FALSE,
      bty="n",
      main='',
      type="n",
      xlab='',
      ylab=''
    )

    doPlotBackgroundAndGrid()

    boxplot(yData ~ xData,
      add=T,
      at=xData[1],
      axes=F,
      border=colorScheme[1,1],
      col=colorScheme[1,2],
      xlim=range(xData),
      ylim=range(yData)
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotBoxes <- function(xData, yData, mainTitle=NULL,
                      xTitle=NULL,
                      yTitle=NULL,
                      pdfFile=NULL,
                      pdfTitle="thillux plot",
                      breaks=10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    stopifnot(breaks > 1)

    seqTwice <- seq(from=min(xData), to=max(xData), length=2 * breaks + 1)
    cutLabels <- seqTwice[seq(from=2, to=2 * breaks + 1, by=2)]
    cuttedData <- as.numeric(cut(xData, breaks=breaks, labels=cutLabels))
    cutLabels <- cutLabels[sort(unique(cuttedData))]

    plot(cuttedData, yData,
      ann=FALSE,
      axes=FALSE,
      bty="n",
      main='',
      type="n",
      xlab='',
      xlim=range(xData),
      ylab='',
      ylim=range(yData)
    )

    doPlotBackgroundAndGrid()

    boxplot(yData ~ cuttedData,
      add=T,
      at=cutLabels,
      axes=F,
      border=colorScheme[1,1],
      boxwex=abs(diff(range(xData))) / (breaks^1.2),
      col=colorScheme[1,2],
      names=sprintf("%2.2f", cutLabels),
      xlim=range(xData),
      ylim=range(yData)
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotDensity <- function(xData, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    d <- density(xData)

    plot(d, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(d$x, d$y, type="l", col=colorScheme[1,1], xlab="", ylab="", main="")

    polygon(d$x, d$y, col=colorScheme[1,2], border=FALSE)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
each-mode: batch-mode: no

if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	each-mode:  find args "--each"
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either each-mode [
    	do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ][
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
#' Import a module into the current scope
#'
#' \code{module = import('module')} imports a specified module and makes its
#' code available via the environment-like object it returns.
#'
#' @param module a character string specifying the full module path
#' @param attach either a boolean or a  character vector. If \code{TRUE}, attach
#'  the newly loaded module to the object search path (see \code{Details}).
#'  Alternatively, if a character vector is given, attach only the listed names.
#' @param attach_operators if \code{TRUE}, attach operators of module to the
#'  object search path, even if \code{attach} is \code{FALSE}
#' @param doc boolean specifying whether to load the module’s documentation (see
#'  \code{Details})
#' @return the loaded module environment (invisible)
#'
#' @details Modules are loaded in an isolated environment which is returned, and
#' optionally attached to the object search path of the current scope (if
#' argument \code{attach} is \code{TRUE}).
#' \code{attach} defaults to \code{FALSE}. However, in interactive code it is
#' often helpful to attach packages by default. Therefore, in interactive code
#' invoked directly from the terminal only (i.e. not within modules),
#' \code{attach} defaults to the value of \code{options('import.attach')}, which
#' can be set to \code{TRUE} or \code{FALSE} depending on the user’s preference.
#'
#' \code{attach_operators} causes \emph{operators} to be attached by default,
#' because operators can only be invoked in R if they re found in the search
#' path. Not attaching them therefore drastically limits a module’s usefulness.
#'
#' \code{doc} loads the module’s documentation, specified as roxygen comments.
#' It defaults to \code{TRUE} in interactive mode and to \code{FALSE} otherwise.
#'
#' Modules are searched in the module search path \code{options('import.path')}.
#' This is a vector of paths to consider, from the highest to the lowest
#' priority. The current directory is \emph{always} considered last. That is,
#' if a file \code{a.r} exists both in the current directory and in a module
#' search path, the local file \code{./a.r} will not be loaded, unless the
#' import is explicitly specified as \code{import('./a')}.
#'
#' Module names can be fully qualified to refer to nested paths. See
#' \code{Examples}.
#'
#' Module source code files are assumed to be encoded in UTF-8 without BOM.
#' Ensure that this is the case when using an extended character set.
#'
#' @note Unlike for packages, attaching happens \emph{locally}: if
#' \code{import} is executed in the global environment, the effect is the same.
#' Otherwise, the imported module is inserted as the parent of the current
#' \code{environment()}. When used (globally) \emph{inside} a module, the newly
#' imported module is only available inside the module’s search path, not
#' outside it (nor in other modules which might be loaded).
#'
#' @examples
#' \dontrun{
#' # `a.r` is a file in the local directory containing a function `f`.
#' a = import('a')
#' a$f()
#'
#' # b/c.r is a file in path `b`, containing functions `f` and `g`.
#' import('b/c', attach = 'f')
#' # No module name qualification necessary
#' f()
#' g() # Error: could not find function "g"
#'
#' import('b/c', attach = TRUE)
#' f()
#' g()
#' }
#' @seealso \code{unload}
#' @seealso \code{reload}
#' @seealso \code{module_name}
#' @seealso \code{module_help}
#' @export
import = function (module, attach, attach_operators = TRUE, doc) {
    stopifnot(inherits(module, 'character'))

    if (missing(attach)) {
        attach = if (interactive() && is.null(module_name()))
            getOption('import.attach', FALSE)
        else
            FALSE
    }

    stopifnot(class(attach) == 'logical' && length(attach) == 1 ||
              class(attach) == 'character')

    if (is.character(attach)) {
        export_list = attach
        attach = TRUE
    }
    else
        export_list = NULL

    if (missing(doc))
        doc = interactive()

    module_path = try(find_module(module), silent = TRUE)

    if (inherits(module_path, 'try-error'))
        stop(attr(module_path, 'condition')$message)

    containing_modules = module_init_files(module, module_path)
    mapply(do_import, names(containing_modules), containing_modules,
           rep(doc, length(containing_modules)))

    mod_ns = do_import(as.character(module), module_path, doc)
    module_parent = parent.frame()
    mod_env = exhibit_namespace(mod_ns, as.character(module), module_parent,
                                export_list)

    attached_module = if (attach)
        mod_env
    else if (attach_operators)
        export_operators(mod_ns, module_parent)
    else
        NULL

    if (! is.null(attached_module)) {
        # The following distinction is necessary because R segfaults if we try
        # to change `parent.env(.GlobalEnv)`. More info:
        # http://stackoverflow.com/q/22790484/1968
        if (identical(module_parent, .GlobalEnv)) {
            attach(attached_module, name = environmentName(attached_module))
            attr(mod_env, 'attached') = environmentName(attached_module)
        }
        else
            parent.env(module_parent) = attached_module
    }

    attr(mod_env, 'call') = match.call()
    lockEnvironment(mod_env, bindings = TRUE)
    invisible(mod_env)
}

do_import = function (module_name, module_path, doc) {
    if (is_module_loaded(module_path))
        return(get_loaded_module(module_path))

    # Environment with helper functions which are only available when loading a
    # module via `import`, and are not otherwise exported by the package.
    helper_env = list2env(list(export_submodule = export_submodule),
                          parent = .BaseNamespaceEnv)

    # The namespace contains a module’s content. This schema is very much like
    # R package organisation.
    # A good resource for this is:
    # <http://obeautifulcode.com/R/How-R-Searches-And-Finds-Stuff/>
    namespace = structure(new.env(parent = helper_env),
                          name = paste('namespace', module_name, sep = ':'),
                          path = module_path,
                          class = c('namespace', 'environment'))

    # First cache the (still empty) namespace, then source code into it. This is
    # necessary to allow circular imports.
    cache_module(namespace)

    # R, Windows and Unicode don’t play together. `source` does not work here.
    # See http://developer.r-project.org/Encodings_and_R.html and
    # http://stackoverflow.com/q/5031630/1968 for a discussion of this.
    eval(parse(module_path, encoding = 'UTF-8'), envir = namespace)

    make_S3_methods_known(namespace)

    if (doc)
        attr(namespace, 'doc') = parse_documentation(namespace)
    namespace
}

exhibit_namespace = function (namespace, name, parent, export_list) {
    if (is.null(export_list))
        export_list = ls(namespace)
    else {
        # Verify correctness.
        exist = vapply(export_list, exists, logical(1), envir = namespace)
        if (! all(exist))
            stop(sprintf('Non-existent function(s) (%s) specified for import',
                         paste(export_list[! exist], collapse = ', ')))
    }

    # Skip one parent environment because this module is hooked into the chain
    # between the calling environment and its ancestor, thus sitting in its
    # local object search path.
    structure(list2env(sapply(export_list, get, envir = namespace,
                              simplify = FALSE),
                       parent = parent.env(parent)),
              name = paste('module', name, sep = ':'),
              path = module_path(namespace),
              doc = attr(namespace, 'doc'),
              class = c('module', 'environment'))
}

export_operators = function (namespace, parent) {
    ops = c('+', '-', '*', '/', '^', '**', '&', '|', ':', '::', ':::', '$',
            '$<-', '=', '<-', '<<-', '==', '<', '<=', '>', '>=', '!=', '~',
            '&&', '||', '!', '?', '@', '@<-', ':=')

    is_predefined = function (f) f %in% ops

    is_op = function (f) {
        # `.` delimits an S3 method name, but only when not inside `%…%`.
        prefix = regmatches(f, regexpr('^[^.]+|(%[^%]*%)', f))
        is_predefined(prefix) || grepl('^%.*%$', prefix)
    }

    operators = Filter(is_op, lsf.str(namespace))

    if (length(operators) == 0)
        return()

    name = module_name(namespace)
    # Skip one parent environment because this module is hooked into the chain
    # between the calling environment and its ancestor, thus sitting in its
    # local object search path.
    structure(list2env(sapply(operators, get, envir = namespace),
                       parent = parent.env(parent)),
              name = paste('operators', name, sep = ':'),
              path = module_path(namespace),
              class = c('module', 'environment'))
}

#' Unload a given module
#'
#' Unset the module variable that is being passed as a parameter, and remove the
#' loaded module from cache.
#' @param module reference to the module which should be unloaded
#' @note Any other references to the loaded modules remain unchanged, and will
#' still work. However, subsequently importing the module again will reload its
#' source files, which would not have happened without \code{unload}.
#' Unloading modules is primarily useful for testing during development, and
#' should not be used in production code.
#'
#' \code{unload} comes with a few restrictions. It attempts to detach itself
#' if it was previously attached. This only works if it is called in the same
#' scope as the original \code{import}.
#' @seealso \code{import}
#' @seealso \code{reload}
#' @export
unload = function (module) {
    stopifnot(inherits(module, 'module'))
    module_ref = as.character(substitute(module))
    rm(list = module_path(module), envir = .loaded_modules)
    attached = attr(module, 'attached')
    if (! is.null(attached))
        detach(attached, character.only = TRUE)
    # Unset the module reference in its scope, i.e. the caller’s environment or
    # some parent thereof.
    rm(list = module_ref, envir = parent.frame(), inherits = TRUE)
}

#' Reload a given module
#'
#' Remove the loaded module from the cache, forcing a reload. The newly reloaded
#' module is assigned to the module reference in the calling scope.
#' @param module reference to the module which should be unloaded
#' @note Any other references to the loaded modules remain unchanged, and will
#' still work. Reloading modules is primarily useful for testing during
#' development, and should not be used in production code.
#'
#' \code{reload} comes with a few restrictions. It attempts to re-attach itself
#' in parts or whole if it was previously attached in parts or whole. This only
#' works if it is called in the same scope as the original \code{import}.
#' @seealso \code{import}
#' @seealso \code{unload}
#' @export
reload = function (module) {
    stopifnot(inherits(module, 'module'))
    module_ref = as.character(substitute(module))
    module_parent = parent.frame()
    # Execute in parent scope, since `unload` deletes the scope’s reference to
    # the module.
    eval(call('unload', as.name(module_ref)), envir = module_parent)
    # Use `eval` to replicate the exact call being made to `import`.
    mod_env = eval(attr(module, 'call'), envir = module_parent)
    assign(module_ref, mod_env, envir = module_parent, inherits = TRUE)
}

#' Pretty-print a module’s description
#'
#' @export
print.module = function (module) {
    cat(sprintf('<%s>\n', attr(module, 'name')))
    invisible(module)
}
import_package = function (package, attach, attach_operators = TRUE) {
    stopifnot(inherits(package, 'character'))

    if (missing(attach)) {
        attach = if (interactive() && is.null(module_name()))
            getOption('import.attach', FALSE)
        else
            FALSE
    }

    stopifnot(class(attach) == 'logical' && length(attach) == 1)

    module_parent = parent.frame()

    # TODO: Do we actually need this? Nothing is attached here, even if loading
    # the package via `library` would attach stuff.
    # We can also just opt to blatantly ignore `Depends` packages.
    # Furthermore, S4 functions don’t work, and nor do S3, I’d wager.

    # Package which use `Depends` will pollute the global `search()` path.
    # We save the old `search()` path, and restore it afterwards. Furthermore,
    # We attach the list of attached packages to our local parent environment
    # chain instead.
    old_search = search()
    on.exit({
        if (! identical(module_parent, .GlobalEnv)) {
            newly_attached = setdiff(search(), old_search)
            for (pkg in newly_attached)
                detach(pkg)

            # Insert them into the current package’s parent chain.
            # We only need to insert the first one, since it already has the
            # others as its parents.
            # NOTE: This relies on the fact that `setdiff` doesn’t change the
            # order of the elements.

            parent.env(tail(newly_attached, 1)) = parent.env(module_parent)
            parent.env(module_parent) = newly_attached[1]
        }
    })

    pkg_ns = require_namespace(package)
    if (inherits(pkg_ns, 'error'))
        stop('Unable to load packge ', sQuote(package), '\n',
             'Failed with error: ', sQuote(conditionMessage(pkg_ns)))

    # TODO: Handle attaching

    # TODO: Return entries from  `.__NAMESPACE__.$exports`
    # FIXME: Wrong environment name set (is: 'module:packagename')
    # FIXME: Can the following ever differ from its contents, i.e. is
    #   all.equal(ls(…$exports), sapply(ls(…$exports), get, envir = …$exports))?
    export_list = getNamespaceExports(pkg_ns)
    # TODO: Use `importIntoEnv`
    pkg_env = exhibit_namespace(pkg_ns, package, module_parent, export_list)

    pkg_env$.__S3MethodsTable__. = pkg_ns$.__S3MethodsTable__.

    attached_module = if (attach)
        pkg_env
    else if (attach_operators)
        export_operators(pkg_ns, module_parent)
    else
        NULL

    if (! is.null(attached_module)) {
        # The following distinction is necessary because R segfaults if we try
        # to change `parent.env(.GlobalEnv)`. More info:
        # http://stackoverflow.com/q/22790484/1968
        if (identical(module_parent, .GlobalEnv)) {
            # FIXME: Run .onAttach?
            attach(attached_module, name = environmentName(attached_module))
            attr(pkg_env, 'attached') = environmentName(attached_module)
        }
        else
            parent.env(module_parent) = attached_module
    }

    lockEnvironment(pkg_env, bindings = TRUE)
    invisible(pkg_env)
}

# Similar to `base::requireNamespace`, but returns the package namespace,
# doesn’t swallow the error message, and without NSE shenanigans.
require_namespace = function(package) {
    ns = .Internal(getRegisteredNamespace(package))
    if (is.null(ns))
        ns = tryCatch(loadNamespace(package), error = identity)

    ns
}
library = function (...)
    suppressMessages(base::library(..., warn.conflicts = FALSE, quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

melt = function (...) {
    args = list(...)
    result = reshape2::melt(...)
    varnames = if ('varnames' %in% names(args))
        args$varnames
    else if ('variable.name' %in% names(args))
        args$variable.name
    else
        'variable'

    result[, varnames] = sapply(result[, varnames], as.character)
    result
}
assign('melt', melt, globalenv())

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
library = function (...)
    suppressMessages(base::library(..., warn.conflicts = FALSE, quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
library = function (...) suppressMessages(base::library(..., quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
each-mode: no

if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	each-mode:  find args "--each"
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either each-mode [
    	do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ][
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.extract.controls <- function(basename, probes=meffil.probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=meffil.probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    ## minfi does this. shouldn't it be green, not red??????
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ext %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ext %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.Rp <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.Rp,na.rm=T)/mean(spec1.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.Gp <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.Gp,na.rm=T)/mean(spec1.R,na.rm=T)
    ## color swap vs spec1.ratio1??? just following minfi but that seems weird
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normC + normG)/(normA + normT)

    rg.bg <- background.correct(rg, probes)
    addresses <- probes.R$address[which(probes.R$target %in% c("NORM_A", "NORM_T"))]
    intensity.bc.R <- mean(rg.bg$R[addresses], na.rm = TRUE)
    addresses <- probes.G$address[which(probes.G$target %in% c("NORM_G", "NORM_C"))]
    intensity.bc.G <- mean(rg.bg$G[addresses], na.rm = TRUE)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio,
      intensity.bc.G=intensity.bc.G,
      intensity.bc.R=intensity.bc.R)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    ratios <- control.matrix["intensity.bc.G",]/control.matrix["intensity.bc.R",]
    reference <- which.min(abs(ratios-1))
    intensity <- (control.matrix["intensity.bc.G",] + control.matrix["intensity.bc.R",])[reference]/2
    list(R=intensity/control.matrix["intensity.bc.R",sample.idx],
         G=intensity/control.matrix["intensity.bc.G",sample.idx])
}


meffil.probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=meffil.probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

select.normalization.subsets <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("autosomal",quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("sex",quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
}

rg.to.mu <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=meffil.probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target %in% c("M","U") & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1

        addresses <- probes$address[which(probes$type == "control" & probes$dye == dye)]
        xc <- rg[[dye]][addresses]
        xc[which(xc <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        bg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), c(xf,xc)) + offset
        names(bg) <- c(names(xf), names(xc))
        bg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=meffil.probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- control.matrix[-grep("^intensity.bc", rownames(control.matrix)),]
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles + t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=meffil.probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-select.normalization.subsets(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=meffil.probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}

require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.extract.controls <- function(basename, probes=meffil.probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=meffil.probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    ## minfi does this. shouldn't it be green, not red??????
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ext %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ext %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.Rp <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.Rp,na.rm=T)/mean(spec1.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.Gp <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.Gp,na.rm=T)/mean(spec1.R,na.rm=T)
    ## color swap vs spec1.ratio1??? just following minfi but that seems weird
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normC + normG)/(normA + normT)

    rg.bg <- background.correct(rg, probes)
    addresses <- probes.R$address[which(probes.R$target %in% c("NORM_A", "NORM_T"))]
    intensity.bc.R <- mean(rg.bg$R[addresses], na.rm = TRUE)
    addresses <- probes.G$address[which(probes.G$target %in% c("NORM_G", "NORM_C"))]
    intensity.bc.G <- mean(rg.bg$G[addresses], na.rm = TRUE)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio,
      intensity.bc.G=intensity.bc.G,
      intensity.bc.R=intensity.bc.R)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    ratios <- control.matrix["intensity.bc.G",]/control.matrix["intensity.bc.R",]
    reference <- which.min(abs(ratios-1))
    intensity <- (control.matrix["intensity.bc.G",] + control.matrix["intensity.bc.R",])[reference]/2
    list(R=intensity/control.matrix["intensity.bc.R",sample.idx],
         G=intensity/control.matrix["intensity.bc.G",sample.idx])
}


meffil.probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=meffil.probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

select.normalization.subsets <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("autosomal",quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("sex",quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
}

rg.to.mu <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=meffil.probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target %in% c("M","U") & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1

        addresses <- probes$address[which(probes$type == "control" & probes$dye == dye)]
        xc <- rg[[dye]][addresses]
        xc[which(xc <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        bg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), c(xf,xc)) + offset
        names(bg) <- c(names(xf), names(xc))
        bg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=meffil.probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- control.matrix[-grep("^intensity.bc", rownames(control.matrix)),]
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=meffil.probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-select.normalization.subsets(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=meffil.probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}


####################################################
## Reshaping data
####################################################


## Sheet input interdependence
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
    if(!isEmpty(currentLayer)){
      markType <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']]
      stat <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']]
      isolate({
        # control stat choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']] <<-
          StatChoices[sapply(StatChoices, function(n) !is.null(getAesChoices(geom=markType, stat=n)))]
        # control aesthetics choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']] <<-
          getAesChoices(markType, stat)
      })
    }

    cc <- sheetList[[currentSheet]][['dynamicProperties']][['columns']]
    rr <- sheetList[[currentSheet]][['dynamicProperties']][['rows']]
    mDat <- sheetList[[currentSheet]][['datR']]()
    fields <- sheetList[[currentSheet]][['fieldNames']]()
    measures <- sheetList[[currentSheet]][['measuresR']]()

    cc1 <- ''; rr1 <- ''; cChoices <- ''; rChoices <- ''
    outTable <- NULL; outDf <- NULL;
    cc.measures <- ''; cc.dims <- '';
    rr.measures <- ''; rr.dims <- ''
    if(!is.null(fields)){
      dims <- setdiff.c(fields, measures)
      cc1 <- intersect(cc,dims); rr1 <- intersect(rr,dims)
      #         cc.measures <- intersect(cc1,measures); rr.measures <- intersect(rr1,measures)
      #         cc.dims <- setdiff(cc1,cc.measures); rr.dims <- setdiff(rr1,rr.measures)

      #         cc1 <- c(cc.dims,cc.measures); rr1 <- c(rr.dims,rr.measures)

      all.x <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesX']][['aesField']])
      all.y <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesY']][['aesField']])

      cChoices <- setdiff.c(dims, c(all.x, all.y, rr1))
      rChoices <- setdiff.c(dims, c(all.x, all.y, cc1))
      if(!isEmpty(currentLayer)){
        isolate({
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesX']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesY']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
        })
      }


      if(!is.null(mDat)){
        outType <- (sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
        if(outType=='table'){
          #             if(combineMeasures && !is.null(facets)){
          #               outTable <- cast(mDat, facets, sum)
          #               outDf <- as.data.frame(outTable)
          #             }

        } else {

        }

        if(!is.null(outDf)){
          ## add to dataList
          isolate({
            sheetNameDat <- convertSheetNameToDatName(sheetList[[currentSheet]][['dynamicProperties']][['name']])
            if(is.null(datList[[currentSheet]])){
              datList[[currentSheet]] <<- createNewDatClassObj(outDf, name=sheetNameDat, type='sheet')
            } else {
              datList[[currentSheet]][['dynamicProperties']][['dat']] <<- outDf
              datList[[currentSheet]][['dynamicProperties']][['measures']] <<- intersect(datList[[currentSheet]][['dynamicProperties']][['measures']],
                                                                                         getDefaultMeasures(outDf))
              ## add new fields, delete outdated fields, leave common fields alone since they might have user customizations
              newFields <- getDefaultFieldsList(outDf)
              oldList <- names(datList[[currentSheet]][['dynamicProperties']][['fieldsList']])
              newList <- names(newFields)
              for(n in setdiff(newList, oldList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- newFields[[n]]
              }
              for(n in setdiff(oldList, newList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- NULL
              }
            }
          })
        }
      }

    }
    isolate({
      #       sheetList[[currentSheet]][['dynamicProperties']][['dat']] <<- mDat
      #       sheetList[[currentSheet]][['dynamicProperties']][['cMeasures']] <<- cc.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['cDims']] <<- cc.dims
      #       sheetList[[currentSheet]][['dynamicProperties']][['rMeasures']] <<- rr.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['rDims']] <<- rr.dims
      if(are.vectors.different(cc1, sheetList[[currentSheet]][['dynamicProperties']][['columns']])){
        triggerUpdateInput('sheetColumns')
      }
      if(are.vectors.different(rr1, sheetList[[currentSheet]][['dynamicProperties']][['rows']])){
        triggerUpdateInput('sheetRows')
      }
      sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- cc1
      sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- rr1
      sheetList[[currentSheet]][['dynamicProperties']][['colChoices']] <<- cChoices
      sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']] <<- rChoices
      sheetList[[currentSheet]][['dynamicProperties']][['outputTable']] <<- outTable
      sheetList[[currentSheet]][['dynamicProperties']][['outputDataframe']] <<- outDf
    })
  }
}, priority=1)




## Switching sheet
observe({
  v <- input$sheetList
  isolate({
    if(!isEmpty(v)) projProperties[['activeSheet']] <<- v
  })

})
observe({
  updateInput[['activeSheet']]
  updateSelectInput(session, 'sheetList', choices=(sheetListNames()),
                    selected=isolate(projProperties[['activeSheet']]))
})


## modify sheet name
observe({
  v <- input$sheetName
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      if(!isEmpty(v) && isEmpty(sheetListNames()[v])){
        ## the second condition makes sure v is different
        ## update doc's rmd
        oldName <- paste('`', sheetList[[currentSheet]][['dynamicProperties']][['name']], '`', sep='')
        newName <- paste('`', v, '`', sep='')
        sapply(names(docList), function(currentDoc){
          docList[[currentDoc]][['rmd']] <<- gsub(oldName, newName, docList[[currentDoc]][['rmd']], fixed=TRUE)
          NULL
        })
        triggerUpdateInput('docRmd')

        sheetList[[currentSheet]][['dynamicProperties']][['name']] <<- v
      }
    }
  })

})
observe({
  updateInput[['sheetName']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['name']])
  } else ''
  updateTextInput(session, 'sheetName', value=null2String(s))
})

## link sheet name to corresponding data name
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    s <- sheetList[[currentSheet]][['dynamicProperties']][['name']]
    isolate({
      if(!is.null(datList[[currentSheet]])){
        datList[[currentSheet]][['dynamicProperties']][['name']] <<- convertSheetNameToDatName(s)
        triggerUpdateInput('datName')
      }
    })
  }
})

## Selecting data for sheet
observe({
  v <- input$sheetDatList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['datId']] <<- v
  })

})
observe({
  updateInput[['sheetDatId']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['datId']])
  } else ''
  choices <- datListNames()
  choices <- choices[!sapply(choices, isDatBasedonSheet, sheetId=currentSheet)]
  updateSelectInput(session, 'sheetDatList', choices=null2String(choices),
                    selected=null2String(s))
})

## whether use molten data?
observe({
  v <- input$combineMeasures
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']] <<- as.logical(v)
    }
  })

})
observe({
  updateInput[['combineMeasures']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']])
  } else FALSE
  updateCheckboxInput(session, 'combineMeasures', value=null2String(s))
})

## Manipulating columns
observe({
  v <- input$columns
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- v
  })

})
observe({
  updateInput[['sheetColumns']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['columns']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['colChoices']]} else ''
  updateSelectizeInput(session, 'columns', choices=null2String(choices), selected=null2String(s))
})

## Manipulating rows
observe({
  v <- input$rows
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- v
  })

})
observe({
  updateInput[['sheetRows']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['rows']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']]} else ''
  updateSelectizeInput(session, 'rows', choices=null2String(choices), selected=null2String(s))
})

## Manipulating output type
observe({
  v <- input$outputTypeList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['outputType']] <<- v
  })

})
observe({
  updateInput[['sheetOutput']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
  } else ''
  updateSelectInput(session, 'outputTypeList', selected=null2String(s))
})

## Selecting ggplot layer for sheet
observe({
  v <- input$layerList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- v
    }
  })
})
observe({
  updateInput[['sheetPlotLayer']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
  } else ''
  choices <- if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['layerNames']]()
  updateSelectInput(session, 'layerList', choices=null2String(choices),
                    selected=null2String(s))
})

## Selecting aesthetic
observe({
  v <- input$aesList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) {
        currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['sheetLayerAes']]
  currentSheet <- projProperties[['activeSheet']]
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']])
    }
  }

  updateSelectInput(session, 'aesList', choices=null2String(choices),
                    selected=null2String(s))
})

## set aes map or set option
observe({
  v <- input$aesMapOrSet
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']] <<- v

            ## set default value
            if(v=='set' && isEmpty(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<-
                switch(currentAes,
                       'aesLabel'='My Label', 'aesFamily'='Times', 'aesFontface'='plain',
                       'aesColor'=, 'aesBorderColor'='darkblue',
                       'aesSize'=8, 'aesLineheight'=1,
                       0
                )

              triggerUpdateInput('aesValue')
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesMapOrSet']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- 'map'
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        s1 <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        if(!are.vectors.different('set', s1)) s <- 'set'
      }
    }
  }
  updateRadioButtons(session, 'aesMapOrSet', selected=s)
})

## map or set UI
output$mapOrSetUI <- renderUI({
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        useMapping <- are.vectors.different('set',
                                            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        isolate({
          aes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]]
          if(useMapping){
            s <- null2String(aes[['aesField']])
            choices <- if(currentAes %in% c('aesX','aesY')) {
              aes[['fieldChoices']]
            } else {
              sheetList[[currentSheet]][['fieldNames']]()
            }
            if(!(s %in% choices)) choices[s]=s ## this is needed when s="", otherwise selected will defaults to the first value

            aggFun <- null2String(aes[['aesAggFun']])
            aggFunchoices <- YFunChoices
            if(!(aggFun %in% aggFunchoices)) aggFunchoices[aggFun]=aggFun

            fluidRow(
              column(4,
                     selectizeInput(inputId='aesField', label='Field',
                                    choices=choices, selected=s, multiple=FALSE,
                                    options = list(create = TRUE))
              ),
              column(4,
                     checkboxInput(inputId='aesAggregate', label='Aggregate Field',
                                   value=aes[['aesAggregate']]),
                     conditionalPanel('input.aesAggregate==true',
                                      selectizeInput(inputId='aesAggFun', label='By',
                                                     choices=aggFunchoices,
                                                     selected=aggFun, multiple=FALSE,
                                                     options = list(create = TRUE))
                     )

              ),
              column(4,
                     conditionalPanel('output.canAesFieldBeContinuous==true',
                                      radioButtons('aesDiscrete', 'Treat Field as',
                                                   choices=c('Continuous'='continuous',
                                                             'Discrete'='discrete'),
                                                   selected=ifelse(aes[['aesDiscrete']], 'discrete', 'continuous'),
                                                   inline=FALSE)
                     )


              )
            )
          } else {
            switch(currentAes,
                   'aesLabel'=textInput('aesValue', '', value=aes[['aesValue']]),
                   'aesFontface'=selectInput('aesValue','',choices=FontFaceChoices, selected=aes[['aesValue']]),
                   'aesFamily'=selectInput('aesValue','',choices=FontFamilyChoices, selected=aes[['aesValue']]),
                   'aesColor'=, 'aesBorderColor'=NULL,
                   numericInput('aesValue', 'Value', value=aes[['aesValue']], step=0.1)
            )
          }
        })
      }
    }
  }
})

## set aesValue
observe({
  v <- input$aesValue
  vColor <- input$aesValueColor
  ## using isEmpty instead of is.null below will cause aesValue not being able to be deleted by user
  ## not ideal, but due to the inability of setting value on jscolorPicker
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          if((currentAes=='aesColor' || currentAes=='aesBorderColor') && !isEmpty(vColor)) v <- paste('#', vColor, sep='')
          if(!isEmpty(v)) sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<- v
        }
      }
    }
  })

})
# observe({
#   updateInput[['aesValue']]
#   currentSheet <- (projProperties[['activeSheet']])
#   s <- 0
#   if(!isEmpty(currentSheet)){
#     currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
#     if(!isEmpty(currentLayer)){
#       currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
#       if(!isEmpty(currentAes)){
#         s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']])
#         switch(currentAes,
#                'aesLabel'=updateTextInput(session, 'aesValue', value=s),
#                'aesFamily'=, 'aesFontface'=updateSelectInput(session, 'aesValue', selected=s),
#                'aesColor'=, 'aesBorderColor'=
#                  NULL, # no update jscolorInput available
#
#                updateNumericInput(session, 'aesValue', value=s)
#         )
#       }
#     }
#   }
#
# })

## set aes field
observe({
  v <- input$aesField
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']] <<- v

              ## set default field properties
              if(isEmpty(v) && currentLayer != 'Plot'){
                v <- null2String(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']][['aesList']][[currentAes]][['aesField']])
              }
              is.measure <- v %in% sheetList[[currentSheet]][['measuresR']]()
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']] <<-
                is.measure  ## just for capturing this information to customize choices for agg fun
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- is.measure
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- if(is.measure) 'sum' else 'length'
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- !is.measure
              sapply(c('aesAggregate','aesAggFun','aesDiscrete'), triggerUpdateInput)

              ## set default xlab, ylab
              if(!isEmpty(v)){
                fieldNames <- sheetList[[currentSheet]][['fieldNames']]()
                i.match <- match(v, fieldNames)
                if(!is.na(i.match)){
                  fieldName <- names(fieldNames)[i.match]
                  switch(currentAes,
                         'aesX'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']] <<- fieldName
                           triggerUpdateInput('plotXlab')
                         },
                         'aesY'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']] <<- fieldName
                           triggerUpdateInput('plotYlab')
                         }
                         )

                }
              }

            }
          }
        }
      }
    })
  }

})
# observe({
#   updateInput[['aesField']]
#   currentSheet <- (projProperties[['activeSheet']])
#   s <- choices <- ''
#   if(!isEmpty(currentSheet)){
#     currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
#     if(!isEmpty(currentLayer)){
#       currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
#       if(!isEmpty(currentAes)){
#         s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']])
#         choices <- if(currentAes %in% c('aesX','aesY')) {
#           sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['fieldChoices']]
#         } else {
#           sheetList[[currentSheet]][['fieldNames']]()
#         }
#       }
#     }
#   }
#
#   updateSelectizeInput(session, 'aesField', choices=null2String(choices), selected=null2String(s))
# })

output$canAesFieldBeContinuous <- reactive({
  ans <- FALSE
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        ans <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['canFieldBeContinuous']]()
      }
    }
  }
  ans
})
outputOptions(output, "canAesFieldBeContinuous", suspendWhenHidden=FALSE)

## set aes aggregate
observe({
  v <- input$aesAggregate
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- v
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesAggregate']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- FALSE
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']])

        }
      }
    }
    updateCheckboxInput(session, 'aesAggregate', value=s)
  })

})


## set aes agg fun
observe({
  v <- input$aesAggFun
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['aesAggFun']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- ''
    choices <- YFunChoices
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']]
          is.measure <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']]
          if(!is.null(is.measure) && !is.measure) choices <- AggFunChoicesDimension
        }
      }
    }

    if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
    updateSelectizeInput(session, 'aesAggFun', choices=null2String(choices), selected=null2String(s))
  })
})

## set aes discrete
observe({
  v <- input$aesDiscrete
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            isDiscrete <- (v=='discrete')
            if(currentAes %in% c('aesX', 'aesY')){
              ## can't mix discrete with continuous scales on x or y, so need to keep all layers the same
              for(layer in names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])){
                sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
              }
            } else {
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesDiscrete']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- 'discrete'
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          d <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']])
          if(!isEmpty(d) && !d){
            s <- 'continuous'
          }

        }
      }
    }
    updateRadioButtons(session, 'aesDiscrete', selected=s)
  })
})

## set Mark Type / geom
observe({
  v <- input$markList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']] <<- v
          # set default stat type & position
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<-
            switch(v, 'boxplot'='boxplot', 'identity')
          triggerUpdateInput('layerStatType')
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<-
            switch(v, 'bar'='dodge', 'identity')
          triggerUpdateInput('layerPositionType')
        }
      }
    }
  })
})
observe({
  updateInput[['layerGeom']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']])
      #choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geomChoices']])
    }
  }
  updateSelectInput(session, 'markList', selected=null2String(s))
})

## set Stat Type
observe({
  v <- input$statTypeList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){

          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerStatType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']])
    }
  }

  updateSelectInput(session, 'statTypeList', choices=null2String(choices), selected=null2String(s))
})

## set y fun
observe({
  v <- input$yFunList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerYFun']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']])
    }
  }
  choices <- YFunChoices
  if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
  updateSelectizeInput(session, 'yFunList', choices=null2String(choices), selected=null2String(s))
})



## set PositionType
observe({
  v <- input$layerPositionType
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']])
    }
  }
  updateSelectizeInput(session, 'layerPositionType', selected=null2String(s))
})

## set Position Height
observe({
  v <- empty2NULL(as.numeric(input$layerPositionHeight))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionHeight']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']])
    }
  }
  updateTextInput(session, 'layerPositionHeight', value=null2String(s))
})

## set Position Width
observe({
  v <- empty2NULL(as.numeric(input$layerPositionWidth))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionWidth']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']])
    }
  }
  updateTextInput(session, 'layerPositionWidth', value=null2String(s))
})




tabS <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
                   (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )
canLatexPNG <- tryCatch(length(make.png(tabS)), error=function(e) FALSE)


output$sheetOutput <- renderUI({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    switch(sheetList[[currentSheet]][['dynamicProperties']][['outputType']],
           'table'=if(canLatexPNG) imageOutput('sheetOutputTable') else {
             tags$div(
               HTML(paste(capture.output(Hmisc::html(sheetList[[currentSheet]][['tableR']]())), collapse=" "))
             )
           },
           'plot'=plotOutput('ggplot'))
  }

})


output$sheetOutputTable <- renderImage(if(canLatexPNG) {
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    tab <- sheetList[[currentSheet]][['tableR']]()

    if(!is.null(tab)){
      #width  <- session$clientData$output_test_width
      #height <- session$clientData$output_test_height

      # For high-res displays, this will be greater than 1
      pixelratio <- session$clientData$pixelratio
      fileName <- make.png(tab, resolution=72*pixelratio)
      pngFile <- readPNG(fileName)

      # Return a list containing the filename
      list(src = normalizePath(fileName),
           width = dim(pngFile)[2],
           height = dim(pngFile)[1],
           alt = "Output not available")
    }
  }
}, deleteFile = TRUE)

# x <- tabular( (Species + 1) ~ (n=1) + Format(digits=3)*
#                 (Sepal.Length + Sepal.Width)*(mean + Justify(r)*sd), data=iris )
# tags$div(
#   HTML(paste(capture.output(Hmisc::html(x)), collapse=" "))
# )

## Reshaped output
output$reshapedDat <- renderTable({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['outputTable']]}
})

ggplotOutput <- reactiveValues()
observe({
  if(input$autoRefresh=='refresh'){
    currentSheet <- projProperties[['activeSheet']]
    if(!isEmpty(currentSheet)){
      ggplotOutput[['plot']] <- sheetList[[currentSheet]][['plotR']]()
    }
  } else {
    isolate({
      if(!is.null(ggplotOutput[['plot']])) ggplotOutput[['plot']] <- ggplotOutput[['plot']] + theme_grey()
    })
  }
})
output$ggplot <- renderPlot({
  ggplotOutput[['plot']]
})



## add Layer
observe({
  v <- input$addLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        existingNames <- names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])
        layerName <- make.unique(c(existingNames, 'Overlay'), sep='_')[length(existingNames)+1]

        newLayer <- createNewLayer()
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]] <<- newLayer
        sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- layerName

        #copy from Plot layer
        plotLayer <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']]
        names1 <- names(plotLayer)
        for(n1 in names1){
          if(n1=='aesList'){
            names2 <- names(plotLayer[[n1]])
            for(n2 in names2){
              names3 <- names(plotLayer[[n1]][[n2]])
              for(n3 in names3){
                if(n3 != 'aesField' && typeof(plotLayer[[n1]][[n2]][[n3]]) != 'closure'){#
                  sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]][[n2]][[n3]] <<- plotLayer[[n1]][[n2]][[n3]]
                }
              }
              setAesReactives(currentSheet, layerName, n2)
            }
          } else {
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]] <<- plotLayer[[n1]]
          }
        }

      }
    }
  })
})
## delete Layer
observe({
  v <- input$deleteLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer) && currentLayer!='Plot'){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- 'Plot'
        }
      }
    }
  })
})
## bring Layer to top
observe({
  v <- input$bringToTop
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          temp <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]]
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- temp
        }
      }
    }
  })
})

## add sheet
observe({
  v <- input$addSheet
  isolate({
    if(v){
      addSheet()
    }
  })
})
## delete sheet
observe({
  v <- input$deleteSheet
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        sheets <- names(sheetList)
        i <- match(currentSheet, sheets)
        sheetList[[currentSheet]] <<- NULL
        projProperties[['activeSheet']] <<- ifelse(length(sheets)>i, sheets[i+1],
                                                   ifelse(i>1, sheets[i-1], ''))
      }
    }
  })
})

#' Load a bunch of dependencies by filename
#' 
#' This is useful for reducing pollution in the global namespace,
#' and not loading multiple files twice unnecessarily.
#'
#' @export
#' @param ... see examples.
#' @param envir environment. The parent environment to use when calling
#'   \code{base::source} to fetch dependencies.
#' @param local logical. If \code{TRUE} and \code{envir} is missing,
#'   it will set \code{envir = parent.frame()}.
#' @examples
#' \dontrun{
#' helper_fn <- define('some/dir/helper_fn')
#' define(c('some/dir/helper_fn', 'some/other_dir/library_fn'), function(helper_fn, library_fn) { ... }
#' helper_fns <<- define('some/dir/helper_fn1', 'some/otherdir/helper_fn2')
#' helper_fns[[1]]('do something'); helper_fns[[2]]('do something else')
#' }
define <- (function() {
  number_of_required_arguments <- function(fn) {
    function_has_variable_number_of_arguments <- '...' %in% names(formals(fn))
    if (function_has_variable_number_of_arguments) return(NA_real_)
    function_arguments <- formals(fn)
    required_arguments <- sapply(function_arguments, class) == 'name'
    sum(required_arguments)
  }

  process_function_with_no_dependencies <- function(fn) {
    number_of_arguments <- number_of_required_arguments(fn)
    if (number_of_arguments == 0) fn()
    else if (number_of_arguments == 1) fn(define)
    else stop("Ramd::define only processes functions with <= 1 ",
              "arguments if no dependencies are given, but the ",
              "passed function has ", number_of_required_arguments, 
              " required arguments")
  }

  flatten <- function(lists) {    
    atomic_vector <- unlist(c(lists))
    delimited_string <- paste(atomic_vector, collapse = ' ')
    strsplit(delimited_string, '[^-a-zA-Z0-9.-_`:\\\\\\/]+')[[1]]
  }

  parse_dependencies <- function(arguments) {
    cd <- current_directory()
    if (any(sapply(arguments, class) != 'character'))
      stop("Ramd::define only accepts atomic character vectors for ",
           "specifying dependencies")
    dependencies <- unlist(c(arguments))
    if ('Ramd.no_flatten' %in% names(.Options) &&
        getOption('Ramd.no_flatten')) dependencies
    else flatten(dependencies)
  }

  fetch_dependencies <- function(arguments, envir) {
    dependency_names <- parse_dependencies(arguments)
    dependencies <- lapply(dependency_names, load_dependency, envir = envir)
    names(dependencies) <- dependency_names
    dependencies
  }

  verify_number_of_required_arguments_matches_number_of_dependencies <-
    function(fn, number_of_dependencies) {
      num_of_required_arguments <- number_of_required_arguments(fn)
      if (is.na(num_of_required_arguments)) return(TRUE)
      if (num_of_required_arguments != number_of_dependencies)
        stop("Ramd::define was not able to load dependencies because ",
             number_of_dependencies, " dependenc",
             # Pluralization, for fun!
             if (number_of_dependencies == 1) 'y was' else 'ies were',
             " passed in but the given function has ",
             num_of_required_arguments, " required argument",
             if (num_of_required_arguments == 1) '' else 's')
      TRUE
    }

  function(..., envir = parent.env(topenv()), local) {
    if (!missing(local) && isTRUE(local)) {
      envir <- parent.frame()
    }

    arguments <- list(...)
    if ('packages' %in% names(arguments)) {
      if (length(arguments) == 1)
        stop("Ramd::define does more than just load packages, ",
             "please provide some dependencies or a function. ",
             "To just load packages, use Ramd::packages")
      packages(arguments$packages)
      arguments <- arguments[names(arguments) != 'packages']
    }

    fn <- tail(arguments, 1)[[1]]
    valid_function <- is.function(fn)
    if (valid_function) {
      dependencies <- head(arguments, -1)
      if (length(dependencies) == 0)
        return (process_function_with_no_dependencies(fn))
    } else dependencies <- arguments

    if (valid_function)
      verify_number_of_required_arguments_matches_number_of_dependencies(
        fn, length(unlist(dependencies)))

    dependencies <- fetch_dependencies(dependencies, envir = envir)
    if (valid_function) do.call(fn, unname(dependencies))
    else dependencies
  }

})()
require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.extract.controls <- function(basename, probes=probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$G[which(probes.G$target == "BISULFITE CONVERSION I"
                               & probes.G$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ExternalType %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ExternalType %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normA + normT)/(normC + normG)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    reference <- which.min(abs(control.matrix["dye.bias",]-1))
    intensity <- mean(control.matrix[c("normA","normT","normC","normG"), reference])
    list(R=intensity/mean(control.matrix[c("normA", "normT"),sample.idx]),
         G=intensity/mean(control.matrix[c("normC", "normG"),sample.idx]))
}


probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

apply.quantile.normalization <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     #| !mixture & sex == "M" & eq.wild("autosomal",quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("sex",quantile.sets$chr.type)
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     #&& length(rg$R) == length(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
     ##&& all(names(rg$R) == names(rg$G)))
}

rg.to.mu <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target != "OOB" & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        xf.bkg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), xf) + offset
        names(xf.bkg) <- names(xf)
        xf.bkg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    ## quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-apply.quantile.normalization(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}

## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}

textareaInput <- function(inputId, label, value="", placeholder="", rows=2){
  tagList(
    div(strong(label), style="margin-top: 5px;"),
    tags$style(type="text/css", "textarea {width:100%; margin-top: 5px;}"),
    tags$textarea(id = inputId, placeholder = placeholder, rows = rows, value))
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='', selectize=FALSE, size=3)),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(4,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL, selectize=FALSE, size=15)
                                   ),
                            column(8,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map', inline=TRUE)
                                                    ),

                                   uiOutput('mapOrSetUI'),
                                   conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                                    jscolorInput('aesValueColor'))
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          textareaInput(inputId = 'plotTitle', label="Plot Title", value="",
                                        placeholder = 'Enter Plot Title here', rows = 2),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    strong('Font Color'), br(),
                                                    jscolorInput('textColor'), br(),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    strong('Border Color'), br(),
                                                    jscolorInput('rectColor'), br(),
                                                    strong('Fill'), br(),
                                                    jscolorInput('rectFill'), br(),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    strong('Line Color'), br(),
                                                    jscolorInput('lineColor'), br(),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   )

                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

#homeDir<-"//home/user/ENVIRONMENT/workspaces/workspace_scala/FarringtonTest/"
#fileDir<-"EDS"
#outDir<-paste(homeDir, "results", sep="")
#setwd(paste(homeDir,fileDir,sep=""))

require(rjson)

#allData = as.data.frame(fromJSON(readLines("tmp.json")))

########Model can not cope with expected[i] being too small and crashes (produces #NAN's).
########As it rounds it off and effectively tries to divide by zero
########Therefore I have set expected[i] to be an extremely small number in the #event that it is effectively zero
########This will not effect the validity of the results 

notZero=1*10^(-150)

#######################################################
## DISPERSION 
## This function estimates the dispersion parameter using the formula described in Farrington #(1996)
#######################################################

disp<-function(i){
	calc<- w*( ( (basecont-expected)^2 )/expected)
	calc[expected<notZero]=notZero
	calc
}

###################################################
## DERIVE THRESHOLD VALUES	 
## This code is used to derive the threshold values using the formula described in Farrington #1996. 
## Two weights are derived -  "threshold" if the linear trend is included and "threshold2" if the
## the linear trend is not significant.
###################################################

# if model is to include linear trend then set 'trend0'=1, differnt calc of var
threshold <-function(z,trend0){
	ifelse(trend0==1, { 
				var=varalpha+(currentmth*currentmth)*varbeta+(2*currentmth*covariance)
			},{ var=varalpha })
	tao<-(dispersion*expectedc+var)/(expectedc^2)
	U<-expectedc*(1+(2/3)*z*(tao^0.5))^(3/2)
}

###########################################################################
###				MAIN MODEL				
###########################################################################

#allData = read.csv("/home/user/ENVIRONMENT/workspaces/workspace_scala/FarringtonTest/results/baselineData.txt")
#allData = as.data.frame(fromJSON(paste(readLines("r-in.json"), collapse="")))

baselineNum = nrow(basedata)
#baseData = allData[1:baselineNum,]
#currentCount = allData[nrow(allData),"Incidents"]
#currentmth = allData[nrow(allData), "MonthNum"]
basemth = basedata$basemth
basecont = basedata$basecont

#basedata<-data.frame(basecont, basemth)
# currentc<-Data2[currentmth, 2+2]  	#LEAVE AS [,2+2] so only look at INCIDENTS. If wish to look at isolations change to [,1+1]. 
n=nrow(basedata)
w<-rep(1,times=n)					#Set weights = 1 
#----fit model with no linear trend----------------------------------------------------------------------------------------
model0<-glm(formula=basecont~1, family=quasipoisson(link=log), weights=w, data=basedata)  #model with no linear trend
	param0<-coef(model0)
	coeff0<-summary(model0)$coeff
#--------fit full model-------------------------------------------------------------------------------------------------
modelF<-glm(formula=basecont~basemth, family=quasipoisson(link=log), weights=w, data=basedata)	#Fit model
	paramF<-coef(modelF)
	hatF<-lm.influence(modelF)$hat
#---calculate weights----------------     
expected<-exp(paramF[1]+(basemth*paramF[2]))  	#Estimate expected values
p<-2						#Number of esitmated parameters
calc<-sum(disp())					#First calculation of dispersion parameter
calc2<-1/(n-p)
dispersion<-if((calc2*calc)>1) calc2*calc else 1		#Calculate dispersion parameter final     
residuals1= (3/(2*(dispersion)^(1/2)))*(((basecont)^(2/3))-((expected)^(2/3))) / (((expected)^(1/6))*((1-hatF)^(1/2)))         
	residuals1[expected<notZero]=notZero 
m<-length(residuals1[residuals1<1])
k=rep(0,times=n)
	k[residuals1<1]=residuals1[residuals1<1]^-2
y<-n/(sum(k)+(n-m))				#Calculate the weights
w=k*y
	w[w==0]=y     
#----fit model with weights--------------------
modelW<-glm(formula=basecont~basemth, family=quasipoisson(link=log), weights=w, data=basedata)   
	paramW<-coef(modelW)
	coeffW<-summary(modelW)$coeff
	covaW<-vcov(modelW) 
#---------------------------------------------------
expected<-exp(paramW[1]+(basemth*paramW[2]))  	#Estimate expected values again
expectedc<-exp(paramW[1]+(currentmth*paramW[2]))	#Estimate expected value for current month again	   
varalpha<-coeffW[1,2]*coeffW[1,2]
varbeta<-coeffW[2,2]*coeffW[2,2]
covariance<-covaW[1,2]

calc<-sum(disp())					#Calculate the first part of dispersion parameter again
calc2<-1/(n-p)
dispersion<-if((calc2*calc)>1) calc2*calc else 1		#Recalculate the dispersion parameter
tvalue<-coeffW[2]/coeffW[2,2]				#T-value for beta
df<-n-p-1					#Degrees freedom
ttest<-qt(0.95,df)					#T-test for the significance of linear trend
z<-1.96  
U<-threshold(z,1)		#Calculate the threshold 
trend=1          #denotes trend is included
if (!( (tvalue>ttest | tvalue < -ttest) & expectedc<=max(basecont)))  { 
	expected<-expected*0+exp(param0)
	expectedc<-exp(param0)
	trend="noTrend"
	p<-1
	calc<-sum(disp())
	calc2<-1/(n-p)
	dispersion<-if((calc2*calc)>1) calc2*calc else 1  	#Final calculation of dispersion parameter
	U<-threshold(z,0)
}

if(expectedc<0.1) U<-1.9                 #threshold starts to increase if expected<0.1 - so fix at value << 2 => if get two cases then raise flag.
if (currentCount==0) {
	expectedc<-0 
	U<-0 
}
thresh<-U
exceed<-(currentCount-expectedc)/(U-expectedc)
if (U==0) exceed<-0 else exceed<-exceed

ifelse(sum(basecont)==0&&currentc>0,exceed<-'>1',exceed<-exceed)

output = toJSON(list(
				"expected" = expectedc[[1]],
				"threshold" = thresh[[1]],
				"trend" = trend,
				"exceed" = exceed[[1]],
				"weights" = w
		))# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            names(dimnames(l.[[i]])) = dimnames[1:length(dim(l.[[i]]))]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=names(l.)[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    lookup = b$match(rownames(x), from, to, na_rm=TRUE)
    x = x[names(lookup),]
    
    # aggregate the rest using fun
    split(x, along=along, subsets=lookup) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
source("colors.r")

#
# OUTLINE
#

# every plot function in this file makes IMHO nice formatted plots in four steps

# 1. Plot an empty plot, to inform R about ranges of data (grid needs this)
# 2. Plot background and grid
# 3. Plot data
# 4. Plot axes, box and titles

################################################################################

# Helper function for leaving out unused margins
doMargins <- function(mainTitle, xTitle, yTitle) {
  margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)
}

################################################################################

# Helper function for plotting axes and title on top of plot
doBoxTitleAndAxes <- function(mainTitle, xTitle, yTitle) {
  box(col = thillux_grey[1], bty="l")
  title(main=mainTitle, col=thillux_grey[1], xlab=xTitle, ylab=yTitle)
  axis(1, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
  axis(2, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
}

################################################################################

# Helper function for creating PDF devices
doOpenPDF <- function(pdfFile, pdfTitle) {
  pdfFilePath = "out.pdf"
  if(!is.null(pdfFile)) {
    pdfFilePath = pdfFile
  }
  pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)
}

################################################################################

# Helper function for plotting background and grid, before plotting on top of it
doPlotBackgroundAndGrid <- function() {
  u <- par("usr")
  rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)
  par(col.lab=thillux_grey[1])
  grid(col=thillux_grey[1], lty=3, lwd=0.5)
}

################################################################################

plotHistogram <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      lty=1,
      cex=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotHistogramNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    h$counts <- h$counts/sum(h$counts)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      freq=FALSE,
      lty=1,
      cex=1)

    x <- seq(min(-10.0, min(dataArray) * 0.5) , max(max(dataArray) * 1.5, 100), length=10000)
    y <- dnorm(x, mean=mean(dataArray), sd=sd(dataArray))

    par(new=TRUE)

    plot(x,y,
         type="l",
         lwd=3,
         axes=FALSE,
         col=colorScheme[2,2],
         xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
         ylab='',
         xlab='',
         main=''
    )

    polygon(x, y,
            col=colorScheme[2,2],
            border=colorScheme[2][1],
            ylab='',
            xlab='',
            main=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqnorm(dataArray, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    qqline(sort(dataArray), ylab='',
      xlab='', col=colorScheme[2,2], lwd=2)

    par(new=TRUE)

    qq <- qqnorm(sort(dataArray), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQ <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqplot(dataArray1, dataArray2, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    qq <- qqplot(sort(dataArray1), sort(dataArray2), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotPoints <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(dataArray1, dataArray2,
      type="p",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotSmoothLine <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(smooth.spline(dataArray1, dataArray2),
      type="l",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidence <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    deltaX <- abs(diff(range(xData))) / 15.0
    deltaY <- abs(diff(range(c(yData+e,yData-e)))) / 15.0
    xLim <- range(xData) + c(-deltaX, deltaX)
    yLim <- range(c(yData+e,yData-e)) + c(-deltaY, deltaY)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    arrowLength <- abs(diff(range(xData)))/25.0
    arrowTipLength <- abs(diff(range(yData)))/50.0

    rect(xData - arrowLength, yData - e, xData + arrowLength, yData + e, col=colorScheme[1,2], border=FALSE)

    segments(xData - arrowLength, yData - e, xData + arrowLength, yData - e, lend=1, col=colorScheme[1,1])
    segments(xData - arrowLength, yData + e, xData + arrowLength, yData + e, lend=1, col=colorScheme[1,1])

    segments(xData - arrowLength/2.0, yData, xData+arrowLength/2.0, yData, col=colorScheme[1,1], lwd = 1.0)

    if (connectionLines) {
      frame <- data.frame(xData,yData)
      frame <- frame[order(xData),]
      lines(frame$xData, frame$yData, col=colorScheme[1,2],lty=2)
    }

    # draw circle outlines
    rVert <- pmin(e/2.0, arrowTipLength)
    rHor <- arrowLength/5.0

    for (i in 1 : length(xData)) {
      mid1X <- xData[i] - arrowLength
      mid1Y <- yData[i] + e[i] - rVert[i]

      mid2X <- xData[i] - arrowLength
      mid2Y <- yData[i] - e[i] + rVert[i]

      mid3X <- xData[i] + arrowLength
      mid3Y <- yData[i] + e[i] - rVert[i]

      mid4X <- xData[i] + arrowLength
      mid4Y <- yData[i] - e[i] + rVert[i]

      deg <- 90 : 180
      xCircle1 <- mid1X + rHor * cos(deg/180.0 * pi)
      yCircle1 <- mid1Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle1, yCircle1, col=colorScheme[1,1])

      deg <- 180 : 270
      xCircle2 <- mid2X + rHor * cos(deg/180.0 * pi)
      yCircle2 <- mid2Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle2, yCircle2, col=colorScheme[1,1])

      polygon(c(xCircle1, xCircle2), c(yCircle1, yCircle2), col = colorScheme[1,2], border = FALSE)

      deg <- 0 : 90
      xCircle3 <- mid3X + rHor * cos(deg/180.0 * pi)
      yCircle3 <- mid3Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle3, yCircle3, col=colorScheme[1,1])

      deg <- 270 : 360
      xCircle4 <- mid4X + rHor * cos(deg/180.0 * pi)
      yCircle4 <- mid4Y + rVert[i] * sin(deg/180.0 * pi)
      lines(xCircle4, yCircle4, col=colorScheme[1,1])

      polygon(c(xCircle3, xCircle4), c(yCircle3, yCircle4), col = colorScheme[1,2], border = FALSE)
    }

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidenceContinous <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    deltaX <- abs(diff(range(xData))) / 15.0
    deltaY <- abs(diff(range(c(yData+e,yData-e)))) / 15.0
    xLim <- range(xData) + c(-deltaX, deltaX)
    yLim <- range(c(yData+e,yData-e)) + c(-deltaY, deltaY)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    polygon(c(sort(xData),rev(sort(xData))),c(yData + e, rev(yData-e)), col=colorScheme[1,2], border=FALSE)

    lines(xData, yData + e, col=colorScheme[1,1])
    lines(xData, yData - e, col=colorScheme[1,1])

    lines(xData,yData,col=colorScheme[2,1])

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotBox <- function(xData, yData, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks=10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(cut(xData, breaks=breaks), yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      col="#00000000",
      border="#00000000",
      bg="#00000000",
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(cut(xData, breaks=breaks), yData,
      type="l",
      axes=FALSE,
      col=thillux_grey[2],
      bg=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotDensity <- function(xData, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    d <- density(xData)

    plot(d, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(d$x, d$y, type="l", col=colorScheme[1,1])

    polygon(d$x, d$y, col=colorScheme[1,2], border=FALSE)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################
#!/usr/lib/R/bin/Rscript

library(methods)
library(ggplot2)
library(reshape2)

args = commandArgs(T)

mri22_data   = read.table(file=args[1], sep=',', header=T)
mri23_data   = read.table(file=args[2], sep=',', header=T)
jruby17_data = read.table(file=args[3], sep=',', header=T)
jruby9_data  = read.table(file=args[4], sep=',', header=T)
# rbx25_data   = read.table(file=args[5], sep=',', header=T)

x       = mri22_data$concurrent
mri22   = mri22_data$loss
mri23   = mri23_data$loss
jruby17 = jruby17_data$loss
jruby9  = jruby9_data$loss
# rbx25   = rbx25_data$loss

df = data.frame(x, mri22, mri23, jruby17, jruby9) #, rbx25)
df.long = melt(df, id.vars='x')

g = ggplot(df.long, aes(x, value, shape=variable)) +
    scale_shape(name='Ruby VM') +
    ylab('Percentage of lost messages') +
	xlab('Concurrent clients') +
	geom_line() +
	geom_point() +
	theme_bw()

path = paste(args[1], 'loss', 'pdf', sep='.')
print(path)
ggsave(g, file=path)
REBOL [
	Title:   "Red/System compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/utils/profiler.r
profiler/active?: no

do-cache %system/utils/r2-forward.r
do-cache %system/utils/int-to-bin.r
do-cache %system/utils/IEEE-754.r
do-cache %system/utils/virtual-struct.r
do-cache %system/utils/secure-clean-path.r
do-cache %system/linker.r
do-cache %system/emitter.r

system-dialect: make-profilable context [
	verbose:  	  0										;-- logs verbosity level
	job: 		  none									;-- reference the current job object	
	runtime-path: pick [%system/runtime/ %runtime/] encap?
	nl: 		  newline
	
	loader: do bind load-cache %system/loader.r 'self
	
	options-class: context [
		config-name:		none						;-- Preconfigured compilation target ID
		OS:					none						;-- Operating System
		OS-version:			none						;-- OS version
		ABI:				none						;-- optional ABI flags (word! or block!)
		link?:				no							;-- yes = invoke the linker and finalize the job
		debug?:				no							;-- reserved for future use
		build-prefix:		%builds/					;-- prefix to use for output file name (none: no prefix)
		build-basename:		none						;-- base name to use for output file name (none: derive from input name)
		build-suffix:		none						;-- suffix to use for output file name (none: derive from output type)
		format:				none						;-- file format
		type:				'exe						;-- file type ('exe | 'dll | 'lib | 'obj | 'drv)
		target:				'IA-32						;-- CPU target
		cpu-version:		6.0							;-- CPU version (default: Pentium Pro)
		verbosity:			0							;-- logs verbosity level
		sub-system:			'console					;-- 'GUI | 'console
		runtime?:			yes							;-- include Red/System runtime
		use-natives?:		no							;-- force use of native functions instead of C bindings
		debug?:				no							;-- emit debug information into binary
		need-main?:			no							;-- yes => emit a function prolog/epilog around global code
		PIC?:				no							;-- generate Position Independent Code
		base-address:		none						;-- base image memory address
		dynamic-linker: 	none						;-- ELF dynamic linker ("interpreter")
		syscall:			'Linux						;-- syscalls convention: 'Linux | 'BSD
		stack-align-16?:	no							;-- yes => align stack to 16 bytes
		literal-pool?:		no							;-- yes => use pools to store literals, no => store them inlined (default: no)
		unicode?:			no							;-- yes => use Red Unicode API for printing on screen
		red-pass?:			no							;-- yes => Red compiler was invoked
		red-only?:			no							;-- yes => stop compilation at Red/System level and display output
		red-store-bodies?:	yes							;-- no => do not store function! value bodies (body-of will return none)
		red-strict-check?:	yes							;-- no => defers undefined word errors reporting at run-time
		red-tracing?:		yes							;-- no => do not compile tracing code
		red-help?:			no							;-- yes => keep doc-strings from boot.red
		legacy:				none						;-- block of optional OS legacy features flags
	]
	
	compiler: make-profilable context [
		job:		 	 none							;-- shortcut for job object
		pc:			 	 none							;-- source code input cursor
		script:		 	 none							;-- source script file name
		none-type:	 	 [#[none]]						;-- marker for "no value returned"
		last-type:	 	 none-type						;-- type of last value from an expression
		locals: 	 	 none							;-- currently compiled function specification block
		definitions:  	 make block! 100
		enumerations: 	 make hash! 10
		expr-call-stack: make block! 1					;-- simple stack of nested calls for a given expression
		locals-init: 	 []								;-- currently compiler function locals variable init list
		func-name:	 	 none							;-- currently compiled function name
		block-level: 	 0								;-- nesting level of input source block
		catch-level:	 0								;-- nesting level of CATCH body block
		verbose:  	 	 0								;-- logs verbosity level
	
		imports: 	   	 make block! 10					;-- list of imported functions
		exports: 	   	 make block! 10					;-- list of exported symbols
		natives:	   	 make hash!  40					;-- list of functions to compile [name [specs] [body]...]
		ns-path:		 none							;-- namespaces access path
		ns-stack:		 none							;-- namespaces resolution stack
		ns-list:		 make hash!  8					;-- namespaces definition list [name [word type...]...]
		sym-ctx-table:	 make hash!  100				;-- reverse lookup table for contexts
		globals:  	   	 make hash!  40					;-- list of globally defined symbols from scripts
		aliased-types: 	 make hash!  10					;-- list of aliased type definitions
		keywords-list:	 make block! 20
		
		resolve-alias?:  yes							;-- YES: instruct the type resolution function to reduce aliases
		decoration:		 slash							;-- decoration separator for namespaces
		shift-right-sym: to word! ">>>"					;-- workaround REBOL LOAD limitation
		
		debug-lines: reduce [							;-- runtime source line/file information storage
			'records make block!  1000					;-- [address line file] records
			'files	 make hash!   20					;-- filenames table
		]
		
		pos:		none								;-- validation rules cursor for error reporting
		return-def: to-set-word 'return					;-- return: keyword
		fail:		[end skip]							;-- fail rule
		rule: value: v: none							;-- global parsing rules helpers
		
		number!: 	  [byte! integer!]					;-- reserved for internal use only
		bit-set!: 	  [byte! integer! logic!]			;-- reserved for internal use only
		any-float!:	  [float! float32! float64!]		;-- reserved for internal use only
		any-number!:  union number! any-float!			;-- reserved for internal use only
		pointers!:	  [pointer! struct! c-string!] 		;-- reserved for internal use only
		any-pointer!: union pointers! [function!]		;-- reserved for internal use only
		poly!:		  union any-number! pointers!		;-- reserved for internal use only
		any-type!:	  union poly! [logic!]			  	;-- reserved for internal use only
		type-sets:	  [									;-- reserved for internal use only
			number! poly! any-type! any-pointer!
			any-number! bit-set!
		]
		
		comparison-op: [= <> < > <= >=]
		
		functions: to-hash compose [
		;--Name--Arity--Type----Cc--Specs--		   Cc = Calling convention
			+		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			-		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			*		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			/		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			and		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			or		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			xor		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			//		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- modulo
			(to-word "%")		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- remainder (real syntax: %)
			>>		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right signed
			<<		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift left signed
			-**		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right unsigned
			=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			not		[1	inline	- [a [bit-set!] 		   return: [bit-set!]]]
			push	[1	inline	- [a [any-type!]]]
			pop		[0	inline	- [						   return: [integer!]]]
			throw	[1	inline	- [n [integer!]]]
		]
		
		repend functions [shift-right-sym copy functions/-**]
		
		user-functions: tail functions					;-- marker for user functions
		
		action-class: context [action: type: data: none]
		
		struct-syntax: [
			pos: opt [into ['align integer! opt ['big | 'little]]]	;-- struct's attributes
			pos: some [word! into [func-pointer | type-spec]]		;-- struct's members
		]
		
		pointer-syntax: ['integer! | 'byte! | 'float32! | 'float64! | 'float!]
		
		func-pointer: ['function! set value block! (check-specs '- value)]
		
		type-syntax: [
			'logic! | 'integer! | 'byte! | 'int16!		;-- int16! needed for AVR8 backend
			| 'float! | 'float32! | 'float64!
			| 'c-string!
			| 'pointer! into [pointer-syntax]
			| 'struct!  into [struct-syntax]
		]

		type-spec: [
			pos: some type-syntax | pos: set value word! (	;-- multiple types allowed for internal usage		
				unless any [
					all [v: find-aliased/prefix value v <> value find aliased-types v pos/1: v]			;-- rewrite the type to prefix it
					find aliased-types value
					all [v: resolve-ns value v <> value enum-type? v pos/1: v]	;-- rewrite the type to prefix it
					all [enum-type? value pos/1: 'integer!]
				][throw false]							;-- stop parsing if unresolved type			
			)
		]		
		
		keywords: make hash! [
			;&			 [throw-error "reserved for future use"]
			?? 			 [comp-print-debug]
			as			 [comp-as]
			assert		 [comp-assert]
			size? 		 [comp-size?]
			if			 [comp-if]
			either		 [comp-either]
			case		 [comp-case]
			switch		 [comp-switch]
			until		 [comp-until]
			while		 [comp-while]
			any			 [comp-expression-list]
			all			 [comp-expression-list/_all]
			exit		 [comp-exit]
			return		 [comp-exit/value]
			catch		 [comp-catch]
			declare		 [comp-declare]
			null		 [comp-null]
			context		 [comp-context]
			with		 [comp-with]
			comment 	 [comp-comment]
			
			true		 [also true pc: next pc]		  ;-- converts word! to logic!
			false		 [also false pc: next pc]		  ;-- converts word! to logic!
			
			func 		 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			function 	 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			alias 		 [raise-level-error "an alias"]	  ;-- alias declaration not allowed at this level
		]
		
		calling-keywords: [								;-- keywords accepted in expr-call-stack
			?? as assert size? if either case switch until while any all
			return catch
		]
		
		foreach [word action] keywords [append keywords-list word]
		foreach [name spec] functions  [append keywords-list name]
		
		calc-line: has [idx head-end prev p header][
			header: head pc
			idx: (index? pc) - header/1  				;-- calculate real pc position (not counting hidden header)
			prev: 1

			parse header [								;-- search for closest line marker
				skip									;-- skip over header length
				some [
					set p pair! (
						if p/2 = idx [return p/1]		;-- exact value position match
						if p/2 > idx [return prev]		;-- closest value position match 
						prev: p/1
					)
				]
			]
			return p/1									;-- return last marker
		]
		
		store-dbg-lines: has [dbg pos][
			dbg: debug-lines
			unless pos: find dbg/files script [
				pos: tail dbg/files
				append dbg/files script
			]
			repend dbg/records [
				emitter/tail-ptr calc-line index? pos
			]
		]
		
		quit-on-error: does [
			clean-up
			if system/options/args [quit/return 1]
			halt
		]
		
		throw-error: func [err [word! string! block!]][
			print [
				"*** Compilation Error:"
				either word? err [
					join uppercase/part mold err 1 " error"
				][reform err]
				"^/*** in file:" mold script
				either locals [join "^/*** in function: " func-name][""]
			]
			if pc [
				print [
					"*** at line:" calc-line lf
					"*** near:" mold copy/part pc 8
				]
			]
			quit-on-error
		]
		
		throw-warning: func [msg [string! block!] /near][
			print [
				"*** Warning:" 	reform msg
				"^/*** in:" 	mold script
				"^/*** at:" 	mold copy/part any [all [near back pc] pc] 8
			]
		]
		
		raise-level-error: func [kind [string!]][
			pc: back pc
			throw-error reform ["declaring" kind "at this level is not allowed"]
		]
		
		raise-casting-error: does [
			backtrack 'as
			throw-error "multiple type casting not allowed"
		]
		
		;raise-paren-error: does [
		;	pc: back pc
		;	throw-error "parens are only allowed nested in an expression"
		;]
		
		raise-runtime-error: func [error [integer!]][
			emitter/target/emit-get-pc				;-- get current CPU program counter address
			last-type: [integer!]					;-- emit-get-pc returns an integer! (required for next line)
			compiler/comp-call '***-on-quit reduce [error <last>] ;-- raise a runtime error
		]
		
		undecorate: func [value [word! path! set-word! set-path!] /local v pos][
			unless find v: mold value decoration [return value]
			
			while [pos: find v decoration][
				unless find ns-list to path! copy/part v pos [
					pos: next pos
					v: append replace/all copy/part head v pos decoration slash pos
					return load v
				]
				v: at v pos + 1
			]
			value
		]
		
		backtrack: func [value /local res][
			if find [word! path! set-word! set-path!] type?/word value [
				value: undecorate value
			]
			pc: any [res: find/only/reverse pc value pc]
			to logic! res
		]
		
		blockify: func [value][either block? value [value][reduce [value]]]

		literal?: func [value][
			not any [word? value get-word? value path? value block? value value = <last>]
		]
		
		not-initialized?: func [name [word!] /local pos][
			all [
				locals
				pos: find locals /local
				pos: find next pos name
				not find locals-init name
			]
		]
		
		get-alias-id: func [pos [hash!]][
			1000 + divide 1 + index? pos 2
		]
		
		get-type-id: func [value /local type alias][
			with-alias-resolution off [type: resolve-expr-type value]
			
			either alias: find-aliased/position type/1 [		
				get-alias-id alias
			][
				type: resolve-aliased type
				type: switch/default type/1 [
					any-pointer! ['int-ptr!]
					pointer! [pick [int-ptr! byte-ptr!] type/2/1 = 'integer!]
				][type/1]
				select emitter/datatype-ID type
			]
		]
		
		system-reflexion?: func [path [path! set-path!] /local def][
			if path/1 = 'system [
				switch path/2 [
					alias [
						unless path/3 [
							backtrack path
							throw-error "invalid system/alias path access"
						]
						unless def: find-aliased/position path/3 [
							backtrack path
							throw-error ["undefined alias name:" path/3]
						]
						last-type: [integer!]
						return get-alias-id def			;-- special encoding for aliases
					]
					words [
						unless path/3 [
							backtrack path
							throw-error "invalid system/words path access"
						]
						path: remove/part copy path 2
						return either 1 = length? path [
							either set-path? path [to set-word! path/1][path/1]
						][
							path
						]
					]
					; add new special reflective system path here
				]
			]
			none
		]
		
		base-type?: func [value][
			if block? value [value: value/1]
			to logic! find/skip emitter/datatypes value 3
		]
		
		unbox: func [value][
			either object? value [value/data][value]
		]
		
		clear-docstrings: func [spec [block!]][
			remove-each s spec [string? s]
			spec
		]
		
		get-return-type: func [name [word!] /check /local type spec][
			unless all [
				spec: find-functions name
				any [
					type: select spec/2/4 return-def
					check
				]
			][
				backtrack name
				throw-error ["return type missing in function:" name]
			]
			any [type none-type]
		]
		
		set-last-type: func [spec [block!]][
			if spec: select spec return-def [last-type: spec]
		]
		
		local-variable?: func [name [word!]][
			all [locals find locals name]
		]
		
		exists-variable?: func [name [word! set-word!]][
			name: to word! name
			to logic! any [
				local-variable? name
				find globals name
			]
		]
		
		select-globals: func [name [word!] /local pos][
			all [
				pos: find globals name
				pos/2
			]
		]
		
		get-variable-spec: func [name [word!]][
			any [
				all [locals select locals name]
				select-globals name
			]
		]
		
		get-arity: func [spec [block!] /local count][
			count: 0
			parse spec [opt block! any [word! block! (count: count + 1)]]
			count
		]
		
		any-path?: func [value][
			find [path! set-path! lit-path!] type?/word value
		]
		
		any-float?: func [type [block!]][
			find any-float! type/1
		]
		
		any-pointer?: func [type [block!]][
			type: first resolve-aliased type
			
			either find type-sets type [
				not empty? intersect get type any-pointer!
			][
				to logic! find any-pointer! type
			]
		]

		equal-types?: func [type1 [word!] type2 [word!]][
			type1: either find type-sets type1 [get type1][reduce [type1]]
			type2: either find type-sets type2 [get type2][reduce [type2]]
			not empty? intersect type1 type2
		]
		
		equal-types-list?: func [types [block!]][
			forall types [							;-- check if all last expressions are of same type
				unless types/1/1 [return none-type]	;-- test if type is defined
				types/1: resolve-aliased types/1	;-- reduce aliases and pseudo-types
				if all [
					not head? types
					not equal-types? types/-1/1 types/1/1
				][
					return none-type
				]
			]
			first head types						;-- all types equal, return the first one
		]
						
		with-alias-resolution: func [mode [logic!] body [block!] /local saved][
			saved: resolve-alias?
			resolve-alias?: mode	
			do body
			resolve-alias?: saved
		]
		
		find-aliased: func [type [word!] /prefix /position /local ns pos][
			if all [ns: resolve-ns type find aliased-types ns][type: ns]
			if prefix [return ns]
			pos: find aliased-types type
			either position [pos][all [pos pos/2]]
		]
		
		resolve-aliased: func [type [block!] /local name][
			name: type/1
			all [
				type/1								;-- ensure it is not [none]
				not base-type? name
				not find type-sets name
				not all [
					enum-type? name
					type: [integer!]
				]
				not type: find-aliased name
				throw-error ["unknown type:" type]
			]
			type
		]
		
		resolve-type: func [name [word!] /with parent [block! none!] /local type local?][
			type: any [
				all [parent select parent name]
				local?: all [locals select locals name]
				select-globals name
			]
			if all [not type find functions name][
				return reduce ['function! functions/(decorate-fun name)/4]
			]
			if any [
				all [not local?	any [enum-type? name enum-id? name]]
				all [type enum-type? type/1]
			][
				return [integer!]
			]
			unless any [not resolve-alias? none? type base-type? type/1][
				type: find-aliased type/1
			]
			type
		]
		
		resolve-struct-member-type: func [spec [block!] name [word!] /local type][
			unless type: select spec name [
				while [not all [any-path? pc/1 find pc/1 name]][pc: back pc]
				throw-error [
					"invalid struct member" to lit-word! name "in:" mold to path! pc/1
				]
			]
			either resolve-alias? [resolve-aliased type][type]
		]
		
		resolve-path-type: func [path [path! set-path!] /short /parent prev /local type path-error saved][
			path-error: [
				pc: skip pc -2
				throw-error "invalid path value"
			]
			either word? path/1 [
				either parent [
					resolve-struct-member-type prev path/1	;-- just check for correct member name
					with-alias-resolution on [
						type: resolve-type/with path/1 prev
					]
				][
					with-alias-resolution on [
						type: resolve-type path/1
					]
				]
			][
				type: reduce [type?/word path/1]
			]
			
			unless type path-error
			
			either tail? skip path 2 [
				switch/default type/1 [
					c-string! [
						check-path-index path 'string
						[byte!]
					]
					pointer!  [
						check-path-index path 'pointer
						reduce [type/2/1]				;-- return pointed value type
					]
					struct!   [
						unless word? path/2 [
							backtrack path
							throw-error ["invalid struct member" path/2]
						]
						type: resolve-struct-member-type type/2 path/2
						
						if all [
							not short
							not set-path? path
							type/1 = 'function!
						][
							type: select type/2 return-def
						]
						type
					]
				] path-error
			][
				either short [
					resolve-path-type/parent/short next path second type
				][
					resolve-path-type/parent next path second type
				]
			]
		]
		
		get-type: func [value /local type][
			switch/default type?/word value [
				none!	 [none-type]					;-- no type case (func with no return value)
				tag!	 [either value = <last> [last-type][ [logic!] ]]
				logic!	 [[logic!]]
				word! 	 [resolve-type value]
				char!	 [[byte!]]
				integer! [[integer!]]
				decimal! [[float!]]
				string!	 [[c-string!]]
				path!	 [resolve-path-type value]
				object!  [value/type]
				block!	 [
					if value/1 = 'not [return get-type value/2]	;-- special case for NOT multitype native
					
					either 'op = second get-function-spec value/1 [
						either base-type? type: get-return-type value/1 [
							type						;-- unique returned type, stop here
						][
							get-type value/2			;-- recursively search for left operand base type
						]
					][
						get-return-type value/1
					]
				]
				paren!	 [
					switch/default value/1 [
						struct!  [reduce pick [[value/2][value/1 value/2]] word? value/2]
						pointer! [reduce [value/1 value/2]]
					][
						next next reduce ['array! length? value	'pointer! get-type value/1]	;-- hide array size
					]
				]
				get-word! [
					type: resolve-type to word! value
					switch/default type/1 [
						function! [type]
						integer! byte! float! float32! [compose/deep [pointer! [(type/1)]]]
					][
						throw-error ["invalid datatype for a get-word:" mold type]
					]
				]
			][
				throw-error ["not accepted datatype:" type? value]
			]
		]
		
		enum-type?: func [name [word!] /local type][
			all [
				type: find/skip enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				reduce [next type]
			]
		]
		
		enum-id?: func [name [word!] /local pos][
			all [
				pos: find/skip next enumerations name 3
				reduce [pos/-1]
			]
		]

		get-enumerator: func [name [word!] /value /local pos][
			all [
				pos: find/skip next enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				pos/2
			]
		]
		
		set-enumerator: func [
			identifier [word!] name [word! block!] value [integer! word!] /local list v
		][
			store-ns-symbol identifier
			if ns-path [
				add-ns-symbol to set-word! identifier
				identifier: ns-prefix identifier
			]
			
			if word? name [name: reduce [name]]
			forall name [
				store-ns-symbol name/1
				if ns-path [
					add-ns-symbol to set-word! name/1
					name/1: ns-prefix name/1
				]
				check-enum-word name/1
			]
			name: head name
			
			if all [
				word? value
				none? value: get-enumerator resolve-ns value
			][
				throw-error ["cannot resolve literal enum value for:" form name]
			]
			forall name [
				if verbose > 3 [print ["Enum:" identifier "[" name/1 "=" value "]"]]
				repend enumerations [identifier name/1 value]
			]
			value: value + 1
		]

		resolve-expr-type: func [expr /quiet /local type func? spec][
			if block? expr [
				switch type?/word expr/1 [
					set-word! [expr: expr/2]			;-- resolve assigned value type
					set-path! [expr: to path! expr/1]	;-- resolve path type
				]
			]			
			func?: all [
				block? expr word? expr/1
				not find comparison-op expr/1
				spec: find functions expr/1 		 ;-- works for unary & binary functions only!
				spec: spec/2
			]
			type: case [
				object? expr [
					expr/type						 ;-- type casting case
				]
				all [func? find [op inline] spec/2][ ;-- works for unary & binary functions only!
					any [
						all [
							expr/1 <> 'not			;-- @@ issue with 'not return type
							spec: select spec/4 return-def
							base-type? spec/1		;-- determined return type
							spec
						]
						get-type expr/2				;-- recursively search for return type
					]
				]
				all [func? quiet][
					any [
						select spec/4 return-def	;-- workaround error throwing in get-return-value
						none-type
					]
				]
				'else [
					expr: get-type expr
					if resolve-alias? [expr: resolve-aliased expr]
					expr
				]
			]
			type
		]
		
		check-throw: does [
			unless any [locals positive? catch-level][
				backtrack 'throw
				throw-error "THROW used without a wrapping CATCH"
			]
		]
		
		push-call: func [action [word! set-word! set-path!]][
			append/only expr-call-stack action
			if verbose >= 4 [
				new-line/all expr-call-stack off
				?? expr-call-stack
			]
		]
		
		pop-calls: does [clear expr-call-stack]
		
		cast: func [obj [object!] /quiet /local value ctype type][
			value: obj/data
			ctype: resolve-aliased obj/type
			type: get-type value

			if all [not quiet type = obj/type type/1 <> 'function!][
				throw-warning/near [
					"type casting from" type/1 
					"to" obj/type/1 "is not necessary"
				] 'as
			]
			if any [
				all [type/1 = 'function! not find [function! integer!] ctype/1]
				all [find [float! float64!] ctype/1 not any-float? type]
				all [find [float! float64!] type/1  not any-float? ctype]
				all [type/1 = 'float32! not find [float! float64! integer!] ctype/1]
				all [ctype/1 = 'byte! find [c-string! pointer! struct!] type/1]
				all [
					find [c-string! pointer! struct!] ctype/1
					find [byte! logic!] type/1
				]
			][
				backtrack value
				throw-error [
					"type casting from" type/1
					"to" ctype/1 "is not allowed"
				]
			]	
			unless literal? value [return value]	;-- shield the following literal conversions
			
			switch ctype/1 [
				byte! [
					switch type/1 [
						integer! [value: to char! value and 255]
						logic! 	 [value: pick [#"^(01)" #"^(00)"] value]
					]
				]
				integer! [
					if find [byte! logic!] type/1 [
						value: to integer! value
					]
				]
				logic! [
					switch type/1 [
						byte! 	 [value: value <> null]
						integer! [value: value <> 0]
					]
				]
			]
			value
		]
		
		decorate-function: func [name [word!]][
			to word! join "_local_" form name
		]
		
		find-functions: func [name [word!]][
			if all [
				locals
				type: select locals name
				type/1 = 'function!
			][
				name: decorate-function name
			]
			any [
				find functions name
				find functions resolve-ns name
			]
		]

		get-function-spec: func [name [word!] /local spec][
			all [
				spec: find-functions name
				spec/2
			]
		]

		decorate-fun: func [name [word!] /local type][
			either all [
				locals
				type: select locals name
				block? type
				type/1 = 'function!
			][
				decorate-function name
			][
				name
			]
		]

		remove-func-pointers: has [vars name][
			vars: any [find/tail locals /local []]
			forall vars [
				if all [
					word? vars/1
					block? vars/2
					vars/2/1 = 'function!
				][
					name: decorate-function vars/1
					remove/part find functions name 2
				]
			]
		]
		
		init-local: func [name [word!] expr casted [block! none!] /local pos type][
			append locals-init name					;-- mark as initialized
			pos: find locals name
			unless block? pos/2 [					;-- if not typed, infer type
				insert/only at pos 2 type: any [
					casted
					resolve-expr-type expr
				]
				if verbose > 2 [print ["inferred type" mold type "for variable:" pos/1]]
			]
		]
		
		order-ctx-candidates: func [a b][				;-- order by increasing path size,
			to logic! not all [							;-- and word! before path!.
				path? a
				any [
					word? b
					all [path? b greater? length? a length? b]
				]
			]
		]
		
		store-ns-symbol: func [name [word!] /local pos][
			if ns-path [
				either pos: find/skip sym-ctx-table name 2 [
					either block? pos/2 [
						if find/only pos/2 ns-path [exit]
					][
						if ns-path = pos/2 [exit]
						pos/2: reduce [pos/2]
					]
					append/only pos/2 copy ns-path
					sort/compare pos/2 :order-ctx-candidates
				][
					append sym-ctx-table name
					append/only sym-ctx-table copy ns-path
				]
			]
		]
		
		add-ns-symbol: func [name [set-word!] /local ctx ns][
			name: to word! name
			if find second find/only ns-list ns-path name [exit]
			if ns-stack [
				ctx: tail ns-stack
				until [
					ctx: back ctx
					if all [
						ns: find/only ns-list to path! ctx/1
						find second ns name 
					][exit]
					head? ctx
				]
			]
			append second find/only ns-list ns-path name
		]
		
		add-symbol: func [name [word!] value type][
			unless type [type: get-type value]
			unless 'array! = first head type [type: copy type]
			append globals reduce [name type]
			type
		]
		
		add-function: func [type [word!] spec [block!] cc [word!]][
			repend functions [
				to word! spec/1 reduce [get-arity spec/3 type cc new-line/all spec/3 off]
			]
			if find-attribute spec/3 'callback [
				append last functions 'callback
			]
		]
		
		compare-func-specs: func [
			f-type [block!] c-type [block!] /with fun [word!] cb [get-word!] /local spec pos idx
		][
			if with [
				cb: to word! cb
				if functions/:cb/3 <> functions/:fun/3 [
					throw-error [
						"incompatible calling conventions between"
						fun "and" cb
					]
				]
			]
			if pos: find f-type /local [f-type: head clear copy pos] ;-- remove locals
			if block? f-type/1 [f-type: next f-type]	;-- skip optional attributes block
			if block? c-type/1 [c-type: next c-type]	;-- skip optional attributes block
			idx: 2
			foreach [name type] f-type [
				if type <> c-type/:idx [return false]
				idx: idx + 2
			]
			true
		]
		
		ns-decorate: func [path [path!] /global /set][
			to get pick [set-word! word!] to logic! set mold path	;-- unless / use: replace/all mold path slash decoration
		]

		ns-join: func [ns [path! word!] name [word! path! set-word! set-path!]][
			join ns to word! mold/flat name
		]

		ns-prefix: func [name [word! path! set-word! set-path!] /set][
			if set-word? name [name: to word! name]
			name: ns-join ns-path name
			either set [ns-decorate/set name][ns-decorate name]
		]
		
		check-enum-word: func [name [word!] /local error][
			case [
				all [find keywords name name <> 'context][
					error: ["attempt to redefine a protected keyword:" name]
				]
				find functions name [
					error: ["attempt to redefine existing function name:" name]
				]
				find definitions name [
					error:  ["attempt to redefine existing definition:" name]
				]
				find-aliased name [
					error:  ["attempt to redefine existing alias definition:" name]
				]
				base-type? name [
					error:  ["redeclaration of base type:" name ]
				]
				any [
					exists-variable? name
					get-variable-spec name
				][										;-- it's a variable
					error:  ["redeclaration of variable:" name]
				]
				enum-type? name [
					error:  ["redeclaration of enum identifier:" name ]
				]
				enum-id? name [
					error:  ["redeclaration of enumerator:" name ]
				]
			]
			if error [throw-error error]
		]
		
		check-keywords: func [name [word!]][
			if find keywords name [
				throw-error ["attempt to redefine a protected keyword:" name]
			]
		]
		
		check-path-index: func [path [path! set-path!] type [word!] /local ending enum-value][
			ending: path/2
			case [
				all [type = 'pointer ending = 'value][]	;-- pass thru case
				word? ending [
					either all [
						not local-variable? ending
						enum-value: get-enumerator ending
					][
						path/2: ending: enum-value
					][
						unless any [
							local-variable? ending
							find globals ending: resolve-ns ending
							get-enumerator ending
						][
							backtrack path
							throw-error ["undefined" type "index variable"]
						]
						if 'integer! <> first resolve-type ending [
							backtrack path
							throw-error [
								"attempt to use" type
								"indexing with a non-integer! variable"
							]
						]
					]
				]
				not integer? ending [
					backtrack path
					throw-error [
						"attempt to use" type
						"indexing with a non-integer! value"
					]
				]
			]
		]
		
		check-func-name: func [name [word!] /only][
			if find functions name [
				pc: back pc
				throw-error ["attempt to redefine existing function name:" name]
			]
			if any [enum-type? name	enum-id? name][
				pc: back pc
				throw-error ["attempt to redefine existing enumerator:" name]
			]
			if all [not only find any [locals globals] name][
				pc: back pc
				throw-error ["a variable is already using the same name:" name]
			]
		]
		
		check-duplicates: func [
			name [word!] args [block! none!] locs [block! none!]
			/local dups
		][
			if args [remove-each item args: copy args [not word? item]]
			if locs [remove-each item locs: copy locs [not word? item]]
			
			if any [
				all [args (length? unique args) <> length? args]
				all [locs (length? unique locs) <> length? locs]
				all [args locs not empty? dups: intersect args locs]
			][
				throw-error [
					"duplicate variable definition in function" name
					either dups [reform ["for:" mold/only new-line/all dups no]][""]
				]
			]
		]
		
		check-specs: func [
			name specs /extend
			/local type type-def spec-type attribs value args locs cconv pos
		][
			unless block? specs [
				throw-error "function definition requires a specification block"
			]
			cconv: ['cdecl | 'stdcall]
			attribs: [
				[cconv ['variadic | 'typed | 'custom]]
				| [['variadic | 'typed | 'custom] cconv]
				| 'catch | 'infix | 'variadic | 'typed | 'custom | 'callback | cconv
			]
			type-def: pick [[func-pointer | type-spec] [type-spec]] to logic! extend

			unless catch [
				parse specs [
					opt [								;-- function's attribute and main doc-string
						string! opt [into attribs]		;-- can be specified in any order
						| into attribs opt string!
					]
					pos: copy args any [pos: word! into type-def opt string!]	;-- arguments definition
					pos: opt [							;-- return type definition				
						set value set-word! (					
							rule: pick reduce [[into type-spec] fail] value = return-def
						) rule
						opt string!
					]
					pos: opt [/local copy locs some [pos: word! opt [into type-spec]]] ;-- local variables definition
				]
			][
				throw-error rejoin ["invalid definition for function " name ": " mold pos]
			]
			if block? args [
				clear-docstrings args
				foreach [name type] args [
					if enum-id? name [
						throw-warning ["function's argument redeclares enumeration:" name]
					]
				]
			]
			check-duplicates name args locs
		]
		
		check-conditional: func [name [word!] expr][
			if last-type/1 <> 'logic! [check-expected-type/key name expr [logic!]]
		]
		
		check-expected-type: func [name [word!] expr expected [block!] /ret /key /local type alias][
			unless any [not none? expr key][return none]   ;-- expr == none for special keywords
			if all [
				not all [object? expr expr/action = 'null] ;-- avoid null type resolution here
				not none? expr							;-- expr can be false, so explicit check for none is required
				first type: resolve-expr-type expr		;-- first => deep check that it's not [none]
			][											;-- check if a type is returned or none
				type: resolve-aliased type
				if alias: find-aliased expected/1 [expected: alias]
			]
			if all [
				ret
				block? expr
				any [set-word? expr/1 set-path? expr/1]
			][
				type: none
			]
			unless any [
				all [
					object? expr
					expr/action = 'null
					type: either expected/1 = 'any-type! [expr/type][expected]	;-- morph null type to expected
					any-pointer? expected
				]
				all [
					type
					any [
						find type-sets expected/1
						find type-sets type/1
					]
					equal-types? type/1 expected/1		;-- internal polymorphic case
				]
				all [
					type
					type/1 = 'function!
					any [
						find [any-type! any-pointer!] expected/1
						all [
							expected/1 = 'function!
							compare-func-specs/with type/2 expected/2 name expr	 ;-- callback case
						]
					]
				]
				expected = type 						;-- normal single-type case
				all [
					type
					type/1 = 'integer!
					enum-type? expected/1				;-- TODO: add also a value check for enums
				]
			][
				if expected = type [type: 'null]		;-- make null error msg explicit
				any [
					backtrack any [all [block? expr expr/1] expr]
					backtrack name
				]
				throw-error [
					reform case [
						ret   [["wrong return type in function:" name]]
						key   [[
							uppercase form name "requires a conditional expression"
							either find [while until] name ["as last expression"][""]
						]]
						'else [["argument type mismatch on calling:" name]]
					]
					"^/*** expected:" join mold expected #","
					"found:" mold new-line/all any [type [none]] no
				]
			]
			type
		]
		
		check-arguments-type: func [name args /local entry spec list type][
			if find [set-word! set-path!] type?/word name [exit]
			
			entry: find functions name
			if all [
				not empty? spec: entry/2/4 
				block? spec/1
			][
				spec: next spec							;-- jump over attributes block
			]
			list: clear []
			forall args [
				either all [decimal? args/1 spec/2/1 = 'float32!][
					args/1:	make action-class [			;-- inject type casting to float32!
						action: 'type-cast
						type: [float32!]
						data: args/1					;-- literal float!
					]
					append/only list spec/2				;-- pass-thru for float! values used as float32! arguments
				][
					append/only list check-expected-type name args/1 spec/2
				]
				spec: skip spec	2
			]
			if all [
				any [
					find emitter/target/comparison-op name
					find emitter/target/bitwise-op name
				]
				not equal-types? list/1/1 list/2/1		;-- allow implicit casting for math ops only
			][
				backtrack name
				throw-error [
					"left and right argument must be of same type for:" name
					"^/*** left:" join list/1/1 #"," "right:" list/2/1
				]
			]
			if find emitter/target/math-op name	[
				case [
					any [
						all [list/1/1 = 'byte! any-pointer? list/2]
						all [list/2/1 = 'byte! any-pointer? list/1]
					][
						backtrack name
						throw-error [
							"arguments must be of same size for:" name
							"^/*** left:" join list/1/1 #"," "right:" list/2/1
						]
					]
					any [string? unbox args/1 string? unbox args/2][
						backtrack name
						throw-error "a literal string cannot be used with a math operator"
					]
				]
			]
		]
		
		check-variable-arity?: func [spec [block!] /local attribs][
			all [
				attribs: get-attributes spec
				any [
					all [find attribs 'variadic 'variadic]
					all [find attribs 'typed 'typed]
					all [find attribs 'custom 'custom]
				]
			]
		]
		
		check-body: func [body][
			case/all [
				not block? :body [throw-error "expected a block of code"]
				empty? body  	 [throw-error "expected a non-empty block of code"]
			]
		]
		
		fetch-into: func [								;-- compile sub-block
			code [block! paren!] body [block!] /root
			/local save-pc level
		][
			if root [
				level: block-level						;-- save block level from parent context
				clear expr-call-stack
			]
			save-pc: pc
			pc: code
			do body
			if root [block-level: level]
			next pc: save-pc
		]
		
		get-attributes: func [spec [block!]][
			any [
				all [block? spec/1 spec/1]
				all [string? spec/1 block? spec/2 spec/2]
			]
		]
		
		find-attribute: func [spec [block!] name [word!]][
			either list: get-attributes spec [
				to logic! find list name
			][
				false
			]
		]
		
		get-cconv: func [specs [block!]][
			pick [cdecl stdcall] to logic! all [
				not empty? specs
				find-attribute specs 'cdecl
			]
		]
		
		fetch-func: func [name /local specs type cc attribs][
			name: to word! name
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			if ns-path [name: ns-prefix name]
			check-func-name name
			check-specs name specs: pc/2
			specs: copy specs
			clear-docstrings specs
			
			type: 'native
			cc:   'stdcall								;-- default calling convention
			
			if all [
				not empty? specs
				attribs: get-attributes specs
			][
				case [
					find attribs 'infix [
						if 2 <> get-arity specs [
							throw-error [
								"infix function requires 2 arguments, found"
								get-arity specs "for" name
							]
						]
						type: 'infix
					]
					find attribs 'cdecl   [cc: 'cdecl]
					find attribs 'stdcall [cc: 'stdcall]	;-- get ready when fastcall will be the default cc
				]
			]
			add-function type reduce [name none specs] cc
			emitter/add-native name
			repend natives [
				name specs pc/3 script
				all [ns-path copy ns-path]
				all [ns-stack copy/deep ns-stack]		;@@ /deep doesn't work on paths
			]
			pc: skip pc 3
		]
		
		reduce-logic-tests: func [expr /local test value][
			test: [logic? expr/2 logic? expr/3]
			
			if all [
				block? expr
				find [= <>] expr/1
				any test
			][
				expr: either all test [
					do expr								;-- let REBOL reduce the expression
				][
					expr: copy expr
					if any [
						all [expr/1 = '= not all [expr/2 expr/3]]
						all [expr/1 = first [<>] any [expr/2 = true expr/3 = true]]
					][
						insert expr 'not
					]
					remove-each v expr [any [find [= <>] v logic? v]]
					if any [
						all [
							word? expr/1
							any [
								get-variable-spec expr/1
								enum-id? expr/1
							]
						]
						paren? expr/1
						block? expr/1
						object? expr/1
					][
						expr: expr/1					;-- remove outer brackets if variable
					]
					expr
				]
			]
			expr
		]
		
		process-export: has [defs cc ns func? spec][
			if word? pc/2 [
				unless find [stdcall cdecl] cc: pc/2 [
					throw-error ["invalid calling convention specifier:" cc]
				]
				pc: next pc
			]
			foreach name pc/2 [
				func?: no
				unless any [word? name path? name][
					throw-error ["invalid exported symbol:" mold name]
				]
				if path? name [name: resolve-ns-path name]
				unless any [
					find globals name
					func?: find-functions name
				][
					throw-error ["undefined exported symbol:" mold name]
				]
				append exports name
				
				if func? [
					spec: select functions name
					spec/3: any [cc 'cdecl]
					unless spec/5 = 'callback [append spec 'callback]
				]
			]
		]
		
		process-import: func [defs [block!] /local lib list cc name specs spec id reloc pos][
			unless block? defs [throw-error "#import expects a block! as argument"]
			
			unless parse defs [
				some [
					pos: set lib string! (
						unless list: select imports lib [
							repend imports [lib list: make block! 10]
						]
					)
					pos: set cc ['cdecl | 'stdcall]		;-- calling convention	
					pos: into [
						some [
							specs:						;-- new function mapping marker
							pos: set name set-word! (
								name: to word! name
								store-ns-symbol name
								if ns-path [
									add-ns-symbol to set-word! name
									name: ns-prefix name
								]
								check-func-name name
							)
							pos: set id   string!   (repend list [id reloc: make block! 1])
							pos: set spec block!    (
								check-specs/extend name spec
								clear-docstrings spec
								specs: copy specs
								specs/1: name
								add-function 'import specs cc
								emitter/import-function name reloc
							)
						]
					]
				]
			][
				throw-error ["invalid import specification at:" pos]
			]		
		]
		
		process-syscall: func [defs [block!] /local name id spec pos][
			unless block? defs [throw-error "#syscall expects a block! as argument"]
			unless parse defs [
				some [
					pos: set name set-word! (check-func-name name: to word! name)
					pos: set id   integer!
					pos: set spec block!    (
						check-specs/extend name spec
						spec: copy spec
						clear-docstrings spec
						add-function 'syscall reduce [name none spec] 'syscall
						append last functions id		;-- extend definition with syscode
					)
				]
			][
				throw-error ["invalid syscall specification at:" pos]
			]
		]
		
		process-enum: func [name value /local enum-value enum-names][
			unless word? name [throw-error "enumeration expected a word as name"]
			
			either block? value [
				check-enum-word name 					;-- first checking enumeration identifier possible conflicts
				parse value [
					(enum-value: 0)
					any [
						[
							copy enum-names word!
							| (enum-names: make block! 10) some [
								set enum-name set-word!
								(append enum-names to word! enum-name)
							]	set enum-value [integer! | word!]
						] 
						(enum-value: set-enumerator name enum-names enum-value)
						| set enum-name 1 skip (
							throw-error ["invalid enumeration:" to word! enum-name]
						)
					]
				]
			][
				throw-error ["invalid enumeration (block required!):" mold value]
			]
		]
		
		process-get: func [code [block!] /local value][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #get directive
				return none
			]
			red/process-get-directive code/2 pc
			fetch-expression
		]
		
		process-in: func [code [block!] /local value][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #in directive
				return none
			]
			red/process-in-directive code/2 code/3 pc
			fetch-expression
		]
		
		process-call: func [code [block!] /local mark][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #call directive
				return none
			]
			mark: tail red/output
			red/process-call-directive code/2 yes
			remove/part pc 2
			insert pc mark
			clear mark
			none										;-- do not return an expression to compile
		]
		
		comp-chunked: func [body [block!]][
			emitter/chunks/start
			do body
			emitter/chunks/stop
		]

		comp-directive: has [body][
			switch/default pc/1 [
				#import  [process-import  pc/2  pc: skip pc 2]
				#export  [process-export  pc/2  pc: skip pc 2]
				#syscall [process-syscall pc/2	pc: skip pc 2]
				#call	 [process-call	  pc]
				#get	 [process-get	  pc]
				#in		 [process-in	  pc]
				#enum	 [process-enum pc/2 pc/3 pc: skip pc 3]
				#verbose [set-verbose-level pc/2 pc: skip pc 2]
				#script	 [								;-- internal compiler directive
					unless pc/2 = 'in-memory [
						compiler/script: secure-clean-path pc/2	;-- set the origin of following code
					]
					pc: skip pc 2
				]
			][
				throw-error ["unknown directive" pc/1]
			]
		]
		
		comp-print-debug: has [out][
			unless word? name: pc/2 [
				throw-error "?? needs a word as argument"
			]
			out: next next compose/deep [
				2 (to pair! reduce [calc-line 1])		;-- hidden line offset header
				print-line [
					2 (to pair! reduce [calc-line 1])	;-- hidden line offset header
					(join name ": ") (name)
				]
			]
			out/2: next next out/2
			change/part pc out 2
			none
		]
		
		comp-comment: does [
			pc: next pc
			either block? pc/1 [pc: next pc][fetch-expression]
			none
		]
		
		comp-with: has [ns list with-ns words res ctx][
			ns: pc/2
			unless all [any [word? ns block? ns] block? pc/3][
				throw-error "WITH invalid argument"
			]
			unless block? ns [ns: reduce [ns]]
			
			forall ns [
				ns/1: either path? ctx: resolve-ns/path ns/1 [ctx][to path! ctx]
				unless find/only ns-list ns/1 [throw-error ["undefined context" ns/1]]
			]
			with-ns: unique copy ns
			
			list: clear []
			foreach ns with-ns [
				either empty? res: intersect list words: to block! second find/only ns-list ns [
					append list words
				][
					throw-warning rejoin [
						"contexts are using identical word"
						pick ["s: " ": "] 1 < length? res
						res
					]
				]
			]

			list: copy with-ns
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack list
			
			fetch-into/root pc/3 [comp-dialect]
			
			pc: skip pc 3
			clear skip tail ns-stack negate length? list
			if empty? ns-stack [ns-stack: none]
			
			none
		]
		
		comp-context: has [name level][
			unless block? pc/2 [throw-error "context specification block is missing"]
			unless set-word? pc/-1 [throw-error "context's name setting is missing"]
			unless zero? block-level [
				pc: back pc
				throw-error "context has to be declared at root level"
			]
			
			check-keywords name: to word! pc/-1
			if any [										;@@ factorize this out
				all [locals find locals name]
				find globals name
				find functions name
				find aliased-types name
				find definitions name
				find enumerations name
			][
				pc: back pc
				throw-error "context name is already taken"
			]
			pc: next pc
			
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack to word! mold/flat name
			
			either ns-path [
				append ns-path to word! mold/flat name
			][
				ns-path: to lit-path! mold/flat name		;-- workaround newline flag remanence issue
			]
			either find/only ns-list ns-path [
				throw-error ["context" name "already defined"]
			][
				repend ns-list [copy ns-path make hash! 32]
			]

			fetch-into/root pc/1 [comp-dialect]
			
			remove back tail ns-path
			if empty? ns-path [ns-path: none]
			remove back tail ns-stack
			if empty? ns-stack [ns-stack: none]
			
			pc: next pc
			none
		]
		
		comp-declare: has [rule value pos offset ns][
			unless find [set-word! set-path!] type?/word pc/-1 [
				throw-error "assignment expected before literal declaration"
			]
			value: to paren! reduce either find [pointer! struct!] pc/2 [
				rule: get pick [struct-syntax pointer-syntax] pc/2 = 'struct!
				unless catch [parse pos: pc/3 rule][
					throw-error ["invalid literal syntax:" mold pos]
				]
				if all [
					pc/2 = 'struct!
					(length? pc/3) <> (length? unique/skip pc/3 2)
				][
					throw-error ["duplicate member name in struct:" mold pc/3]
				]
				if pc/3/1 = 'float64! [pc/3/1: 'float!]
				offset: 3
				[pc/2 pc/3]
			][
				unless all [word? pc/2 resolve-aliased reduce [pc/2]][
					throw-error ["declaring literal for type" pc/2 "not supported"]
				]
				value: pc/2
				if all [ns-path ns: find-aliased/prefix value][value: ns]
				offset: 2
				['struct! value]
			]
			pc: skip pc offset
			value
		]
		
		comp-null: does [
			pc: next pc
			make action-class [action: 'null type: [any-pointer!] data: 0]
		]
		
		comp-as: has [ctype ptr? expr type][
			ctype: pc/2
			if ptr?: find [pointer! struct! function!] ctype [ctype: reduce [pc/2 pc/3]]
			
			unless any [
				parse blockify ctype [func-pointer | type-syntax]
				find-aliased ctype
			][
				throw-error ["invalid target type casting:" ctype]
			]
			pc: skip pc pick [3 2] to logic! ptr?
			expr: fetch-expression

			if all [
				block? ctype
				ctype/1 = 'function!
				type: get-type expr
				type/1 = 'function!
			][
				unless compare-func-specs ctype/2 copy type/2 [
					throw-error "invalid functions casting: specifications not matching"
				]
			]
			if all [object? expr expr/action = 'null][
				pc: back pc
				throw-error "type casting on null value is not allowed"
			]
			make action-class [
				action: 'type-cast
				type: blockify ctype
				data: expr
			]
		]
		
		comp-assert: has [expr line][
			either job/debug? [
				line: calc-line
				pc: next pc
				expr: fetch-expression/final
				check-conditional 'assert expr			;-- verify conditional expression
				expr: process-logic-encoding expr yes

				insert/only pc next next compose [
					2 (to pair! reduce [line 1])			;-- hidden line offset header
					***-on-quit 98 as integer! system/pc
				]
				set [unused chunk] comp-block-chunked		;-- compile TRUE block
				emitter/set-signed-state expr				;-- properly set signed/unsigned state
				emitter/branch/over/on chunk reduce [expr/1] ;-- branch over if expr is true
				emitter/merge chunk
				last-type: none-type
				<last>
			][
				pc: next pc
				fetch-expression							;-- consume next expression
				none
			]
		]
		
		comp-alias: has [name pos][
			unless set-word? pc/-1 [
				throw-error "assignment expected for ALIAS"
			]
			unless find [struct! function!] pc/2 [
				throw-error "ALIAS only allowed for struct! and function!"
			]
			name: to word! pc/-1
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			all [
				not base-type? name
				ns-path
				name: ns-prefix name
			]
			if find aliased-types name [
				pc: back pc
				throw-error reform [
					"alias name already defined as:"
					mold aliased-types/:name
				]
			]
			if base-type? name [
				pc: back pc
				throw-error "a base type name cannot be defined as an alias name"
			]
			repend aliased-types [name reduce [pc/2 pc/3]]
			switch pc/2 [
				struct! [
					unless catch [parse pos: pc/3 struct-syntax][
						throw-error ["invalid struct syntax:" mold pos]
					]
				]
				function! [check-specs 'pointer pc/3]
			]
			pc: skip pc 3
			none
		]
		
		comp-size?: has [type expr][
			pc: next pc
			unless all [
				word? expr: pc/1
				type: any [
					all [base-type? expr expr]
					all [enum-type? expr [integer!]]
					find-aliased expr
				]
				pc: next pc
			][
				expr: fetch-expression/final	
				type: resolve-expr-type expr
			]
			emitter/get-size type expr
		]
		
		comp-exit: func [/value /local expr type ret][
			unless locals [
				throw-error [pc/1 "is not allowed outside of a function"]
			]
			pc: next pc
			ret: select locals return-def
			
			either value [				
				unless ret [							;-- check if return: declared
					throw-error [
						"RETURN keyword used without return: declaration in"
						func-name
					]
				]
				expr: fetch-expression/final/keep		;-- compile expression to return
				type: check-expected-type/ret func-name expr ret
				ret: either type [last-type: type <last>][none]
			][
				if ret [throw-error "EXIT keyword is not compatible with declaring a return value"]
			]
			emitter/target/emit-exit
			ret
		]
		
		comp-catch: has [offset locals-size][
			pc: next pc
			fetch-expression/keep/final
			if any [not last-type last-type <> [integer!]][
				backtrack 'catch
				throw-error "CATCH expects a threshold value of type integer!"
			]
			unless block? pc/1 [
				backtrack 'catch
				throw-error "CATCH requires a body block as 2nd argument"
			]
			
			catch-level: catch-level + 1
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			catch-level: catch-level - 1
			
			offset: emitter/target/emit-open-catch length? chunk/1
			foreach ptr chunk/2 [ptr/1: ptr/1 + offset]	;-- account for (catch-frame + push) opcodes
			emitter/merge chunk
			
			locals-size: either locals [
				abs last emitter/stack
			][
				emitter/target/locals-offset
			]
			emitter/target/emit-close-catch locals-size
			
			last-type: none-type
			none
		]

		comp-block-chunked: func [/only /test name [word!] /local expr][
			emitter/chunks/start
			expr: either only [
				fetch-expression/final					;-- returns first expression
			][
				comp-block/final						;-- returns last expression
			]
			if test [
				check-conditional name expr				;-- verify conditional expression
				expr: process-logic-encoding expr no
			]
			reduce [
				expr 
				emitter/chunks/stop						;-- returns a chunk block!
			]
		]
		
		process-logic-encoding: func [expr invert? [logic!]][	;-- preprocess logic values
			case [
				logic? expr [ [#[true]] ]
				find [word! path!] type?/word expr  [
					emitter/target/emit-integer-operation '= [<last> 0]
					reduce [not invert?]
				]
				object? expr [
					expr: cast expr
					unless find [word! path!] type?/word any [
						all [block? expr expr/1] expr 
					][
						emitter/target/emit-integer-operation '= [<last> 0]
					]
					process-logic-encoding expr invert?
				]
				block? expr [
					case [
						find comparison-op expr/1 [expr]
						'else [process-logic-encoding expr/1 invert?]
					]
				]
				tag? expr [
					either last-type/1 = 'logic! [
						emitter/target/emit-integer-operation '= [<last> 0]
						reduce [not invert?]
					][expr] 
				]
				'else [expr]
			]
		]
		
		comp-if: has [expr unused chunk][		
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'if expr					;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
	
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/on chunk expr/1			;-- insert IF branching			
			emitter/merge chunk
			last-type: none-type
			<last>
		]
		
		comp-either: has [expr e-true e-false c-true c-false offset t-true t-false ret][
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'either expr				;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
			check-body pc/2								;-- check FALSE block
			
			set [e-true c-true]   comp-block-chunked	;-- compile TRUE block
			set [e-false c-false] comp-block-chunked	;-- compile FALSE block

			t-true:  resolve-expr-type/quiet e-true
			t-false: resolve-expr-type/quiet e-false

			last-type: either all [
				t-true/1 t-false/1
				t-true:  resolve-aliased t-true			;-- alias resolution is safe here
				t-false: resolve-aliased t-false
				equal-types? t-true/1 t-false/1
			][t-true][none-type]						;-- allow nesting if both blocks return same type

			if any [
				all [
					locals								;-- if in function body
					tail? pc							;-- and if at tail of body
					ret: select locals return-def		;-- and if function returns something
					ret/1 = 'logic!						;-- and if it returns a logic! value
				]
				all [
					not empty? expr-call-stack
					last-type/1 = 'logic!				;-- and if EITHER returns a logic! too
				]
			][
				if block? e-true  [emitter/logic-to-integer/with e-true  c-true]
				if block? e-false [emitter/logic-to-integer/with e-false c-false]
			]
		
			offset: emitter/branch/over c-false
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/adjust/on c-true negate offset expr/1	;-- skip over JMP-exit
			emitter/merge emitter/chunks/join c-true c-false
			<last>
		]
		
		comp-case: has [cases list test body op bodies offset types][
			pc: next pc
			cases: pc/1
			list:  make block! 8
			types: make block! 8
			
			until [										;-- collect and pre-compile all cases
				append expr-call-stack #test			;-- marker for disabling expression post-processing
				fetch-into cases [						;-- compile case test
					append/only list comp-block-chunked/only/test 'case
					cases: pc							;-- set cursor after the expression
				]
				clear find expr-call-stack #test
				
				append expr-call-stack #body			;-- marker for enabling expression post-processing
				fetch-into cases [						;-- compile case body
					append/only list body: comp-block-chunked
					append/only types resolve-expr-type/quiet body/1
				]
				clear find expr-call-stack #body
				tail? cases: next cases
			]
			
			bodies: comp-chunked [raise-runtime-error 100] ;-- raise a runtime error if unmatched value
			
			list: tail list								;-- point to last case test
			until [										;-- left join all cases in reverse order			
				list: skip list -2
				set [test body] list					;-- retrieve case-test and case-body chunks

				emitter/set-signed-state test/1			;-- properly set signed/unsigned state
				offset: negate emitter/branch/over bodies		;-- insert case exit branching
				emitter/branch/over/on/adjust body/2 test/1/1 offset	;-- insert case test branching
				
				body: emitter/chunks/join test/2 body/2	;-- join case test with case body
				bodies: emitter/chunks/join body bodies	;-- left join case with other cases
				head? list		
			]	
			emitter/merge bodies						;-- commit all to main code buffer
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-switch: has [expr save-type spec value values body bodies list types default pos][
			pc: next pc
			expr: fetch-expression/keep/final			;-- compile argument
			if any [none? expr last-type = none-type][
				throw-error "SWITCH argument has no return value"
			]
			save-type: last-type			
			check-body spec: pc/1
			foreach w [values list types][set w make block! 8]
			forall spec [								;-- resolve possible enumeration symbols
				if all [word? spec/1 spec/1 <> 'default][
					check-enum-symbol spec
				]
			]
			
			;-- check syntax and store parts in different lists
			unless parse spec [
				some [
					pos: copy value some [integer! | char!] 
					(repend values [value none])		;-- [value body-offset ...]
					pos: block! (
						fetch-into pos [				;-- compile action body
							body: comp-block-chunked
							append/only list body/2		
							append/only types resolve-expr-type/quiet body/1
						]
					)
				]
				opt [
					'default pos: block! (
						fetch-into pos [				;-- compile default body
							default: comp-block-chunked
							append/only types resolve-expr-type/quiet default/1
						]
					)
				]
			][
				throw-error ["wrong syntax in SWITCH block at:" copy/part pos 4]
			]

			;-- assemble all actions together, with exit at end for each one
			bodies: emitter/chunks/empty
			list: tail list								;-- point to last action
			until [										;-- left join all actions in reverse order		
				body: first list: back list
				unless empty? bodies/1 [
					emitter/branch/over bodies			;-- insert case exit branching
				]
				bodies: emitter/chunks/join body bodies	;-- left join action with other actions		
				change at values 2 * index? list length? bodies/1
				head? list		
			]
			
			;-- insert default clause or jump to runtime error
			either default [
				emitter/branch/over bodies          	;-- insert default exit branching
				bodies: emitter/chunks/join default/2 bodies ;-- insert default action
			][
				body: comp-chunked [raise-runtime-error 101] ;-- raise a runtime error if unmatched value
				bodies: emitter/chunks/join body bodies
			]

			;-- construct tests + branching and insert them at head
			last-type: save-type
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			values: tail values
			until [
				values: skip values -2
				foreach v values/1 [					;-- process multiple values per action
					body: comp-chunked [
						emitter/target/emit-integer-operation '= reduce [<last> v]
					]
					emitter/branch/over/on/adjust bodies [=] values/2	;-- insert action branching			
					bodies: emitter/chunks/join body bodies
				]
				head? values
			]
			emitter/merge bodies						;-- commit all to main code buffer	
			
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-until: has [expr chunk][
			pc: next pc
			check-body pc/1
			set [expr chunk] comp-block-chunked/test 'until
			emitter/branch/back/on chunk expr/1	
			emitter/merge chunk	
			last-type: none-type
			<last>
		]
		
		comp-while: has [expr unused cond body offset bodies][
			pc: next pc
			check-body pc/1								;-- check condition block
			check-body pc/2								;-- check body block
			
			set [expr cond]   comp-block-chunked/test 'while	;-- Condition block
			set [unused body] comp-block-chunked		;-- Body block
			
			if logic? expr/1 [expr: [<>]]				;-- re-encode test op
			offset: emitter/branch/over body			;-- Jump to condition
			bodies: emitter/chunks/join body cond
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/back/on/adjust bodies reduce [expr/1] offset ;-- Test condition, exit if FALSE
			emitter/merge bodies
			last-type: none-type
			<last>
		]
		
		comp-expression-list: func [/_all /local list offset bodies op][
			pc: next pc
			check-body pc/1								;-- check body block
			
			list: make block! 8
			pc: fetch-into pc/1 [
				while [not tail? pc][					;-- comp all expressions in chunks
					append/only list comp-block-chunked/only/test pick [all any] to logic! _all
				]
			]
			list: back tail list
			set [offset bodies] emitter/chunks/make-boolean			;-- emit ending FALSE/TRUE block
			if _all [emitter/branch/over/adjust bodies offset/1]	;-- conclude by a branch on TRUE
			offset: pick offset not _all				;-- branch to TRUE or FALSE 
			
			until [										;-- left join all expr in reverse order			
				op: either logic? list/1/1/1 [first [<>]][list/1/1/1]
				unless _all [op: reduce [op]]			;-- do not invert the test if ANY
				emitter/set-signed-state list/1/1		;-- properly set signed/unsigned state
				emitter/branch/over/on/adjust bodies op offset		;-- first emit branch				
				bodies: emitter/chunks/join list/1/2 bodies			;-- then left join expr
				also head? list	list: back list
			]	
			emitter/merge bodies
			last-type: [logic!]
			<last>
		]
		
		comp-assignment: has [name value n enum ns][
			push-call name: pc/1
			pc: next pc
			if set-word? name [
				n: to word! name
				unless any [locals local-variable? n][store-ns-symbol n]
				
				unless all [
					local-variable? n
					n = 'context						;-- explicitly allow 'context name for local variables
				][
					check-keywords n					;-- forbid keywords redefinition
				]
				if find definitions n [
					backtrack name
					throw-error ["redeclaration of definition" name]
				]
				if all [
					not local-variable? n
					enum: enum-id? n
				][
					backtrack name
					throw-error ["redeclaration of enumerator" name "from" enum]
				]
				if all [
					get-word? pc/1
					find functions to word! pc/1
				][
					throw-error "storing a function! requires a type casting"
				]
				unless local-variable? n [
					if all [ns-path none? locals][add-ns-symbol pc/-1]
					if all [ns: resolve-ns n ns <> n][name: to set-word! ns]
					check-func-name/only to word! name	;-- avoid clashing with an existing function name		
				]
			]
			if set-path? name [
				unless any [name/1 = 'system local-variable? name/1][
					name: resolve-ns-path name
				]
				if all [series? name value: system-reflexion? name][name: value]
			]
			
			either none? value: fetch-expression [		;-- explicitly test for none!
				none
			][
				new-line/all reduce [name value] no
			]
		]
		
		comp-func-args: func [name [word!] entry [hash!] /local attribute fetch expr args n pos][
			push-call name
			pc: next pc							;-- it's a function
			either attribute: check-variable-arity? entry/2/4 [
				fetch: [
					pos: pc
					expr: fetch-expression
					either attribute = 'typed [
						if all [expr = <last> none? last-type/1][
							pc: pos
							throw-error "expression has no defined return type"
						]
						append args id: get-type-id expr
						append/only args expr
						append args pick [#_ 0] id = emitter/datatype-ID/float! ;-- 32-bit padding
					][
						append/only args expr
					]
				]
				args: make block! 1
				either block? pc/1 [
					fetch-into pc/1 [until [do fetch tail? pc]]
					pc: next pc					;-- jump over arguments block
				][
					do fetch
				]
				reduce [name to-issue attribute args]
			][									;-- fixed arity case
				args: make block! n: entry/2/1
				loop n [append/only args fetch-expression]	;-- fetch n arguments
				new-line/all head insert/only args name no
			]
		]
		
		resolve-ns-path: func [path [path! set-path!] /local new pos][
			new: resolve-ns/path path/1					;-- try to prefix path/1

			either find/only ns-list to path! new [		;-- check if (prefixed) path/1 is a namespace
				new: to path! new
				until [									;-- collect all ns prefixes from head
					path: next path
					append new path/1					;-- move each path value to new one
					not find/only ns-list new			;-- while the new path is still a namespace
				]
				new: ns-decorate new					;-- prefix and convert to word 
				unless tail? next path [				;-- if non-ns remains in path
					new: append to path! new next path	;-- convert back to path by adding non-ns remain 
				]
				if set-path? path [
					new: to either word? new [set-word!][set-path!] new
				]
				new
			][
				unless word? new [path/1: ns-decorate new]	;-- only prefix+convert path/1 if required
				path
			]
		]
		
		comp-path: has [path value ns type name][
			path: pc/1
			if #":" = first mold path/1 [
				throw-error "get-path! syntax is not supported"
			]
			either all [
				not local-variable? path/1
				path: resolve-ns-path path
				word? path
			][
				if value: get-enumerator path [
					last-type: [integer!]
					pc: next pc
					return value
				]
				comp-word/with path
			][
				case [
					value: system-reflexion? path [
						either path/2 = 'words [
							return comp-word/with/root value ;-- re-route to global word resolution
						][
							pc: next pc
						]
					]
					'function! = first type: resolve-path-type/short path [
						name: to word! form path
						check-specs name type/2
						clear-docstrings type/2
						add-function 'routine reduce [name none type/2] get-cconv type/2
						append last functions reduce [path 'local]
						return comp-func-args name skip tail functions -2
					]
					'else [
						comp-word/path path/1				;-- check if root word is defined
						last-type: resolve-path-type path
					]
				]
				any [value path]
			]
		]
		
		comp-get-word: has [spec name ns symbol][
			name: resolve-ns to word! pc/1
			comp-word/with/check name
			
			if all [
				spec: find functions name
				spec: spec/2
			][
				unless find [native routine] spec/2 [
					throw-error "get-word syntax only reserved for native functions for now"
				]
				if all [
					symbol: last expr-call-stack
					spec: find functions symbol
					spec/2/2 = 'import					;-- only flag it when passed to external calls
					spec/2/5 <> 'callback
				][
					append spec/2 'callback				;@@ force cdecl ????
				]
			]
			also to get-word! name pc: next pc
		]
		
		direct-match-ns: func [ctx [path!] name [word!] path /local ns][
			if all [
				any [
					all [ns-stack find/only ns-stack ctx]
					all [ns-path find/only ns-path ctx]
				]
				ns: find/only ns-list ctx
				find ns/2 name
			][
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join ctx name
			]
		]
		
		match-ns: func [name [word!] ctx [word! path!] path /local pos][
			either pos: find ns-stack either path? ctx [ctx/1][ctx][ ;-- match (1st) context with stack
				if path? ctx [							;-- context hierarchy to match with stack
					foreach level ctx [					;-- match each context with next one on stack
						if pos/1 <> level [return none]	;-- if doesn't match, prefix doesn't apply
						pos: next pos					;-- next stack entry
					]
				]
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join to path! ctx name	;-- prefix and convert back to word
			][
				none									;-- no match on stack
			]
		]
		
		resolve-ns: func [name [word!] /path /local ctx pos][
			unless ns-stack [return name]				;-- no current ns, pass-thru

			if ctx: find/skip sym-ctx-table name 2 [	;-- fetch context candidates
				ctx: ctx/2								;-- SELECT/SKIP on hash! unreliable!
				either block? ctx [						;-- more than one candidate
					all [								;-- try direct matching first
						pos: find/only ctx to path! load mold ns-stack	;-- safer to-path conversion
						return either path [
							ns-join to path! first pos name
						][
							ns-decorate ns-join first pos name
						]
					]
					ctx: tail ctx						;-- start from last defined context
					until [
						ctx: back ctx
						if value: any [
							match-ns name ctx/1 path 
							direct-match-ns ctx/1 name path
						][
							return value				;-- prefix name if context on stack
						]
						head? ctx
					]									;-- no match found, pass-thru
				][										;-- one parent context only
					name: any [
						match-ns name ctx path		 	;-- prefix name if context is on stack
						direct-match-ns ctx name path
						name
					]
				]
			]
			name
		]
	
		comp-word: func [
			/path symbol [word!]
			/with word [word!]
			/root										;-- system/words/* pass-thru
			/check										;-- check word validity, do not consume input
			/local entry name local? spec type
		][
			name: pc/1
			if name = shift-right-sym [name: '-**]		;-- replace '>>> words produced by Red layer

			name: any [
				word
				symbol
				all [local-variable? name name]			;-- pass-thru for locals
				all [not root resolve-ns name]
				name
			]
			local?: local-variable? name
			case [
				all [
					not all [local? name = 'context]
					entry: select keywords name			;-- it's a reserved word
				][
					if find calling-keywords name [push-call pc/1]
					unless check [do entry]
				]
				any [
					all [
						local?
						any [
							all [						;-- block local function pointers
								block? type: select locals name
								'function! <> type/1
							]
							not block? type				;-- pass-thru
						]
					]
					all [
						find globals name
						'function! <> first get-type name	;-- block function pointers
					]
				][										;-- it's a variable
					if not-initialized? name [
						throw-error ["local variable" name "used before being initialized!"]
					]
					last-type: resolve-type name
					unless check [also name pc: next pc]
				]
				type: enum-type? name [
					last-type: type
					if verbose >= 3 [print ["ENUMERATOR" name "=" last-type]]
					unless check [also name pc: next pc]
				]
				all [
					not path
					entry: find-functions name
				][
					spec: entry/2/4
					if all [
						find-attribute spec 'infix
						path? pc/1
					][
						throw-error "infix functions cannot be called using a path"
					]
					unless check [comp-func-args name entry]
				]
				'else [throw-error ["undefined symbol:" mold name]]
			]
		]
		
		cast-null: func [variable [set-word! set-path!] /local casting][
			unless all [
				attempt [
					casting: get-type any [
						all [set-word? variable	to word! variable]
						to path! variable
					]
				]
				any-pointer? casting
			][
				backtrack variable
				throw-error "Invalid null assignment"
			]			
			casting
		]
		
		order-args: func [name [word!] args [block!]][
			if any [
				all [
					find [import native infix routine] functions/:name/2
					find [stdcall cdecl] functions/:name/3
				]
				all [
					functions/:name/2 = 'syscall
					job/syscall = 'BSD
				]
				all [
					functions/:name/2 = 'syscall		
					job/target = 'ARM					;-- odd, but required for Linux/ARM syscalls
					job/syscall = 'Linux
				]
			][		
				reverse args
			]
		]
		
		external-call?: func [spec [block!] /local attribs][
			to logic! any [
				spec/5 = 'callback
				all [
					attribs: get-attributes spec/4
					any [find attribs 'cdecl find attribs 'stdcall]
				]
			]
		]

		comp-call: func [
			name [word!] args [block!] /sub
			/local list type res align? left right dup var-arity? saved? arg expr spec
		][
			name: decorate-fun name
			list: either issue? args/1 [				;-- bypass type-checking for variable arity calls
				args/2
			][
				check-arguments-type name args
				args
			]
			order-args name list						;-- reorder argument according to cconv

			spec: functions/:name
			align?: all [
				args/1 <> #custom
				any [
					spec/2 = 'import					;@@ syscalls don't seem to need special alignment??
					all [spec/2 = 'routine external-call? spec]
				]
			]
			if align? [emitter/target/emit-stack-align-prolog args]
			
			if args/1 <> #custom [
				type: functions/:name/2
				either type <> 'op [
					forall list [						;-- push function's arguments on stack
						expr: list/1
						if block? unbox expr [comp-expression expr yes]	;-- nested call
						if object? expr [cast expr]
						if type <> 'inline [
							emitter/target/emit-argument expr functions/:name ;-- let target define how arguments are passed
						]
					]
				][										;-- nested calls as op argument require special handling
					if block? unbox list/1 [comp-expression list/1 yes]	;-- nested call
					left:  unbox list/1
					right: unbox list/2
					if saved?: all [block? left any [block? right path? right]][
						emitter/target/emit-save-last	;-- optionally save left argument result
					]
					if block? unbox list/2 [comp-expression list/2 yes]	;-- nested call
					if saved? [emitter/target/emit-restore-last]
				]
			]
			res: emitter/target/emit-call name args to logic! sub

			either res [
				last-type: res
			][
				set-last-type functions/:name/4			;-- catch nested calls return type
			]
			if align? [emitter/target/emit-stack-align-epilog args]
			res
		]
				
		comp-path-assign: func [
			set-path [set-path!] expr casted [block! none!]
			/local type new value
		][
			value: unbox expr
			if find [block! path! tag!] type?/word value [
				emitter/target/emit-move-path-alt		;-- save assigned value
			]
			if all [
				not local-variable? set-path/1
				enum-id? set-path/1
			][
				backtrack set-path
				throw-error ["enumeration cannot be used as path root:" set-path/1]
			]
			unless get-variable-spec set-path/1 [
				backtrack set-path
				throw-error ["unknown path root variable:" set-path/1]
			]
			type: resolve-path-type set-path			;-- check path validity
			new: resolve-aliased get-type expr		

			if type <> any [casted new][
				backtrack set-path
				throw-error [
					"type mismatch on setting path:" to path! set-path
					"^/*** expected:" mold type
					"^/*** found:" mold any [casted new]
				]
			]		
			emitter/access-path set-path either any [block? value path? value][
				 <last>
			][
				expr
			]
		]
		
		comp-variable-assign: func [
			set-word [set-word!] expr casted [block! none!]
			/local name type new value fun-name
		][
			name: to word! set-word		
			if find aliased-types name [
				backtrack set-word
				throw-error "name already used for as an alias definition"
			]
			if not-initialized? name [
				init-local name expr casted				;-- mark as initialized and infer type if required
			]

			if all [
				casted
				casted/1 = 'function!
				local-variable? name
			][
				fun-name: decorate-function name
				add-function 'routine reduce [fun-name none casted/2] get-cconv casted/2
				append last functions reduce [name 'local]
			]
			
			either type: any [
				get-variable-spec name					;-- test if known variable (local or global)	
				enum-id? name
			][
				type: resolve-aliased type
				value: get-type expr
				if block? expr [parse value [type-spec]] ;-- prefix return type if required	
				new: resolve-aliased value
				
				if type <> any [casted new][
					backtrack set-word
					throw-error [
						"attempt to change type of variable:" name
						"^/*** from:" mold type
						"^/***   to:" mold any [casted new]
					]
				]
			][
				unless zero? block-level [
					backtrack set-word
					throw-error "variable not declared"
				]
				if any [
					all [casted casted/1 = 'function!]
					all [expr = <last> casted: last-type last-type/1 = 'function!]
				][
					add-function 'routine reduce [name none casted/2] get-cconv casted/2
				]
				type: add-symbol name unbox expr casted  ;-- if unknown add it to global context	
			]
			if none? type/1 [
				backtrack set-word
				throw-error ["unable to determine a type for:" name]
			]
			value: unbox expr
			if any [block? value path? value][value: <last>]
			emitter/store name value type
		]
		
		comp-expression: func [expr keep? [logic!] /local variable boxed casting new? type][
			;-- preprocessing expression
			if all [block? expr find [set-word! set-path!] type?/word expr/1][
				variable: expr/1
				expr: expr/2							;-- switch to assigned expression
				if set-word? variable [
					new?: not exists-variable? variable
				]
			]			
			if object? expr [							;-- unbox type-casting object
				if all [variable expr/action = 'null][
					casting: cast-null variable
				]
				boxed: expr
				expr: either any-float? boxed/type [cast/quiet expr][cast expr]
			]
			
			;-- dead expressions elimination
			if all [
				not keep?
				not any [tail? pc variable]				;-- not last expression nor assignment value
				1 >= length? expr-call-stack			;-- one (for math op) or no parent call
				'switch <> pick tail expr-call-stack -1
				any [
					all [
						any [
							word? expr 					;-- variable alone
							literal? expr				;-- literal, but not logic value
						]
						'logic! <> first get-type expr
					]
					all [
						block? expr
						functions/(decorate-fun expr/1)/2 = 'op	;-- math expression
						any [							;-- no return value, or return value type <> logic!
							not type: find functions/(expr/1)/4 return-def
							type/2/1 <> 'logic!
						]
					]
				]
			][exit]

			;-- emitting expression code
			either block? expr [
				type: comp-call expr/1 next expr 		;-- function call case (recursive)
				if type [last-type: type]				;-- set last-type if not already set
				if all [
					variable boxed						;-- process casting if result assigned to variable
					last-type/1 = 'logic!
					boxed/type  = 'integer!				;-- fixes #967
				][
					emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
					last-type: boxed/type
				]
			][
				last-type: either not any [
					all [new? literal? unbox expr]		;-- if new variable, value will be store in data segment
					all [set-path? variable not path? expr]	;-- value loaded at lower level
					tag? unbox expr
				][
					emitter/target/emit-load either boxed [boxed][expr]	;-- emit code for single value
					either all [boxed not decimal? unbox expr][
						emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
						boxed/type
					][
						resolve-expr-type expr
					]
				][
					resolve-expr-type expr
				]
			]
			
			;-- postprocessing result
			if all [
				any [
					keep?
					variable							;-- result needs to be stored
					all [
						'case = pick tail expr-call-stack -3
						#test <> pick tail expr-call-stack -2
						4 <= length? expr-call-stack
					]
				]
				block? expr								;-- and if expr is a function call		
				last-type/1 = 'logic!					;-- which return type is logic!
			][
				emitter/logic-to-integer expr/1			;-- runtime logic! conversion before storing
			]
			
			if all [									;-- clean FPU stack when required
				not any [keep? variable]
				block? expr
				word? expr/1
				any-float? get-return-type/check expr/1
				any [
					not find functions/(expr/1)/4 return-def	;-- clean if no return value
					1 = length? expr-call-stack					;-- or if return value not used
				]
			][
				emitter/target/emit-float-trash-last	;-- avoid leaving a x86 FPU slot occupied,
			]											;-- if return value is not used.
			
			;-- storing result if assignement required
			if variable [
				if all [boxed not casting][
					casting: resolve-aliased boxed/type
				]
				unless boxed [boxed: expr]
				switch type?/word variable [
					set-word! [comp-variable-assign variable expr casting]
					set-path! [comp-path-assign		variable boxed casting]
				]
			]
		]
		
		check-enum-symbol: func [code [any-block!] /local value][
			if all [									;-- if enum, replace it with its integer value
				word? code/1
				not local-variable? code/1
				value: get-enumerator resolve-ns code/1
			][
				change code value
			]
		]
		
		infix?: func [pos [block! paren!] /local specs][
			all [
				not tail? pos
				word? pos/1
				specs: find functions resolve-ns pos/1
				specs: specs/2
				find [op infix] specs/2
			]
		]
		
		check-infix-operators: has [pos][
			if infix? pc [
				either infix? back tail expr-call-stack [
					exit								;-- infix op already processed
				][
					throw-error "invalid use of infix operator"
				]
			]
			if infix? next pc [
				either find [set-word! set-path! struct!] type?/word pc/1 [
					throw-error "can't use infix operator here"
				][
					pos: 0								;-- relative index of next infix op
					until [								;-- search for all dependent infix op
						pos: pos + 2					;-- target next infix possible position
						insert pc pc/:pos				;-- transform to prefix notation
						remove at pc pos + 1
						not infix? at pc pos + 2		;-- exit when no more infix op found
					]
				]
			]
		]
		
		fetch-expression: func [/final /keep /local expr pass value][
			check-infix-operators
			
			if verbose >= 4 [print ["<<<" mold pc/1]]
			pass: [also pc/1 pc: next pc]
			
			if tail? pc [
				pc: back pc
				throw-error "missing argument"
			]
			if job/debug? [store-dbg-lines]
			
			check-enum-symbol pc

			expr: switch/default type?/word pc/1 [
				set-word!	[comp-assignment]
				word!		[comp-word]
				get-word!	[comp-get-word]
				path! 		[comp-path]
				set-path!	[comp-assignment]
				paren!		[comp-block/only]
				char!		[do pass]
				integer!	[do pass]
				string!		[do pass]
				decimal!	[do pass]
				block!		[also to paren! pc/1 pc: next pc]
				issue!		[comp-directive]
			][
				throw-error "datatype not allowed"
			]
			expr: reduce-logic-tests expr

			if final [
				if verbose >= 3 [?? expr]
				unless find [none! tag!] type?/word expr [
					comp-expression expr to logic! keep
				]
			]
			expr
		]
		
		comp-block: func [/final /only /local expr save-pc][
			block-level: block-level + 1
			save-pc: pc
			pc: pc/1

			either only [
				expr: either final [fetch-expression/final][fetch-expression]
				unless tail? pc [
					throw-error "more than one expression found in parentheses"
				]
			][
				while [not tail? pc][
					;if all [paren? pc/1 not infix? at pc 2][raise-paren-error]
					expr: either final [fetch-expression/final][fetch-expression]
					unless tail? pc [pop-calls]
				]
			]
			pc: next save-pc
			
			block-level: block-level - 1
			expr
		]
		
		comp-dialect: has [expr][
			block-level: 0
			while [not tail? pc][
				case [
					issue? pc/1 [comp-directive]
					all [
						set-word? pc/1
						find [func function] pc/2
					][
						pc: next pc
						fetch-func pc/-1				;-- allow function declaration at root level only
					]
					all [set-word? pc/1 pc/2 = 'alias][
						pc: next pc
						comp-alias						;-- allow alias declaration at root level only
					]
					paren? pc/1 [
						;unless infix? at pc 2 [raise-paren-error]
						expr: fetch-expression/final/keep
					]
					'else [expr: fetch-expression/final/keep]
				]
				pop-calls
				emitter/target/on-root-level-entry
			]
			expr
		]
		
		comp-func-body: func [
			name [word!] spec [block!] body [block!]
			/local args-sz local-sz expr ret
		][
			locals: spec
			func-name: name
			set [args-sz local-sz] emitter/enter name locals ;-- build function prolog
			pc: body
			
			expr: comp-dialect							;-- compile function's body
			
			if ret: select spec return-def [
				check-expected-type/ret name expr ret	;-- validate return value type
				if all [
					object? expr 
					find [block! tag!] type?/word expr/data
				][
					emitter/target/emit-casting expr no	;-- insert runtime type casting when required
					last-type: expr/type
				]
			]
			emitter/leave name locals args-sz local-sz	;-- build function epilog
			remove-func-pointers
			clear locals-init
			locals: func-name: none
		]
		
		comp-natives: does [			
			foreach [name spec body origin ns nss] natives [
				if verbose >= 2 [
					print [
						"---------------------------------------^/"
						"function:" name newline
						"---------------------------------------"
					]
				]
				script: origin
				ns-path: ns
				ns-stack: nss
				comp-func-body name spec body
			]
		]
		
		comp-header: has [pos][
			unless pc/1 = 'Red/System [
				throw-error "source is not a Red/System program"
			]
			pc: next pc
			unless block? pc/1 [
				throw-error "missing Red/System program header"
			]
			unless parse pc/1 [any [pos: set-word! skip]][
				throw-error ["invalid program header at:" mold pos]
			]
			pc: next pc
		]
		
		get-proto: func [name [word!]][
			switch/default job/OS [
				Windows [
					[handle [integer!]]
				]
				MacOSX [
					pick [
						[
							argc	[integer!]
							argv	[struct! [s [c-string!]]]
							envp	[struct! [s [c-string!]]]
							apple	[struct! [s [c-string!]]]
							pvars	[program-vars!]
						]
						[[cdecl]]
					] name = 'on-load
				]
			][											;-- Linux
				[[cdecl]]
			]
		]
		
		add-dll-callbacks: has [list code exp][			;-- add missing callbacks
			list: copy [on-load on-unload]
			if job/OS = 'Windows [
				append list [on-new-thread on-exit-thread]
			]
			code: make block! 1
			exp:  make block! 1
			
			foreach fun list [
				unless find/skip natives fun 6 [
					repend code [
						to set-word! fun 'func get-proto fun []	;-- stdcall
					]
				]
			]
			unless empty? code [
				pc: code
				comp-dialect
			]
		]

		run: func [obj [object!] src [block!] file [file!] /no-header /runtime /no-events][
			runtime: to logic! runtime
			job: obj
			pc: src
			script: secure-clean-path file
			unless no-header [comp-header]
			unless no-events [emitter/target/on-global-prolog runtime job/type]
			comp-dialect
			unless no-events [
				case [
					runtime [
						emitter/target/on-global-epilog yes	job/type ;-- postpone epilog event after comp-runtime-epilog
					]
					not job/runtime? [
						emitter/target/on-global-epilog no job/type
					]
				]
			]
		]
		
		finalize: does [
			if verbose >= 2 [print "^/---^/Compiling native functions^/---"]
			if job/type = 'dll [
				if empty? exports [
					throw-error "missing #export directive for library production"
				]
				add-dll-callbacks 						;-- make sure they are defined
			]
			comp-natives
			emitter/target/on-finalize
			if verbose >= 2 [print ""]
			emitter/reloc-native-calls
		]
	]
	
	set-verbose-level: func [level [integer!]][
		foreach ctx reduce [
			self
			loader
			compiler
			emitter
			emitter/target
			linker
		][
			ctx/verbose: level
		]
	]
	
	output-logs: does [
		case/all [
			verbose >= 1 [
				print [
					nl
					"-- compiler/globals --" nl mold new-line/all/skip to-block compiler/globals yes 2 nl
					"-- emitter/symbols --"  nl mold new-line/all/skip to-block emitter/symbols yes 2 nl
				]
			]
			verbose >= 2 [
				print [
					"-- compiler/functions --" nl mold new-line/all/skip to-block compiler/functions yes 2 nl
				]
			]
			verbose >= 6 [
				print [
					"-- emitter/code-buf --" nl mold emitter/code-buf nl
					"-- emitter/data-buf --" nl mold emitter/data-buf nl
					"as-string:"        	 nl mold as-string emitter/data-buf nl
				]
			]
		]
	]
	
	emit-main-prolog: has [name spec][
		either job/type = 'exe [
			emitter/target/on-init
		][												;-- wrap global code in a function
			name: '***-main
			compiler/add-function 'native reduce [name none []] 'stdcall
			spec: emitter/add-native name
			spec/2: 1
			emitter/target/emit-prolog name [] 0
		]
	]

	comp-start: has [script][
		emitter/libc-init?: yes
		emitter/start-prolog
		script:	either encap? [
			set-cache-base %system/runtime/
			%start.reds
		][
			secure-clean-path runtime-path/start.reds
		]
 		compiler/run/no-events job loader/process/own script script
 		emitter/start-epilog
 
		;-- selective clean-up of compiler's internals
 		remove/part find compiler/globals 'system 2		;-- avoid 'system redefinition clash
 		remove/part find emitter/symbols 'system 4
		clear compiler/definitions
		clear compiler/aliased-types
		emitter/libc-init?: no
	]
	
	comp-runtime-prolog: func [red? [logic!] /local script][
		script: either encap? [
			set-cache-base %system/runtime/
			%common.reds
		][
			secure-clean-path runtime-path/common.reds
		]
 		compiler/run/runtime job loader/process/own script script
 		
 		if red? [
 			unless empty? red/sys-global [
				set-cache-base %./
				compiler/run job loader/process red/sys-global %***sys-global.reds
 			]
 			set-cache-base %runtime/
 			script: pick [%red.reds %../runtime/red.reds] encap?
 			compiler/run job loader/process/own script script
 		]
 		set-cache-base none
	]
	
	comp-runtime-epilog: does [
		either job/need-main? [
			emitter/target/on-global-epilog no job/type	;-- emit main() epilog
		][
			switch job/type [
				exe [compiler/comp-call '***-on-quit [0 0]]	;-- call runtime exit handler
				dll [emitter/target/emit-epilog '***-main [] 0 0]
				drv [emitter/target/emit-epilog '***-main [] 0 0]
			]
		]
	]
	
	clean-up: does [
		compiler/ns-path: 
		compiler/ns-stack: 
		compiler/locals: none
		compiler/resolve-alias?:  yes
		
		clear compiler/imports
		clear compiler/exports
		clear compiler/natives
		clear compiler/ns-list
		clear compiler/sym-ctx-table
		clear compiler/globals
		clear compiler/definitions
		clear compiler/enumerations
		clear compiler/aliased-types
		clear compiler/user-functions
		clear compiler/debug-lines/records
		clear compiler/debug-lines/files
		clear emitter/symbols
	]
	
	make-job: func [opts [object!] file [file!] /local job][
		job: construct/with third opts linker/job-class	
		file: last split-path file					;-- remove path
		file: to-file first parse file "."			;-- remove extension
		case [
			none? job/build-basename [
				job/build-basename: file
			]
			slash = last job/build-basename [
				append job/build-basename file
			]
		]
		job
	]
	
	set 'dt func [code [block!] /local t0][
		t0: now/time/precise
		do code
		now/time/precise - t0
	]
	
	compile: func [
		files [file! block!]							;-- source file or block of source files
		/options
			opts [object!]
		/loaded 										;-- source code is already in LOADed format
			src	[block!]
		/local
			comp-time link-time err output
	][
		comp-time: dt [
			unless block? files [files: reduce [files]]
			
			unless opts [opts: make options-class []]
			job: make-job opts last files				;-- last input filename is retained for output name
			emitter/init opts/link? job
			if opts/verbosity >= 10 [set-verbose-level opts/verbosity]
			
			clean-up
			loader/init
			emit-main-prolog
			
			job/need-main?: to logic! any [
				job/need-main?							;-- pass-thru if set in config file
				all [
					job/type = 'exe
					not find [Windows MacOSX] job/OS
				]
			]
			
			if all [
				job/need-main?
				not opts/use-natives?
				opts/runtime?
			][
				comp-start								;-- init libC properly
			]
			
			if opts/runtime? [comp-runtime-prolog to logic! loaded]
			
			set-verbose-level opts/verbosity
			foreach file files [
				src: either loaded [
					loader/process/with src file
				][
					loader/process file
				]
				compiler/run job src file
			]
			set-verbose-level 0
			if opts/runtime? [comp-runtime-epilog]
			
			set-verbose-level opts/verbosity
			compiler/finalize							;-- compile all functions
			set-verbose-level 0
		]
		if verbose >= 5 [
			print [
				"-- emitter/code-buf (empty addresses):"
				nl mold emitter/code-buf nl
			]
		]

		if opts/link? [
			link-time: dt [
				job/symbols: emitter/symbols
				job/sections: compose/deep/only [
					code   [- 	(emitter/code-buf)]
					data   [- 	(emitter/data-buf)]
					import [- - (compiler/imports)]
				]
				if not empty? compiler/exports [
					append job/sections compose/deep/only [
						export [- - (compiler/exports)]
					]
				]
				if opts/debug? [
					job/debug-info: reduce ['lines compiler/debug-lines]
				]
				output: linker/build job
			]
		]
		
		set-verbose-level opts/verbosity
		output-logs
		if opts/link? [clean-up]

		reduce [
			comp-time
			link-time
			any [all [job/buffer length? job/buffer] 0]
			output
		]
	]
]
#!/usr/bin/Rscript

library(lme4)
library(coefplot2)
library(glmmADMB)
library(Hmisc)
library(ggplot2)

load('flows-checkpoint3.RData')

## Refit with glmmadmb due to warnings about gradients above tolerance with lme4 fits

modNames <- c('glmeundirhmax', 'glmedirhmax', 'glmehmax')
fFin <- f[modNames]

tmpf <- function(x) {
    test <- !is.na(om$cases1WksAgo)
    data <- om[test, ]
    glmmadmb(x, data=data, family='nbinom')
}
mFin <- lapply(fFin, tmpf)
save.image('flows-checkpoint4.RData')

## Plot of predicted cases vs flow

scales <- c(week=iqr(om$weekCent),
            internal=iqr(log(om$internalFlow)),
            cmedDense=iqr(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=iqr(log(om$undirectedFlow)),
            directeted=iqr(log(om$directedFlow)))
sink(file='scales.txt')
print(scales)
sink()

centers <- c(week=mean(om$weekCent),
            internal=mean(log(om$internalFlow)),
            cmedDense=mean(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=mean(log(om$undirectedFlow)),
            directeted=mean(log(om$directedFlow)))

fund <- fortify(m$glmeundirhmax, data=model.frame(m$glmeundirhmax))
stopifnot(all.equal(attributes(fund$logUndirectedFlowScaled)[["scaled:center"]], centers[['undirected']]))
stopifnot(all.equal(attributes(fund$logUndirectedFlowScaled)[["scaled:scale"]][["75%"]], scales[['undirected.75%']]))

theme_set(new=theme_classic())
fund$log10UndirectedFlow <- log10(exp(scales['undirected.75%'] * as.numeric(fund$logUndirectedFlowScaled) + centers['undirected']))
fund$predCases <- exp(fund$.fitted)
fund$smoothpred <- predict(loess(predCases~log10UndirectedFlow, data=fund, span=.5))
fund$casesJittered <- runif(fund$cases, min=-1, max=1)*0.2 + fund$cases

g <- ggplot(data=fund, aes(x=log10UndirectedFlow, y=casesJittered))
g <- g + geom_point(col='red', alpha=.5)
g <- g + geom_line(aes(y=smoothpred))
g <- g + labs(x='Log10(transport flow)', y='Cases')
g <- g + coord_trans(y="log1p")

ggsave('flows-prediction.eps', width=4, height=4, pointsize=18, device=cairo_ps)
ggsave('flows-prediction.pdf', width=4, height=4, pointsize=18, device=cairo_pdf)

## Plots of fixed effects

ct <- lapply(mFin, function(x) coeftab(x)[, 1:2])

extractEsts <- function(pattern, type) {
  tmpf <- function(x) grep(pattern, rownames(x))
  inds <- lapply(ct, tmpf)
  res <- list()
  mapply(function(x, y) x[y, type], ct, inds)
}
  
patterns <- list(flow='Flow', dense='logCmedDenseScaled', week='weekCent', inf='Inf')
ests <- sapply(patterns, extractEsts, type='Estimate')
sds <- sapply(patterns, extractEsts, type='Std. Error')
weekIqr <- iqr(model.frame(m$glmedirhmax)$weekCent)
ests[, 'week'] <- ests[, 'week']*weekIqr
sds[, 'week'] <- sds[, 'week']*weekIqr

stopifnot(rownames(ests) == c('glmeundirhmax', 'glmedirhmax', 'glmehmax'))
ests <- cbind(ests, baseline=c(hund$maximum, hdir$maximum, hint$maximum))
sds <- cbind(sds, baseline=0)

tmpf <- function() {
    longnames <- c(flow='Scaled transport flow', inf='Cases last week', week='Scaled week', dense='Scaled farm density', baseline='Baseline risk') 
    pal <- c('black', 'orange', 'blue')
    pch <- 15:17
    for(i in seq_len(nrow(ests))){
        coefplot2(ests[i, ], sds[i, ], varnames=longnames[colnames(ests)],
                  offset=(i-1)/10, col=pal[i], add=i>1, pch=pch[i],
                  main="Regression estimates")
    }
    legend('topright', legend=c('undirected', 'directed', 'none'), col=pal, pch=pch, title='Interstate flow')
}

pdf('coefplot.pdf', width=5,height=4)
tmpf()
dev.off()
## This works better than making the ps with R for some reason
system('pdftops coefplot.pdf')

res <- 100
png('coefplot.png', width=5*res, height=4*res, res=res)
tmpf()
dev.off()


## Table of likelihoods, dispersion, parameters, random effects

getNBTheta <- function(x) {
    if(inherits(x, 'glmmadmb')) {
        summary(x)$alpha
    } else {
        as.numeric(strsplit(family(x)$family, split='\\(|\\)')[[1]][2])
    }
}
getLL <- function(x) as.numeric(logLik(x))
getSD <- function(x) as.numeric(sqrt(VarCorr(x)$stateF))
getdf <- function(x) attr(logLik(x), 'df')
getintercept <- function(x) fixef(x)['(Intercept)']

modList <- c(mFin, m[c('nbme', 'nbmeN')])
disp <- sapply(modList, getNBTheta)
llik <- sapply(modList, getLL)
resd <- sapply(modList, getSD)
df <- sapply(modList, getdf)
int <- sapply(modList, getintercept)

tmpf <- function() {
  tab <- data.frame(baseline=I('no'), int=unname(int), disp, resd, df, llik)
  rownames(tab) <- names(modList)
  tab[c('glmeundirhmax', 'glmedirhmax', 'glmehmax'), 'baseline'] <- 'yes'
  tab[, 'df'] <- tab[, 'df'] + ifelse(tab[, 'baseline'] == 'yes', 1, 0)
  aic <- 2*-tab[, 'llik'] + 2*tab[, 'df']
  tab <- cbind(tab, deltaAIC = aic - min(aic))
  flowTerm <- c(glmeundirhmax='undirected', glmedirhmax='directed', glmehmax='internal',
                nbme='internal', nbmeN='none')
  tab <- data.frame(flowTerm=flowTerm[rownames(tab)], tab)
  tf <- format.df(tab)
  align <- paste(attr(tf, "col.just"), collapse="|")
  align <- paste('|', align, '|', sep='')
  longnames <- c(flowTerm='\\bf Flow term', baseline='\\bf Fit $\\eta$',
                 disp='\\bf Intercept', df='\\bf d.f.', llik='\\bf Log lik.',
                 deltaAIC='\\bf $\\Delta$ AIC', resd='\\bf $\\hat{\\sigma}$',
                 int='{\\bf Intercept}')
  colnames(tab) <- longnames[colnames(tf)]
  tab <- latexTabular(tab, helvetica=FALSE, align=align, translate=FALSE,
                   cdec=c(0,0,1,2,2,0,1,1))
  tab <- gsub('\\\\multicolumn\\{1\\}\\{c\\}', '', tab)
  tab <- gsub('(\\\\)\\s?(\n)', '\\1\\\\hline\\2', tab)
  tab <- gsub('(\\n)(\\{\\\\bf Flow term\\})', '\\1\\\\hline\\2', tab)
  cat(tab, file='tab.tex')
  list(aic=aic, tab=tab)
}
tables <- tmpf()

## Dotplot of AICs

tmpf <- function() {
    tab <- tables$tab
    aic <- tables$aic
    flowTerm <- c(glmeundirhmax='Within-state + undirected between state',
                  glmedirhmax='Within-state + directed between state',
                  glmehmax='Within-state only',
                  nbme='Within-state only, fixed other risks ',
                  nbmeN='No flow, fixed other risks')
    labels <- flowTerm[rownames(tab)]
    dotchart2(tables$aic, labels=labels, xlab='AIC (i.e., Estimated information loss)', dotsize=2)
}
png('aic.png', width=7*res, height=4*res, res=res)
tmpf()
dev.off()

save.image('flows-checkpoint5.RData')

                                             
#!/usr/bin/Rscript

library(lme4)
library(coefplot2)
library(glmmADMB)
library(Hmisc)
library(ggplot2)

load('flows-checkpoint3.RData')

## Refit with glmmadmb due to warnings about gradients above tolerance with lme4 fits

modNames <- c('glmeundirhmax', 'glmedirhmax', 'glmehmax')
fFin <- f[modNames]

tmpf <- function(x) {
    test <- !is.na(om$cases1WksAgo)
    data <- om[test, ]
    glmmadmb(x, data=data, family='nbinom')
}
mFin <- lapply(fFin, tmpf)
save.image('flows-checkpoint4.RData')

## Plot of predicted cases vs flow

scales <- c(week=iqr(om$weekCent),
            internal=iqr(log(om$internalFlow)),
            cmedDense=iqr(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=iqr(log(om$undirectedFlow)),
            directeted=iqr(log(om$directedFlow)))
sink(file='scales.txt')
print(scales)
sink()

centers <- c(week=mean(om$weekCent),
            internal=mean(log(om$internalFlow)),
            cmedDense=mean(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=mean(log(om$undirectedFlow)),
            directeted=mean(log(om$directedFlow)))

stopifnot(all.equal(attributes(fund$logUndirectedFlowScaled)[["scaled:center"]], centers[['undirected']]))
stopifnot(all.equal(attributes(fund$logUndirectedFlowScaled)[["scaled:scale"]][["75%"]], scales[['undirected.75%']]))

fund <- fortify(m$glmeundirhmax, data=model.frame(m$glmeundirhmax))
theme_set(new=theme_classic())
fund$flow <- exp(scales['undirected.75%'] * as.numeric(fund$logUndirectedFlowScaled) + centers['undirected'])
fund$predCases <- exp(fund$.fitted)
fund$smoothpred <- predict(loess(predCases~flow, data=fund))

g <- ggplot(data=fund, aes(x=flow, y=predCases))
g <- g + geom_line(aes(y=smoothpred))
g <- g + geom_point(aes(x=I(flow + runif(flow, min=-5e5, max=5e5)), y=cases), col='red', alpha=0.5)
g <- g + labs(x='Flow (swine / year)', y='Cases')
g <- g + coord_trans(y="log1p") + ylim(0,100)
ggsave('flows-prediction.eps', width=4, height=4, pointsize=18, device=cairo_ps)
ggsave('flows-prediction.pdf', width=4, height=4, pointsize=18, device=cairo_pdf)

## Plots of fixed effects

ct <- lapply(mFin, function(x) coeftab(x)[, 1:2])

extractEsts <- function(pattern, type) {
  tmpf <- function(x) grep(pattern, rownames(x))
  inds <- lapply(ct, tmpf)
  res <- list()
  mapply(function(x, y) x[y, type], ct, inds)
}
  
patterns <- list(flow='Flow', dense='logCmedDenseScaled', week='weekCent', inf='Inf')
ests <- sapply(patterns, extractEsts, type='Estimate')
sds <- sapply(patterns, extractEsts, type='Std. Error')
weekIqr <- iqr(model.frame(m$glmedirhmax)$weekCent)
ests[, 'week'] <- ests[, 'week']*weekIqr
sds[, 'week'] <- sds[, 'week']*weekIqr

stopifnot(rownames(ests) == c('glmeundirhmax', 'glmedirhmax', 'glmehmax'))
ests <- cbind(ests, baseline=c(hund$maximum, hdir$maximum, hint$maximum))
sds <- cbind(sds, baseline=0)

tmpf <- function() {
    longnames <- c(flow='Scaled transport flow', inf='Cases last week', week='Scaled week', dense='Scaled farm density', baseline='Baseline risk') 
    pal <- c('black', 'orange', 'blue')
    pch <- 15:17
    for(i in seq_len(nrow(ests))){
        coefplot2(ests[i, ], sds[i, ], varnames=longnames[colnames(ests)],
                  offset=(i-1)/10, col=pal[i], add=i>1, pch=pch[i],
                  main="Regression estimates")
    }
    legend('topright', legend=c('undirected', 'directed', 'none'), col=pal, pch=pch, title='Interstate flow')
}

pdf('coefplot.pdf', width=5,height=4)
tmpf()
dev.off()
## This works better than making the ps with R for some reason
system('pdftops coefplot.pdf')

res <- 100
png('coefplot.png', width=5*res, height=4*res, res=res)
tmpf()
dev.off()


## Table of likelihoods, dispersion, parameters, random effects

getNBTheta <- function(x) {
    if(inherits(x, 'glmmadmb')) {
        summary(x)$alpha
    } else {
        as.numeric(strsplit(family(x)$family, split='\\(|\\)')[[1]][2])
    }
}
getLL <- function(x) as.numeric(logLik(x))
getSD <- function(x) as.numeric(sqrt(VarCorr(x)$stateF))
getdf <- function(x) attr(logLik(x), 'df')
getintercept <- function(x) fixef(x)['(Intercept)']

modList <- c(mFin, m[c('nbme', 'nbmeN')])
disp <- sapply(modList, getNBTheta)
llik <- sapply(modList, getLL)
resd <- sapply(modList, getSD)
df <- sapply(modList, getdf)
int <- sapply(modList, getintercept)

tmpf <- function() {
  tab <- data.frame(baseline=I('no'), int=unname(int), disp, resd, df, llik)
  rownames(tab) <- names(modList)
  tab[c('glmeundirhmax', 'glmedirhmax', 'glmehmax'), 'baseline'] <- 'yes'
  tab[, 'df'] <- tab[, 'df'] + ifelse(tab[, 'baseline'] == 'yes', 1, 0)
  aic <- 2*-tab[, 'llik'] + 2*tab[, 'df']
  tab <- cbind(tab, deltaAIC = aic - min(aic))
  flowTerm <- c(glmeundirhmax='undirected', glmedirhmax='directed', glmehmax='internal',
                nbme='internal', nbmeN='none')
  tab <- data.frame(flowTerm=flowTerm[rownames(tab)], tab)
  tf <- format.df(tab)
  align <- paste(attr(tf, "col.just"), collapse="|")
  align <- paste('|', align, '|', sep='')
  longnames <- c(flowTerm='\\bf Flow term', baseline='\\bf Fit $\\eta$',
                 disp='\\bf Intercept', df='\\bf d.f.', llik='\\bf Log lik.',
                 deltaAIC='\\bf $\\Delta$ AIC', resd='\\bf $\\hat{\\sigma}$',
                 int='{\\bf Intercept}')
  colnames(tab) <- longnames[colnames(tf)]
  tab <- latexTabular(tab, helvetica=FALSE, align=align, translate=FALSE,
                   cdec=c(0,0,1,2,2,0,1,1))
  tab <- gsub('\\\\multicolumn\\{1\\}\\{c\\}', '', tab)
  tab <- gsub('(\\\\)\\s?(\n)', '\\1\\\\hline\\2', tab)
  tab <- gsub('(\\n)(\\{\\\\bf Flow term\\})', '\\1\\\\hline\\2', tab)
  cat(tab, file='tab.tex')
  list(aic=aic, tab=tab)
}
tables <- tmpf()

## Dotplot of AICs

tmpf <- function() {
    tab <- tables$tab
    aic <- tables$aic
    flowTerm <- c(glmeundirhmax='Within-state + undirected between state',
                  glmedirhmax='Within-state + directed between state',
                  glmehmax='Within-state only',
                  nbme='Within-state only, fixed other risks ',
                  nbmeN='No flow, fixed other risks')
    labels <- flowTerm[rownames(tab)]
    dotchart2(tables$aic, labels=labels, xlab='AIC (i.e., Estimated information loss)', dotsize=2)
}
png('aic.png', width=7*res, height=4*res, res=res)
tmpf()
dev.off()

save.image('flows-checkpoint5.RData')

                                             
library = function (...) suppressMessages(base::library(..., quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(6,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL)
                                   ),
                            column(6,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map')
                                                    )

                                   )
                            ),

                          uiOutput('mapOrSetUI'),
                          conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                           jscolorInput('aesValueColor')),

                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          textInput('plotTitle', 'Plot Title'),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    strong('Font Color'), br(),
                                                    jscolorInput('textColor'), br(),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    strong('Border Color'), br(),
                                                    jscolorInput('rectColor'), br(),
                                                    strong('Fill'), br(),
                                                    jscolorInput('rectFill'), br(),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    strong('Line Color'), br(),
                                                    jscolorInput('lineColor'), br(),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   )

                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(6,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL)
                                   ),
                            column(6,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map')
                                                    )

                                   )
                            ),

                          uiOutput('mapOrSetUI'),
                          conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                           jscolorInput('aesValueColor')),

                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          textInput('plotTitle', 'Plot Title'),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem')
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    strong('Font Color'), br(),
                                                    jscolorInput('textColor'), br(),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    strong('Border Color'), br(),
                                                    jscolorInput('rectColor'), br(),
                                                    strong('Fill'), br(),
                                                    jscolorInput('rectFill'), br(),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    strong('Line Color'), br(),
                                                    jscolorInput('lineColor'), br(),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   )

                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)
library(magrittr)
library(hexbin)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# spatial analysis see if county assignment went right
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.05), maptype='toner-lite') +
  guides(colour = guide_legend(override.aes = list(alpha=1)))

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 1700, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))


# tiemline
# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  theme(axis.text.x = element_text(angle=45, hjust=1))

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  coord_flip()

# smoothing
smooth <- function(y, x) {
  as.numeric(predict(gam(y ~ s(x), na.action = na.exclude)))
}

bigsum <- plyr::ddply(bigsum, plyr::.(city), transform,
                price_s = smooth(price, as.numeric(date)))
ggplot(bigsum, aes(date, price_s /1e6, group=city)) +
  geom_line()

index <- function(y, x) {
  y / y[order(x)[1]]
}
bigsum <- plyr::ddply(bigsum, plyr::.(city), transform,
                price_si = index(price_s, date))
ggplot(bigsum, aes(date, price_si /1e6, group=city, color=city)) +
  geom_line()

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city)

# get the peak and last price
covar <- arrange(bigsum, city, date) %>%
  group_by(city) %>%
  summarise(
    peak = max(price_si),
    plummet = last(price_si)
  )

ggplot(covar, aes(peak, plummet)) +
  geom_point()
ggplot(covar, aes(peak, plummet)) +
  geom_point() +
  geom_text(aes(label=city), size=4, hjust=-0.05)

covar %<>% transform(delta=plummet - peak)

census <- read.csv('data/census-city.csv')
covar %<>% inner_join(census)

plot_base <- ggplot(covar, aes(y=delta)) + geom_point()
plot_base + aes(grads)
plot_base + aes(income)
plot_base + aes(housesold_size)library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)
library(magrittr)
library(hexbin)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# spatial analysis see if county assignment went right
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.05), maptype='toner-lite') +
  guides(colour = guide_legend(override.aes = list(alpha=1)))

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 1700, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))


# tiemline
# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  theme(axis.text.x = element_text(angle=45, hjust=1))

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  coord_flip()

# smoothing
smooth <- function(y, x) {
  as.numeric(predict(gam(y ~ s(x), na.action = na.exclude)))
}

bigsum <- plyr::ddply(bigsum, plyr::.(city), transform,
                price_s = smooth(price, as.numeric(date)))
ggplot(bigsum, aes(date, price_s /1e6, group=city)) +
  geom_line()

index <- function(y, x) {
  y / y[order(x)[1]]
}
bigsum <- plyr::ddply(bigsum, plyr::.(city), transform,
                price_si = index(price_s, date))
ggplot(bigsum, aes(date, price_si /1e6, group=city, color=city)) +
  geom_line()

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city)

# get the peak and last price
covar <- arrange(bigsum, city, date) %>%
  group_by(city) %>%
  summarise(
    peak = max(price_si),
    plummet = last(price_si)
  )

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city)

ggplot(covar, aes(peak, plummet)) +
  geom_point()library = function (...) suppressMessages(base::library(..., quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data) {
    data = melt(data, id.vars = 'Gene', variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_fill_manual(values = celltype_colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
REBOL [
	Title:   "Red Lexical Scanner"
	Author:  "Nenad Rakocevic"
	File: 	 %lexer.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

lexer: context [
	verbose: 0
	
	line: 	none									;-- source code lines counter
	lines:	[]										;-- offsets of newlines marker in current block
	count?: yes										;-- if TRUE, lines counter is enabled
	cnt:	none									;-- counts nested {} in multi-line strings
	pos:	none									;-- source input position (error reporting)
	s:		none									;-- mark start position of new value
	e:		none									;-- mark end position of new value
	value:	none									;-- new value
	fail?:	none									;-- used for failing some parsing rules
	type:	none									;-- define the type of the new value
	rs?:	no 										;-- if TRUE, do lexing for Red/System
	neg?:	no										;-- if TRUE, denotes a negative number value
	
	;====== Parsing rules ======

	four:  charset "01234"
	half:  charset "012345"
    non-zero: charset "123456789"
    digit: union non-zero charset "0"
    dot: #"."
    comma: #","

	byte: [
		"25" half
		| "2" four digit
		| "1" digit digit
		| non-zero digit
		| digit
	]

	hexa:  union digit charset "ABCDEF"
	hexa-char: union hexa charset "abcdef"
	
	;-- UTF-8 encoding rules from: http://tools.ietf.org/html/rfc3629#section-4
	UTF-8-BOM: #{EFBBBF}
	ws-ASCII:  charset " ^-^M"						;-- ASCII common whitespaces
	ws-U+2k:   charset [#"^(80)" - #"^(8A)"]		;-- Unicode spaces in the U+2000-U+200A range
	UTF8-tail: charset [#"^(80)" - #"^(BF)"]
	UTF8-1:    charset [#"^(00)" - #"^(7F)"]
	
	UTF8-2: reduce [
		charset [#"^(C2)" - #"^(DF)"]
		UTF8-tail
	]
	
	UTF8-3: reduce [
		#{E0} 	 charset [#"^(A0)" - #"^(BF)"] UTF8-tail
		'| 		 charset [#"^(E1)" - #"^(EC)"] 2 UTF8-tail
		'| #{ED} charset [#"^(80)" - #"^(9F)"] UTF8-tail
		'| 		 charset [#"^(EE)" - #"^(EF)"] 2 UTF8-tail
	]
	
	UTF8-4: reduce [
		#{F0} 	 charset [#"^(90)" - #"^(BF)"] 2 UTF8-tail
		'| 		 charset [#"^(F1)" - #"^(F3)"] 3 UTF8-tail
		'| #{F4} charset [#"^(80)" - #"^(8F)"] 2 UTF8-tail
	]
	
	UTF8-char: [pos: UTF8-1 | UTF8-2 | UTF8-3 | UTF8-4]
	
	not-word-char:  charset {/\^^,[](){}"#%$@:;}
	not-word-1st:	union union not-word-char digit charset {'}
	not-file-char:  charset {[](){}"@:;}
	not-url-char:	charset {[](){}";}
	not-str-char:   #"^""
	not-mstr-char:  #"}"
	caret-char:	    charset [#"^(40)" - #"^(5F)"]
	non-printable-char: charset [#"^(00)" - #"^(1F)"]
	integer-end:	charset {^{"[]);}
	stop: 		    none

	control-char: reduce [
		charset [#"^(00)" - #"^(1F)"] 				;-- ASCII control characters
		'| #"^(C2)" charset [#"^(80)" - #"^(9F)"] 	;-- C2 control characters
	]
	
	UTF8-filtered-char: [
		[pos: stop :pos (fail?: [end skip]) | UTF8-char e: (fail?: none)]
		fail?
	]
	
	UTF8-printable: [
		[non-printable-char | not-str-char (fail?: [end skip]) | UTF8-char (fail?: none)]
		fail?
	]
	
	;-- Whitespaces list from: http://en.wikipedia.org/wiki/Whitespace_character
	ws: [
		pos: #"^/" (
			if count? [
				line: line + 1 
				append/only lines to block! stack/tail?
			]
		)
		| ws-ASCII									;-- only the common whitespaces are matched
		| #{C2} [
			#{85}									;-- U+0085 (Newline)
			| #{A0}									;-- U+00A0 (No-break space)
		]
		| #{E1} [
			#{9A80}									;-- U+1680 (Ogham space mark)
			| #{A08E}								;-- U+180E (Mongolian vowel separator)
		]
		| #{E2} [
			#{80} [
				ws-U+2k								;-- U+2000-U+200A range
				| #{A8}								;-- U+2028 (Line separator)
				| #{A9}								;-- U+2029 (Paragraph separator)
				| #{AF}								;-- U+202F (Narrow no-break space)
			]
			| #{819F}								;-- U+205F (Medium mathematical space)
		]
		| #{E38080}									;-- U+3000 (Ideographic space)
	]
	
	newline-char: [
		#"^/"
		| #{C285}									;-- U+0085 (Newline)
		| #{E280} [
			#{A8}									;-- U+2028 (Line separator)
			| #{A9}									;-- U+2029 (Paragraph separator)
		]
	]
	
	counted-newline: [pos: #"^/" (line: line + 1)]
	
	ws-no-count: [(count?: no) ws (count?: yes)]
	
	any-ws: [pos: any ws]
	
	symbol-rule: [
		(stop: [not-word-char | ws-no-count | control-char])
		some UTF8-filtered-char e:
	]
	
	begin-symbol-rule: [							;-- 1st char in symbols is restricted
		(stop: [not-word-1st | ws-no-count | control-char])
		UTF8-filtered-char
		opt symbol-rule
	]
	
	path-rule: [
		pos: slash :pos (							;-- path detection barrier
			stack/push path!
			stack/push to type copy/part s e		;-- push 1st path element
		)
		some [
			slash
			s: [
				integer-number-rule
				| begin-symbol-rule			(type: word!)
				| paren-rule 				(type: paren!)
				| #":" s: begin-symbol-rule	(type: get-word!)
				;@@ add more datatypes here
			] (
				stack/push either type = paren! [	;-- append path element
					value
				][
					to type copy/part s e
				]
				type: path!
			)
			opt [#":" (type: set-path!)]
		]
		(value: stack/pop type)
	]
	
	word-rule: 	[
		(type: word!)
		#"%" ws-no-count (value: "%")				;-- special case for remainder op!
		| s: begin-symbol-rule [
			url-rule
			| path-rule 							;-- path matched
			| (value: copy/part s e)				;-- word matched
			  opt [#":" (type: set-word!)]
		] 
	]
	
	get-word-rule: [
		#":" (type: get-word!) s: begin-symbol-rule [
			path-rule (
				value/1: to get-word! value/1		;-- workaround missing get-path! in R2
			)
			| (
				type: get-word!
				value: copy/part s e				;-- word matched
			)
		]
	]
	
	lit-word-rule: [
		#"'" (type: word!) s: begin-symbol-rule [
			path-rule (type: lit-path!)				;-- path matched
			| (
				type: lit-word!
				value: copy/part s e				;-- word matched
			)
		]
	]
	
	issue-rule: [#"#" (type: issue!) s: symbol-rule]
	
	refinement-rule: [slash (type: refinement!) s: symbol-rule]
	
	slash-rule: [s: [slash opt slash] e:]
	
	hexa-rule: [2 8 hexa e: #"h" (type: integer!)]

	sticky-word-rule: [
		pos: [										;-- protection rule from typo with sticky words
			[integer-end | ws-no-count | end] (fail?: none)
			| skip (fail?: [end skip])
		] :pos
		fail?
	]

	tuple-value-rule: [
		(type: tuple!)
		byte dot byte 1 8 [dot byte | dot] e:
	]

	tuple-rule: [
		tuple-value-rule
		sticky-word-rule
	]
		
	integer-number-rule: [
		(type: integer!)
		opt [#"-" | #"+"] digit any [digit | #"'" digit] e:
	]
	
	integer-rule: [
		decimal-special									;-- escape path for NaN, INFs
		| integer-number-rule
		  opt [decimal-number-rule | decimal-exp-rule e: (type: decimal!)]
		  sticky-word-rule
	]

	decimal-special: [
		s: "-0.0" e: (type: issue!) |
			(neg?: no) opt [#"-" (neg?: yes)] "1.#" s: [
				[[#"N" | #"n"] [#"a" | #"A"] [#"N" | #"n"]]
				| [[#"I" | #"i"] [#"N" | #"n"] [#"F" | #"f"]]
		] e: (type: issue!)
	]
	
	decimal-exp-rule: [
		[[#"e" | #"E"] opt [#"-" | #"+"] 1 3 digit]
	]
	
	decimal-number-rule: [
		[dot | comma] digit any [digit | #"'" digit]
		opt decimal-exp-rule e: (type: decimal!)
	]

	decimal-rule: [
		decimal-number-rule
		sticky-word-rule
	]
		
	block-rule: [#"[" (stack/push block!) any-value #"]" (value: stack/pop block!)]
	
	paren-rule: [#"(" (stack/push paren!) any-value	#")" (value: stack/pop paren!)]
	
	escaped-char: [
		"^^(" [
			[										;-- special case first
				"null" 	 (value: #"^(00)")
				| "back" (value: #"^(08)")
				| "tab"  (value: #"^(09)")
				| "line" (value: #"^(0A)")
				| "page" (value: #"^(0C)")
				| "esc"  (value: #"^(1B)")
				| "del"	 (value: #"^(7F)")
			]
			| pos: [2 6 hexa-char] e: (				;-- Unicode values allowed up to 10FFFFh
					either rs? [
						value: to-char to-integer debase/base copy/part pos e 16
					][value: encode-UTF8-char pos e]
			)
		] #")"
		| #"^^" [
			[
				#"/" 	(value: #"^/")
				| #"-"	(value: #"^-")
				| #"?" 	(value: #"^(del)")
				| #"^^" (value: #"^^")				;-- caret escaping case
				| #"{"	(value: #"{")
				| #"}"	(value: #"}")
				| #"^""	(value: #"^"")
			]
			| pos: caret-char (value: pos/1 - 64)
		]
	]
	
	char-rule: [
		{#"} (type: char!) [
			s: escaped-char
			| copy value UTF8-printable (value: as-binary value)
			| #"^-" (value: s/1)
		] {"}
	]
	
	line-string: [
		{"} s: (type: string! stop: [not-str-char | newline-char])
		any [{^^"} | escaped-char | UTF8-filtered-char]
		e: {"}
	]
	
	nested-curly-braces: [
		(cnt: 1 fail?: none)
		any [
			[
				counted-newline 
				| "^^{" | "^^}"
				| #"{" (cnt: cnt + 1)
				| e: #"}" (if zero? cnt: cnt - 1 [fail?: [end skip]])
				| UTF8-char
			] fail?
		]
		#"}"
	]
	
	multiline-string: [#"{" s: (type: string!) nested-curly-braces]
	
	string-rule: [line-string | multiline-string]
	
	binary-rule: [
		"#{" (type: binary!) 
		s: any [counted-newline | 2 hexa-char | ws-no-count | comment-rule]
		e: #"}"
	]
	
	file-rule: [
		#"%" (type: file! stop: [not-file-char | ws-no-count])
		s: any UTF8-filtered-char e:
	]

	url-rule: [
		#":" (type: url! stop: [not-url-char | ws-no-count])
		some UTF8-filtered-char e: (value: dehex copy/part s e)
	]

	escaped-rule: [
		"#[" any-ws [
			  "true"  (value: true)
			| "false" (value: false)
			| s: [
				"none!" | "logic!" | "block!" | "integer!" | "word!" 
				| "set-word!" | "get-word!" | "lit-word!" | "refinement!"
				| "binary!" | "string!"	| "char!" | "bitset!" | "path!"
				| "set-path!" | "lit-path!" | "native!"	| "action!"
				| "issue!" | "paren!" | "function!"
			] e: (value: get to word! copy/part s e)
			| "none" (value: none)
		]  any-ws #"]"
	]
	
	comment-rule: [#";" [to #"^/" | to end]]
	
	wrong-delimiters: [
		pos: [
			  #"]" (value: #"[") | #")" (value: #"(")
			| #"[" (value: #"]") | #"(" (value: #")")
		] :pos
		(throw-error/with ["missing matching" value])
	]

	literal-value: [
		pos: (e: none) s: [
			comment-rule
			| escaped-rule    (stack/push value)
			| integer-rule	  (stack/push load-number    copy/part s e)
			| decimal-rule	  (stack/push load-decimal	 copy/part s e)
			| tuple-rule	  (stack/push to tuple!		 copy/part s e)
			| hexa-rule		  (stack/push decode-hexa	 copy/part s e)
			| word-rule		  (stack/push to type value)
			| lit-word-rule	  (stack/push to type value)
			| get-word-rule	  (stack/push to type value)
			| refinement-rule (stack/push to refinement! copy/part s e)
			| slash-rule	  (stack/push to word! 	   	 copy/part s e)
			| issue-rule	  (stack/push to issue!	   	 copy/part s e)
			| file-rule		  (stack/push load-file		 copy/part s e)
			| char-rule		  (stack/push decode-UTF8-char value)
			| block-rule	  (stack/push value)
			| paren-rule	  (stack/push value)
			| string-rule	  (stack/push load-string s e)
			| binary-rule	  (stack/push load-binary s e)
		]
	]
	
	any-value: [pos: any [literal-value | ws]]

	header: [
		pos: thru "Red" opt ["/System" (rs?: yes stack/push 'Red/System)]
		any-ws block-rule (stack/push value)
		| (throw-error/with "Invalid Red program") end skip
	]

	program: [
		pos: opt UTF-8-BOM
		header
		any-value
		opt wrong-delimiters
	]
	
	;====== Helper functions ======
	
	stack: context [
		stk: []
		
		push: func [value][
			either any [value = block! value = paren! value = path!][
				if value = path! [value: block!]
				insert/only tail stk value: make value 1
				value
			][
				insert/only tail last stk :value
			]
		]
		
		pop: func [type [datatype!]][
			if any [type = path! type = set-path!][type: block!]
			
			if type <> type? last stk [
				throw-error/with ["invalid" mold type "closing delimiter"]
			]
			also last stk remove back tail stk
		]
		
		tail?: does [tail last stk]
		reset: does [clear stk]
	]
	
	throw-error: func [/with msg [string! block!]][
		print rejoin [
			"*** Syntax Error: " either with [
				uppercase/part reform msg 1
			][
				reform ["Invalid" mold type "value"]
			]
			"^/*** line: " line
			"^/*** at: " mold copy/part pos 40
		]
		either encap? [quit][halt]
	]

	add-line-markers: func [blk [block!]][	
		foreach pos lines [new-line pos yes]
		clear lines
	]
	
	pad-head: func [s [string!]][
		head insert/dup s #"0" 8 - length? s
	]
	
	encode-UTF8-char: func [s [string!] e [string!] /local c code new][
		c: debase/base pad-head copy/part s e 16
		while [c/1 = 0][c: next c]					;-- trim heading zeros
		code: to integer! c
		
		case [
			code <= 127  [
				new: to char! code					;-- c <= 7Fh
			]
			code <= 2047 [							;-- c <= 07FFh
				new: (shift/left (shift code 6) or #"^(C0)" 8)
						or (code and #"^(3F)") or #"^(80)"
			]
			code <= 65535 [							;-- c <= FFFFh
				new: (shift/left (shift code 12) or #"^(E0)" 16)
						or (shift/left (shift code 6) and #"^(3F)" or #"^(80)" 8)
						or (code and #"^(3F)") or #"^(80)"
			]
			code <= 1114111 [						;-- c <= 10FFFFh
				new: (shift/left (shift code 18) or #"^(F0)" 24)
						or (shift/left (shift code 12) and #"^(3F)" or #"^(80)" 16)
						or (shift/left (shift code 6)  and #"^(3F)" or #"^(80)" 8)
						or (code and #"^(3F)") or #"^(80)"
			]
			'else [
				throw-error/with "Codepoints above U+10FFFF are not supported"
			]
		]
		if integer? new [
			new: debase/base to-hex new 16
			remove-each byte new [byte = #"^(null)"]
		]	
		new
	]
	
	decode-UTF8-char: func [value][
		if char? value [return encode-char to integer! value]
		
		value: switch/default length? value [
			1 [value]
			2 [
				value: value and #{1F3F}
				value: add shift/left value/1 6 value/2
			]
			3 [
				value: value and #{0F3F3F}
				value: add add
					shift/left value/1 12
					shift/left value/2 6
					value/3
			]
			4 [
				value: value and #{073F3F3F}
				value: add add add
					shift/left value/1 18
					shift/left value/2 12
					shift/left value/3 6
					value/4
			]
		][
			throw-error/with "Unsupported or invalid UTF-8 encoding"
		]	
		
		encode-char to integer! value				;-- special encoding for Unicode char!
	]
	
	decode-UTF8-string: func [str [string!] /local new s e][
		new: make string! length? str
		parse/all str [
			some [
				s: UTF8-char e: (
					append new debase/base skip decode-UTF8-char as-binary copy/part s e 7 16
				)
			]
		]
		head change/part str new tail str
	]
	
	encode-char: func [value [integer!]][
		head insert to-hex value #"'"
	]
	
	decode-hexa: func [s [string!]][
		to integer! debase/base s 16
	]

	load-number: func [s [string!]][
		switch/default type [
			#[datatype! decimal!][s: load-decimal s]
			#[datatype! issue!  ][
				if s = "-0.0" [s: "0-"]					;-- reencoded for consistency
				s: to issue! join "." s
				if neg? [append s #"-"]
			]
		][
			unless integer? s: to integer! s [throw-error]
		]
		s
	]

	load-decimal: func [s [string!]][
		unless attempt [s: to decimal! s][throw-error]
		s
	]

	load-string: func [s [string!] e [string!] /local new filter][
		new: make string! offset? s e				;-- allocated size close to final size
		filter: get pick [UTF8-char UTF8-filtered-char] s/-1 = #"{"

		parse/all/case copy/part s e [
			any [
				escaped-char   (insert tail new value)
				| s: filter e: (insert/part tail new s e)
			]										;-- exit on matching " or }
		]
		new
	]
	
	load-binary: func [s [string!] e [string!] /local new byte][
		new: make binary! (offset? s e) / 2			;-- allocated size above final size

		parse/all/case s [
			some [
				copy byte 2 hexa-char (insert tail new debase/base byte 16)
				| ws | comment-rule
				| #"}" end skip
			]
		]
		new
	]

	load-file: func [s [string!]][
		to file! dehex s
	]
	
	process: func [src [string! binary!] /local blk][
		line: 1
		count?: yes
		
		blk: stack/push block!						;-- root block

		unless parse/all/case src program [throw-error]
		
		add-line-markers blk
		stack/reset
		blk
	]
]# Command line tools don’t want to clutter their output with unnecessary noise.
library = function (...)
    suppressMessages(base::library(...))

#' The command line arguments
args = commandArgs(trailingOnly = TRUE)

#' The name of the script
#'
#' @note If the script was invoked interactively, this is the empty string.
script_name = local({
    file = grep('^--file=', commandArgs(trailingOnly = FALSE), value = TRUE)
    sub('--file=', '', file)
})

#' Quit the program
#'
#' @param code numeric exit code (default: \code{0})
exit = function (code = 0)
    quit(save = 'no', status = if (is.null(code)) 0 else code)

#' Execute the \code{entry_point} function defined by the caller
#'
#' Execute an entry point function, but only if the calling code is executed as
#' a stand-alone script, not when it is imported as a module.
#'
#' @param entry_point code or function to run (default: \code{main})
#' @return This function is called for its side-effect. If the calling code was
#' imported as a module, then return nothing. Otherwise, this function
#' \emph{does not return}; instead, it quits the script.
#'
#' @details The argument may either be a function (the default is assumed to be
#' a function called \code{main} in the calling code’s scope) or a
#' brace-enclosed expression. It is executed in the calling code’s scope.
#'
#' @examples
#' \dontrun{
#' main = function () { … }
#' # Run function `main`
#' sys$run()
#'
#' # Run the specified function
#' sys$run(function () { … })
#'
#' # Run the specified code
#' sys$run({ … })
#' }
run = function (entry_point = main) {
    caller = parent.frame()
    caller_name = evalq(modules::module_name(), envir = caller)

    if (is.null(caller_name)) {
        if (class(substitute(entry_point)) == '{')
            exit(entry_point)

        exit(eval(substitute(main(), list(main = entry_point)), envir = caller))
    }
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' @export
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' Principle coordinate analysis of phylogenies
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' @export
#' @examples
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}# Command line tools don’t want to clutter their output with unnecessary noise.
library = function (...)
    suppressMessages(base::library(...))

#' The command line arguments
args = commandArgs(trailingOnly = TRUE)

#' The name of the script
script_name = local({
    file = grep('^--file=', commandArgs(trailingOnly = FALSE), value = TRUE)
    sub('--file=', '', file)
})

#' Quit the program
#'
#' @param code numeric exit code (default: \code{0})
exit = function (code = 0)
    quit(save = 'no', status = if (is.null(code)) 0 else code)

#' Execute the \code{entry_point} function defined by the caller
#'
#' Execute an entry point function, but only if the calling code is executed as
#' a stand-alone script, not when it is imported as a module.
#'
#' @param entry_point code or function to run (default: \code{main})
#' @return This function is called for its side-effect. If the calling code was
#' imported as a module, then return nothing. Otherwise, this function
#' \emph{does not return}; instead, it quits the script.
#'
#' @details The argument may either be a function (the default is assumed to be
#' a function called \code{main} in the calling code’s scope) or a
#' brace-enclosed expression. It is executed in the calling code’s scope.
#'
#' @examples
#' \dontrun{
#' main = function () { … }
#' # Run function `main`
#' sys$run()
#'
#' # Run the specified function
#' sys$run(function () { … })
#'
#' # Run the specified code
#' sys$run({ … })
#' }
run = function (entry_point = main) {
    caller = parent.frame()
    caller_name = evalq(modules::module_name(), envir = caller)

    if (is.null(caller_name)) {
        if (class(substitute(entry_point)) == '{')
            exit(entry_point)

        exit(eval(substitute(main(), list(main = entry_point)), envir = caller))
    }
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' @examples
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' Prepare the data
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)?
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = do.call(expand.grid, lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)?
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)?
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) { #TODO: name columns in layout df properly (formals if no names)
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(regs=reg, n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) # merge layout+results list
        Qget(regs=reg, fail.on.error=fail.on.error)[[1]]
    else
        layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
#' @param regs        list of registries to include; default: all local
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T, regs=Qregs()) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param regs            list of registries to include; default: all local
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, regs=Qregs(), fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    retrieve = function(job, res) setNames(res, job)
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=retrieve)
    else
        result = reduceResultsList(reg, fun=retrieve)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param grid.sep        separator to use when assembling names from expand.grid
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @param set.names       try to name result or keep numbers? (default: \code{fail.on.error})
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), name=NULL, run=T, get=T,
             memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA,
             expand.grid=F, grid.sep=":", seed=123, fail.on.error=T,
             set.names=fail.on.error) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) {
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    # name every vector so we can identify them afterwards
    ln = lapply(l., names)
    lnFull = lapply(1:length(ln), function(i)
        if (is.character(l.[[i]]) && length(l.[[i]][1])==1 && is.null(ln[[i]]))
            l.[[i]]
        else if (is.null(ln[[i]]))
            1:length(l.[[i]])
        else
            ln[[i]]
    )
 
    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid)
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    else
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))

    if (expand.grid || is.null(unlist(ln)))
        resultNames = apply(expand.grid(lnFull), 1, function(x) paste(x,collapse=grid.sep))
    else
        resultNames = as.matrix(apply(do.call(cbind, ln), 1, unique))
    save(resultNames, name, set.names, file=file.path(tmpdir, "names.RData"))

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(regs=reg, n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    if (get)
        Qget(regs=reg, fail.on.error=fail.on.error)[[1]]
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
#' @param regs        list of registries to include; default: all local
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T, regs=Qregs()) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param regs            list of registries to include; default: all local
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=T, regs=Qregs(), fail.on.error=T) {
    if (class(regs) == 'Registry')
        regs = list(regs)

    getResult = function(reg) {
        waitForJobs(reg, ids=getJobIds(reg))
        print(showStatus(reg, errors=100L))
        if (fail.on.error)
            result = reduceResultsList(reg, ids=getJobIds(reg),
                                       fun=function(job, res) res)
        else
            result = reduceResultsList(reg, fun=function(job, res) res)
        load(file.path(reg$file.dir, 'names.RData')) # resultNames
        if (clean)
            Qclean(reg)
        if (set.names)
            setNames(result, resultNames[as.integer(names(result))])
        else
            result
    }

    setNames(lapply(regs, getResult), names(regs))
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
source("colors.r")

########################################

plotHistogram <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    pdfFilePath <- "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath <- pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=color,
      border=borderColor,
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      lty=1,
      cex=1)
    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotHistogramNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    pdfFilePath <- "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath <- pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    h$counts <- h$counts/sum(h$counts)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=color,
      border=borderColor,
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      freq=FALSE,
      lty=1,
      cex=1)

    x <- seq(min(-10.0, min(dataArray) * 0.5) , max(max(dataArray) * 1.5, 100), length=10000)
    y <- dnorm(x, mean=mean(dataArray), sd=sd(dataArray))

    par(new=TRUE)

    plot(x,y,
         type="l",
         lwd=3,
         axes=FALSE,
         col=thillux_green,
         xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
         ylab='',
         xlab='',
         main=''
    )

    polygon(x, y,
            col=thillux_green,
            border="#4ACAA8",
            ylab='',
            xlab='',
            main=''
    )

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotQQNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(qqnorm(dataArray, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    qqline(sort(dataArray), ylab='',
      xlab='', col=thillux_green, lwd=2)

    par(new=TRUE)

    qq <- qqnorm(sort(dataArray), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotQQ <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(qqplot(dataArray1, dataArray2, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    qq <- qqplot(sort(dataArray1), sort(dataArray2), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotPoints <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    plot(dataArray1, dataArray2,
      type="p",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotSmoothLine <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    plot(smooth.spline(dataArray1, dataArray2),
      type="l",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

plotWithConfidence <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
      pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
      margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
      margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
      margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    xLim <- range(x) + c(-0.1,0.1)
    yLim <- range(c(y+e,y-e)) + c(-0.1,0.1)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    widthToInch = 96.0
    arrowLength = diff(range(xData))/20.0

    rect(xData-arrowLength,y-e,xData+arrowLength,y+e,col=color, border=FALSE)

    arrowTipLength = pmin(e/2.0, arrowLength/3.0)

    segments(xData-arrowLength, y-e, xData-arrowLength, y-e+arrowTipLength, lend=1, col="#E7746F")
    segments(xData-arrowLength, y+e, xData-arrowLength, y+e-arrowTipLength, lend=1, col="#E7746F")
    segments(xData+arrowLength, y-e, xData+arrowLength, y-e+arrowTipLength, lend=1, col="#E7746F")
    segments(xData+arrowLength, y+e, xData+arrowLength, y+e-arrowTipLength, lend=1, col="#E7746F")

    segments(xData-arrowLength, y-e, xData+arrowLength, y-e, lend=1, col="#E7746F")
    segments(xData-arrowLength, y+e, xData+arrowLength, y+e, lend=1, col="#E7746F")

    segments(xData, y-arrowTipLength, xData, y+arrowTipLength, lend=1, col="#E7746F")

    segments(xData-arrowLength/2.0,yData, xData+arrowLength/2.0,yData, col="#E7746F")

    frame <- data.frame(xData,yData)
    frame <- frame[order(xData),]
    lines(frame$xData, frame$yData, col=color,lty=2)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# spatial analysis see if county assignment went right
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.1), maptype='toner-lite')

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 100, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.3))

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))


# tiemline
# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot")#' Prepare the datapoll
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @examples
#' @notes Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}## upsert sheet dynamicProperties
lapply(list(list(inputId='customizeItem', inputType='tabsetPanel'),
            list(inputId='plotTitle', inputType='text'),
            list(inputId='plotXlab', inputType='text'),
            list(inputId='plotYlab', inputType='text')),
       function(x){
         assign(paste0('observer_', x$inputId, '_push'),
                observe({
                  v <- input[[x$inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)){
                      if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][[x$inputId]])){
                        sheetList[[currentSheet]][['dynamicProperties']][[x$inputId]] <<- v
                      }
                    }
                  })
                }),
                sessionEnv)
         assign(paste0('observer_', x$inputId, '_pull'),
                observe({
                  updateInput[[x$inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- if(!isEmpty(currentSheet)){
                    isolate(sheetList[[currentSheet]][['dynamicProperties']][[x$inputId]])
                  } else ''
                  switch(x$inputType,
                         'text'=updateTextInput(session, x$inputId, value=null2String(s)),
                         'tabsetPanel'=updateTabsetPanel(session, x$inputId, selected=null2String(s)))
                }),
                sessionEnv)
       })



###########################
## Text Formatting

lapply(list(list(inputId='textFamily', inputType='select'),
            list(inputId='textFace', inputType='select'),
            list(inputId='textColor', inputType='color'),
            list(inputId='textSize', inputType='numeric'),
            list(inputId='textHjust', inputType='numeric'),
            list(inputId='textVjust', inputType='numeric'),
            list(inputId='textAngle', inputType='numeric'),
            list(inputId='textLineheight', inputType='numeric')),
       function(x){
         assign(paste0('observer_', x$inputId, '_push'),
                observe({
                  v <- input[[x$inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)) {
                      customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
                      if(!isEmpty(customizeItem)){
                        if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
                        }
                        if(x$inputId=='textColor' && !isEmpty(v)) v <- paste0("#", v)
                        if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]])){
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]] <<- v
                        }
                      }
                    }
                  })
                }),
                sessionEnv)
         if(x$inputId=='textColor') return() ## no updateJsColorInput is available yet
         assign(paste0('observer_', x$inputId, '_pull'),
                observe({
                  updateInput[[x$inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- ''
                  if(!isEmpty(currentSheet)){
                    customizeItem <- (sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
                    if(!isEmpty(customizeItem) && !is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]])
                    }
                  }

                  switch(x$inputType,
                         'numeric'=updateNumericInput(session, x$inputId, value=null2String(s)),
                         'select'=updateSelectInput(session, x$inputId, selected=null2String(s)))

                }),
                sessionEnv)
       })


## End of Text Formatting
###########################

install.packages("devtools", dependencies = TRUE)
install.packages("methods", dependencies = TRUE)
install.packages("ggplot2", dependencies = TRUE)
install.packages("knitr", dependencies = TRUE)
install.packages("base64enc", dependencies = TRUE)
library(devtools)
options(unzip = "internal")
install_github('rCharts', 'ramnathv')
install_github("slidify", "ramnathv")
install_github("slidifyLibraries", "ramnathv")
# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            names(dimnames(l.[[i]])) = dimnames[1:length(dim(l.[[i]]))]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=names(l.)[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>% #TODO: use b$match here instead
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = base::match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')


# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot")

# geogrphic analysis
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.1), maptype='toner-lite')

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 100, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.3))

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')


# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot")

# geogrphic analysis
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.1), maptype='toner-lite')

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            names(dimnames(l.[[i]])) = dimnames[1:length(dim(l.[[i]]))]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=names(l.)[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>%
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
library(pcapack)

set.seed(1234)

m <- 10
n <- 50
m <- 50
n <- 10

x <- matrix(rnorm(m*n), m, n)



mdl1 <- prcomp(x)
mdl2 <- pca(x, method="svd")
print(all.equal(mdl1$sdev, mdl2$sdev))
print(all.equal(mdl1$rotation, mdl2$rotation))


mdl1 <- prcomp(x)
mdl2 <- pca(x, method="eigcov")
print(all.equal(mdl1$sdev, mdl2$sdev))
print(all.equal(unclass(mdl1$loadings), mdl2$rotation))
require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

## autosomes,X,Y
## all,autosomes,XY,X

meffil.extract.controls <- function(basename, probes=probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=probe.info()) {
    
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr.type == "chrX"),]
    probes.y <- probes[which(probes$chr.type == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- sapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$G[which(probes.G$target == "BISULFITE CONVERSION I"
                               & probes.G$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ExternalType %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ExternalType %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normA + normT)/(normC + normG)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    model.matrix <- c(bisulfite1=bisulfite1,
                      bisulfite2=bisulfite2,
                      extension.G=extension.G,
                      extension.R=extension.R,
                      hybe=hybe,
                      stain.G=stain.G,
                      stain.R=stain.R,
                      nonpoly.G=nonpoly.G,
                      nonpoly.R=nonpoly.R,
                      targetrem=targetrem,
                      spec1.G=spec1.G,
                      spec1.R=spec1.R,
                      spec2.G=spec2.G,
                      spec2.R=spec2.R,
                      spec1.ratio1=spec1.ratio1,
                      spec1.ratio=spec1.ratio,
                      spec2.ratio=spec2.ratio,
                      spec1.ratio2=spec1.ratio2,
                      normA=normA,
                      normC=normC,
                      normT=normT,
                      normG=normG,
                      dye.bias=dye.bias,
                      oob.G=oob.G,
                      oob.ratio=oob.ratio)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    reference <- which.min(abs(control.matrix["dye.bias",]-1))
    intensity <- mean(control.matrix[c("normA","normT","normC","normG"), reference])
    list(R=intensity/mean(control.matrix[c("normA", "normT"),sample.idx]),
         G=intensity/mean(control.matrix[c("normC", "normG"),sample.idx]))
}


probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=probe.info()) {
    cbind(expand.grid(target=names(mu),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=names(mu),
                      chr="chrX",
                      type3=NA,
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=names(mu),
                      chr=NA,
                      type3=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(probes$target == quantile.sets$target[i]
                          & probes$type3 == quantile.sets$type3[i]
                          & probes$chr == quantile.sets$chr[i]
                          & probes$chr.type == quantile.sets$chr.type[i])]
    })
}

apply.quantile.normalization <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & quantile.sets$chr.type %in% "autosomal"
     | mixture & sex == "M" & quantile.sets$chr.type %in% "sex"
     | mixture & sex == "F" & quantile.sets$chr %in% "chrX"
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     | !mixture & sex == "F" & quantile.sets$chr.type %in% "autosomal"
     | !mixture & sex == "F" & object$quantile.sets$chr %in% "chrX")
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     #&& length(rg$R) == length(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
     ##&& all(names(rg$R) == names(rg$G)))
}

rg.to.mu <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target != "OOB" & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        xf.bkg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), xf) + offset
        names(xf.bkg) <- names(xf)
        xf.bkg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value %in% unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.threshold <- cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    ## quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <- apply.quantile.normalization(quantile.sets, object$sex, mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}

#!/usr/bin/Rscript

library(lme4)
library(coefplot2)
library(glmmADMB)
library(Hmisc)
library(ggplot2)

load('flows-checkpoint3.RData')

## Refit with glmmadmb due to warnings about gradients above tolerance with lme4 fits

modNames <- c('glmeundirhmax', 'glmedirhmax', 'glmehmax')
fFin <- f[modNames]

tmpf <- function(x) {
    test <- !is.na(om$cases1WksAgo)
    data <- om[test, ]
    glmmadmb(x, data=data, family='nbinom')
}
mFin <- lapply(fFin, tmpf)

## Plot of predicted cases vs flow

fund <- fortify(m$glmeundirhmax, data=model.frame(m$glmeundirhmax))
theme_set(new=theme_classic())

g <- ggplot(data=fund, aes(x=exp(logUndirectedFlowScaled), y=exp(.fitted)))
g <- g + geom_smooth(method='loess', alpha=0, size=2, color='black')
g <- g + geom_point(aes(x=I(runif(nrow(fund), min=-.1,max=.1) + exp(logUndirectedFlowScaled)),
                        y=cases), col='black', alpha=0.5)
g <- g + labs(x='Flow (swine / pairs / year)', y='Cases')
g <- g + coord_trans(y="log1p") + ylim(0,100)
ggsave('flows-prediction.eps', width=4, height=4, pointsize=18, device=cairo_ps)
ggsave('flows-prediction.pdf', width=4, height=4, pointsize=18, device=cairo_pdf)

## Plots of fixed effects

ct <- lapply(mFin, function(x) coeftab(x)[, 1:2])

extractEsts <- function(pattern, type) {
  tmpf <- function(x) grep(pattern, rownames(x))
  inds <- lapply(ct, tmpf)
  res <- list()
  mapply(function(x, y) x[y, type], ct, inds)
}
  
patterns <- list(flow='Flow', dense='logCmedDenseScaled', week='weekCent', inf='Inf')
ests <- sapply(patterns, extractEsts, type='Estimate')
sds <- sapply(patterns, extractEsts, type='Std. Error')
weekIqr <- iqr(model.frame(m$glmedirhmax)$weekCent)
ests[, 'week'] <- ests[, 'week']*weekIqr
sds[, 'week'] <- sds[, 'week']*weekIqr

stopifnot(rownames(ests) == c('glmeundirhmax', 'glmedirhmax', 'glmehmax'))
ests <- cbind(ests, baseline=c(hund$maximum, hdir$maximum, hint$maximum))
sds <- cbind(sds, baseline=0)

tmpf <- function() {
    longnames <- c(flow='Scaled transport flow', inf='Cases last week', week='Scaled week', dense='Scaled farm density', baseline='Baseline risk') 
    pal <- c('black', 'orange', 'blue')
    pch <- 15:17
    for(i in seq_len(nrow(ests))){
        coefplot2(ests[i, ], sds[i, ], varnames=longnames[colnames(ests)],
                  offset=(i-1)/10, col=pal[i], add=i>1, pch=pch[i],
                  main="Regression estimates")
    }
    legend('topright', legend=c('undirected', 'directed', 'none'), col=pal, pch=pch, title='Interstate flow')
}

pdf('coefplot.pdf', width=5,height=4)
tmpf()
dev.off()
## This works better than making the ps with R for some reason
system('pdftops coefplot.pdf')

res <- 100
png('coefplot.png', width=5*res, height=4*res, res=res)
tmpf()
dev.off()


## Table of likelihoods, dispersion, parameters, random effects

getNBTheta <- function(x) {
    if(inherits(x, 'glmmadmb')) {
        summary(x)$alpha
    } else {
        as.numeric(strsplit(family(x)$family, split='\\(|\\)')[[1]][2])
    }
}
getLL <- function(x) as.numeric(logLik(x))
getSD <- function(x) as.numeric(sqrt(VarCorr(x)$stateF))
getdf <- function(x) attr(logLik(x), 'df')
getintercept <- function(x) fixef(x)['(Intercept)']

modList <- c(mFin, m[c('nbme', 'nbmeN')])
disp <- sapply(modList, getNBTheta)
llik <- sapply(modList, getLL)
resd <- sapply(modList, getSD)
df <- sapply(modList, getdf)
int <- sapply(modList, getintercept)

tmpf <- function() {
  tab <- data.frame(baseline=I('no'), int=unname(int), disp, resd, df, llik)
  rownames(tab) <- names(modList)
  tab[c('glmeundirhmax', 'glmedirhmax', 'glmehmax'), 'baseline'] <- 'yes'
  tab[, 'df'] <- tab[, 'df'] + ifelse(tab[, 'baseline'] == 'yes', 1, 0)
  aic <- 2*-tab[, 'llik'] + 2*tab[, 'df']
  tab <- cbind(tab, deltaAIC = aic - min(aic))
  flowTerm <- c(glmeundirhmax='undirected', glmedirhmax='directed', glmehmax='internal',
                nbme='internal', nbmeN='none')
  tab <- data.frame(flowTerm=flowTerm[rownames(tab)], tab)
  tf <- format.df(tab)
  align <- paste(attr(tf, "col.just"), collapse="|")
  align <- paste('|', align, '|', sep='')
  longnames <- c(flowTerm='\\bf Flow term', baseline='\\bf Fit $\\eta$',
                 disp='\\bf Intercept', df='\\bf d.f.', llik='\\bf Log lik.',
                 deltaAIC='\\bf $\\Delta$ AIC', resd='\\bf $\\hat{\\sigma}$',
                 int='{\\bf Intercept}')
  colnames(tab) <- longnames[colnames(tf)]
  tab <- latexTabular(tab, helvetica=FALSE, align=align, translate=FALSE,
                   cdec=c(0,0,1,2,2,0,1,1))
  tab <- gsub('\\\\multicolumn\\{1\\}\\{c\\}', '', tab)
  tab <- gsub('(\\\\)\\s?(\n)', '\\1\\\\hline\\2', tab)
  tab <- gsub('(\\n)(\\{\\\\bf Flow term\\})', '\\1\\\\hline\\2', tab)
  cat(tab, file='tab.tex')
}
tmpf()

Scales <- C(week=iqr(om$weekCent),
            internal=iqr(log(om$internalFlow)),
            cmedDense=iqr(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=iqr(log(om$undirectedFlow)),
            directeted=iqr(log(om$directedFlow)))
sink(file='scales.txt')
print(scales)
sink()

## Dotplot of AICs

flowTerm <- c(glmeundirhmax='Within-state + undirected between state',
              glmedirhmax='Within-state + directed between state',
              glmehmax='Within-state only',
              nbme='Within-state only, fixed other risks ',
              nbmeN='No flow, fixed other risks')

png('aic.png', width=7*res, height=4*res, res=res)
dotchart2(aic, labels=flowTerm[rownames(tab)], xlab='AIC (i.e., Estimated information loss)', dotsize=2)
dev.off()

save.image('flows-checkpoint4.RData')

                                             
## Selecting plot element for customizaiton
observe({
  v <- input$customizeItem
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']] <<- v
    }
  })
})
observe({
  updateInput[['customizeItem']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
  } else ''
  updateTabsetPanel(session, 'customizeItem', selected=null2String(s))
})

## modify plotTitle and other text fields
lapply(c('plotTitle', 'plotXlab', 'plotYlab'),
       function(inputId){
         assign(paste0('observer_', inputId, '_push'),
                observe({
                  v <- input[[inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)){
                      sheetList[[currentSheet]][['dynamicProperties']][[inputId]] <<- v
                    }
                  })

                }),
                sessionEnv)
         assign(paste0('observer_', inputId, '_pull'),
                observe({
                  updateInput[[inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- if(!isEmpty(currentSheet)){
                    isolate(sheetList[[currentSheet]][['dynamicProperties']][[inputId]])
                  } else ''
                  updateTextInput(session, inputId, value=null2String(s))
                }),
                sessionEnv)
       })



###########################
## Text Formatting

lapply(list(list(inputId='textFamily', inputType='select'),
            list(inputId='textFace', inputType='select'),
            list(inputId='textColor', inputType='color'),
            list(inputId='textSize', inputType='numeric'),
            list(inputId='textHjust', inputType='numeric'),
            list(inputId='textVjust', inputType='numeric'),
            list(inputId='textAngle', inputType='numeric'),
            list(inputId='textLineheight', inputType='numeric')),
       function(x){
         assign(paste0('observer_', x$inputId, '_push'),
                observe({
                  v <- input[[x$inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)) {
                      customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
                      if(!isEmpty(customizeItem)){
                        if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
                        }
                        if(x$inputId=='textColor' && !isEmpty(v)) v <- paste0("#", v)
                        if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]]))
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]] <<- v
                      }
                    }
                  })
                }),
                sessionEnv)
         if(x$inputId=='textColor') return() ## no updateJsColorInput is available yet
         assign(paste0('observer_', x$inputId, '_pull'),
                observe({
                  updateInput[[x$inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- ''
                  if(!isEmpty(currentSheet)){
                    customizeItem <- (sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
                    if(!isEmpty(customizeItem) && !is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]])
                    }
                  }

                  switch(x$inputType,
                         'numeric'=updateNumericInput(session, x$inputId, value=null2String(s)),
                         'select'=updateSelectInput(session, x$inputId, selected=null2String(s)))

                }),
                sessionEnv)
       })


## End of Text Formatting
###########################

# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    l.names = as.character(substitute(list(...)))[-1L]

    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            dimnames(l.[[i]]) = dimnames[[i]]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=l.names[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>%
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap", "backtrack", "tswap", "r00". See \code{\link[vegan]{commsim}} for details
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42, method="r0")
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="r0")
{
   method <- match.arg(method, c("r0", "r1", "r2", "r00", "c0", "swap", "tswap", "backtrack", "quasiswap"))
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   # Create randomised matrices
   null_model <- vegan::nullmodel (D$HP, method)
   randomised_matrices <- simulate (null_model, nsim = nperm)
   for(n in c(1:nperm))
   {
      permuted_HP <- randomised_matrices[, , n]
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   D$method <- method
   return(D)
}
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
probe system/script/args
if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	fast-mode:  find args "--fast"
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either fast-mode [
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
        
    ][
        do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
probe system/script/args
if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	fast-mode:  find args "--fast"
]
?? fast-mode
;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either fast-mode [
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
        
    ][
        do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
library(pcapack)

set.seed(1234)

m <- 10
n <- 50
m <- 50
n <- 10

x <- matrix(rnorm(m*n), m, n)


test <- function()
{
  mdl1 <- prcomp(x)
  mdl2 <- pca(x, method="svd")
#  mdl3 <- pca(x, method="svd", retx=FALSE)
  
#  all.equal(mdl1, mdl2)
  print(all.equal(mdl1$sdev, mdl2$sdev))
  print(all.equal(mdl1$rotation, mdl2$rotation))
  
  invisible()
}



test()

#Install dependencies
install.packages("reshape2")
install.package("ggplot2")

#Requires
require("reshape2")
require("ggplot2")

#Import the data
teams <- read.csv("./the-blue-alliance-data-master/the-blue-alliance-data-master/teams/teams.csv", header=FALSE)
names(teams) <- c("number", "name", "sponsors", "location", "website", "rookie_year")

#Let's parese the location further down into state
teams <- cbind(teams,colsplit(teams$location, pattern = ",", names = c("city","state","country")))

#Let's take a look ate how many teams join each year
png("new-teams-by-year.png")
years <- data.frame(table(teams$rookie_year))
years[1] <- as.numeric(levels(years[1]))[years[1]]
years[2] <- as.numeric(levels(years[2]))[years[2]]
names(years) <- c("year", "freq")
plot(years$year, years$freq)
reg1 <- lm(years$freq~years$year) #TODO, make this correct
abline(reg1)
abline(-30,20)
#TODO Add a polynomial regression hear
dev.off()

png("new-teams-by-year.2.png")
rookie_hist <- qplot(teams$rookie_year, main="Number of teams per year", xlab="Year")
rookie_hist <- rookie_hist + scale_x_continuous(breaks = seq(1990, 2018, by = 2))
rookie_hist <- rookie_hist + geom_freqpoly(size=2, color = "blue", alpha = .2)
rookie_hist + geom_freqpoly() 
#TODO, add a regression line to this
dev.off()

png("new-teams-by-year.3.png")
hist(teams$rookie_year) #This uses the base plotting system
dev.off()

png("new-teams-by-year.4.png")
#TODO qplot(years) + stat_bin(binwidth = 1,  col = "black")
dev.off()

png("team-count-by-state.png")
qplot(teams$state) #TODO sort by most numerous
dev.off()

png("team-count-by-state.2.png")
plot(table(teams$state)) #Uses base plotting system
dev.off()

png("team-count-by-state.3.png")
plot(data.frame(table(teams$state))) #Uses base plotting system
dev.off()
library(pcapack)
library(rbenchmark)

m <- 1e4
n <- 250
x <- matrix(rnorm(m*n), m, n)

reps <- 5

benchmark(R=A <- cov(x), Me=B <- pcapack_cov(x), replications=reps, columns=c("test", "elapsed", "relative"))
all.equal(A, B)
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}


## #my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


## load_pcoa_data.original <- function(PCoA_in){

##   start <- Sys.time ()
##   print(paste("start:", start))
  
##   con_1 <- file(PCoA_in)
##   con_2 <- file(PCoA_in)
##   # read through the first time to get the number of samples
##   open(con_1);
##   num_values <- 0
##   data_type = "NA"
##   while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##     if ( length( grep("PCO", my_line) ) == 1  ){
##       num_values <- num_values + 1
##     }
##   }
##   close(con_1)


##   # create object for values
##   eigen_values <- matrix("", num_values, 1)
##   dimnames(eigen_values)[[1]] <- 1:num_values
##   eigen_vectors <- matrix("", num_values, num_values)
##   dimnames(eigen_vectors)[[1]] <- 1:num_values
##   # read through a second time to populate the R objects
##   value_index <- 1
##   vector_index <- 1
##   open(con_2)
##   current.line <- 1
##   data_type = "NA"
##   while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##     if ( length( grep("#", my_line) ) == 1  ){
##       if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##     }else{
##       split_line <- noquote(strsplit(my_line, split="\t"))
##       if ( identical(data_type, "eigen_values")==TRUE ){
##         dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##         eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##         value_index <- value_index + 1
##       }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##     }
##   }
##   close(con_2)
##   # finish labeling of data objects
##   dimnames(eigen_values)[[2]] <- "EigenValues"
##   dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
##   class(eigen_values) <- "numeric"
##   class(eigen_vectors) <- "numeric"
##   # write imported data to global objects
##   #eigen_values <<- eigen_values
##   #eigen_vectors <<- eigen_vectors
  
##   runtime <- Sys.time () - start
##   print(paste("runtime:", round(runtime, digits=2), "seconds"))
##   return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
## }



## #my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

## library(data.table)

## load_pcoa_data.new <- function(PCoA_in){
  
##   start <- Sys.time ()
##   print(paste("start:", start))
  
##   con_1 <- file(PCoA_in)

##   open(con_1);
##   num_values <- 0
##   data_type = "NA"
##   while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##     if ( length( grep("PCO", my_line) ) == 1  ){
##       num_values <- num_values + 1
##     }
##   }
##   close(con_1)
##   # create object for values
##   eigen_values <- matrix("", num_values, 1)
##   dimnames(eigen_values)[[1]] <- 1:num_values
  
##   eigen_vectors.raw <- as.matrix(
##                                  fread(
##                                        #input=metadata_file, sep="\t", stringsAsFactors=FALSE,
##                                        input=PCoA_in, sep="\t", stringsAsFactors=FALSE,
##                                        skip="mgm", showProgress=TRUE, colClasses="character"
##                                        )
##                                  )
  
##   eigen_vectors.raw.test <<- eigen_vectors.raw
  
##   eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
##   dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
##   #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

##   runtime <- Sys.time () - start
##   print(paste("runtime:", round(runtime, digits=2), "seconds"))
##   #return(test_table)

##   return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

## }
  
  
## ## con_2 <- file(PCoA_in)
## ## # read through the first time to get the number of samples
## ## open(con_1);
## ## num_values <- 0
## ## data_type = "NA"
## ## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
## ##   if ( length( grep("PCO", my_line) ) == 1  ){
## ##     num_values <- num_values + 1
## ##   }
## ## }
## ## close(con_1)
## ## # create object for values
## ## eigen_values <- matrix("", num_values, 1)
## ## dimnames(eigen_values)[[1]] <- 1:num_values
## ## eigen_vectors <- matrix("", num_values, num_values)
## ## dimnames(eigen_vectors)[[1]] <- 1:num_values
## ## # read through a second time to populate the R objects
## ## value_index <- 1
## ## vector_index <- 1
## ## open(con_2)
## ## current.line <- 1
## ## data_type = "NA"
## ## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
## ##   if ( length( grep("#", my_line) ) == 1  ){
## ##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
## ##         data_type="eigen_values"
## ##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
## ##         data_type="eigen_vectors"
## ##       }
## ##   }else{
## ##     split_line <- noquote(strsplit(my_line, split="\t"))
## ##     if ( identical(data_type, "eigen_values")==TRUE ){
## ##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
## ##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
## ##       value_index <- value_index + 1
## ##     }
## ##       if ( identical(data_type, "eigen_vectors")==TRUE ){
## ##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
## ##         for (i in 2:(num_values+1)){
## ##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
## ##         }
## ##         vector_index <- vector_index + 1
## ##       }
## ##   }
## ## }
## ## close(con_2)
## ## # finish labeling of data objects
## ## dimnames(eigen_values)[[2]] <- "EigenValues"
## ## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## ## class(eigen_values) <- "numeric"
## ## class(eigen_vectors) <- "numeric"
## ## # write imported data to global objects
## ## #eigen_values <<- eigen_values
## ## #eigen_vectors <<- eigen_vectors

## ## runtime <- Sys.time () - start
## ## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## ## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

library(data.table)

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)

  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       #input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       input=PCoA_in, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

library(data.table)

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       #input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       input=PCoA_in, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

library(data.table)

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
con_2 <- file(PCoA_in)
# read through the first time to get the number of samples
open(con_1);
num_values <- 0
data_type = "NA"
while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
  if ( length( grep("PCO", my_line) ) == 1  ){
    num_values <- num_values + 1
  }
}
close(con_1)
# create object for values
eigen_values <- matrix("", num_values, 1)
dimnames(eigen_values)[[1]] <- 1:num_values
eigen_vectors <- matrix("", num_values, num_values)
dimnames(eigen_vectors)[[1]] <- 1:num_values
# read through a second time to populate the R objects
value_index <- 1
vector_index <- 1
open(con_2)
current.line <- 1
data_type = "NA"
while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
  if ( length( grep("#", my_line) ) == 1  ){
    if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
  }else{
    split_line <- noquote(strsplit(my_line, split="\t"))
    if ( identical(data_type, "eigen_values")==TRUE ){
      dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
      eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
      value_index <- value_index + 1
    }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
  }
}
close(con_2)
# finish labeling of data objects
dimnames(eigen_values)[[2]] <- "EigenValues"
dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
class(eigen_values) <- "numeric"
class(eigen_vectors) <- "numeric"
# write imported data to global objects
#eigen_values <<- eigen_values
#eigen_vectors <<- eigen_vectors

runtime <- Sys.time () - start
print(paste("runtime:", round(runtime, digits=2), "seconds"))
return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
con_2 <- file(PCoA_in)
# read through the first time to get the number of samples
open(con_1);
num_values <- 0
data_type = "NA"
while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
  if ( length( grep("PCO", my_line) ) == 1  ){
    num_values <- num_values + 1
  }
}
close(con_1)
# create object for values
eigen_values <- matrix("", num_values, 1)
dimnames(eigen_values)[[1]] <- 1:num_values
eigen_vectors <- matrix("", num_values, num_values)
dimnames(eigen_vectors)[[1]] <- 1:num_values
# read through a second time to populate the R objects
value_index <- 1
vector_index <- 1
open(con_2)
current.line <- 1
data_type = "NA"
while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
  if ( length( grep("#", my_line) ) == 1  ){
    if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
  }else{
    split_line <- noquote(strsplit(my_line, split="\t"))
    if ( identical(data_type, "eigen_values")==TRUE ){
      dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
      eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
      value_index <- value_index + 1
    }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
  }
}
close(con_2)
# finish labeling of data objects
dimnames(eigen_values)[[2]] <- "EigenValues"
dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
class(eigen_values) <- "numeric"
class(eigen_vectors) <- "numeric"
# write imported data to global objects
#eigen_values <<- eigen_values
#eigen_vectors <<- eigen_vectors

runtime <- Sys.time () - start
print(paste("runtime:", round(runtime, digits=2), "seconds"))
return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))




import_package = function (package, attach, attach_operators = TRUE) {
    stopifnot(inherits(package, 'character'))

    if (missing(attach)) {
        attach = if (interactive() && is.null(module_name()))
            getOption('import.attach', FALSE)
        else
            FALSE
    }

    stopifnot(class(attach) == 'logical' && length(attach) == 1)

    module_parent = parent.frame()

    # TODO: Do we actually need this? Nothing is attached here, even if loading
    # the package via `library` would attach stuff.
    # We can also just opt to blatantly ignore `Depends` packages.
    # Furthermore, S4 functions don’t work, and nor do S3, I’d wager.

    # Package which use `Depends` will pollute the global `search()` path.
    # We save the old `search()` path, and restore it afterwards. Furthermore,
    # We attach the list of attached packages to our local parent environment
    # chain instead.
    old_search = search()
    on.exit({
        if (! identical(module_parent, .GlobalEnv)) {
            newly_attached = setdiff(search(), old_search)
            for (pkg in newly_attached)
                detach(pkg)

            # Insert them into the current package’s parent chain.
            # We only need to insert the first one, since it already has the
            # others as its parents.
            # NOTE: This relies on the fact that `setdiff` doesn’t change the
            # order of the elements.

            parent.env(tail(newly_attached, 1)) = parent.env(module_parent)
            parent.env(module_parent) = newly_attached[1]
        }
    })

    pkg_ns = require_namespace(package)
    if (inherits(pkg_ns, 'error'))
        stop('Unable to load packge ', sQuote(package), '\n',
             'Failed with error: ', sQuote(conditionMessage(pkg_ns)))

    # TODO: Handle attaching

    # TODO: Return entries from  `.__NAMESPACE__.$exports`
    # FIXME: Wrong environment name set (is: 'module:packagename')
    # FIXME: Can the following ever differ from its contents, i.e. is
    #   all.equal(ls(…$exports), sapply(ls(…$exports), get, envir = …$exports))?
    export_list = getNamespaceExports(pkg_ns)
    pkg_env = exhibit_namespace(pkg_ns, package, module_parent, export_list)

    pkg_env$.__S3MethodsTable__. = pkg_ns$.__S3MethodsTable__.

    attached_module = if (attach)
        pkg_env
    else if (attach_operators)
        export_operators(pkg_ns, module_parent)
    else
        NULL

    if (! is.null(attached_module)) {
        # The following distinction is necessary because R segfaults if we try
        # to change `parent.env(.GlobalEnv)`. More info:
        # http://stackoverflow.com/q/22790484/1968
        if (identical(module_parent, .GlobalEnv)) {
            # FIXME: Run .onAttach?
            attach(attached_module, name = environmentName(attached_module))
            attr(pkg_env, 'attached') = environmentName(attached_module)
        }
        else
            parent.env(module_parent) = attached_module
    }

    lockEnvironment(pkg_env, bindings = TRUE)
    invisible(pkg_env)
}

# Similar to `base::requireNamespace`, but returns the package namespace,
# doesn’t swallow the error message, and without NSE shenanigans.
require_namespace = function(package) {
    ns = .Internal(getRegisteredNamespace(package))
    if (is.null(ns))
        ns = tryCatch(loadNamespace(package), error = identity)

    ns
}
REBOL [
	Title:   "Builds and Runs All Red and Red/System Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.2.1
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; function to find and run-tests
run-all-script: func [
	dir [file!]
	file [file!]
][
	qt/tests-dir: system/script/path/:dir
  	foreach line read/lines dir/:file [
  		if any [
			find line "===start-group"
  	  		find line "--run-"
  		][
  			do line
  		]
  	]
]

batch-mode: false
fast-mode: false
binary?: false
if system/script/args  [
	;; should we run non-interactively?
	batch-mode: find system/script/args "--batch"
	
	;; should we run quickly?
	fast-mode: find system/script/args "--fast"

	;; should we use the binary compiler?
	args: parse system/script/args " "
	if find system/script/args "--binary" [
		binary?: true
		bin-compiler: select args "--binary"
		if any [
			bin-compiler = "--batch"
			bin-complier = "--fast"
		][
			bin-compiler: none								;; use default
		]
		if bin-compiler [						
			if not attempt [exists? to file! bin-compiler] [
				either batch-mode [
					write %quick-test/quick-test.log "Invalid compiler path"
					quit/return 1
				][
					print "Invalid compiler path supplied"
					print args
					print ""
					halt
				]
			]
		]
	
	]
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true
store-current-dir: what-dir

do %quick-test/quick-test.r
if binary? [
	qt/binary?: binary?
	if bin-compiler [qt/bin-compiler: bin-compiler]
]

;; run the tests
print rejoin ["Quick-Test v" qt/version]
print rejoin ["REBOL " system/version]

start-time: now/precise

***start-run-quiet*** "Complete Red Test Suite"
qt/tests-dir: clean-path %system/tests/
do %system/tests/source/units/make-red-system-auto-tests.r
qt/tests-dir: clean-path %tests/
do %tests/source/units/make-red-auto-tests.r
do %tests/source/units/make-interpreter-auto-tests.r
qt/script-header: "Red []"
either fast-mode [
	run-all-script %tests/ %run-all-fast.r
][
	run-all-script %tests/ %run-all.r
]
qt/script-header: "Red/System []"
qt/tests-dir: clean-path %system/tests/ 
run-all-script %system/tests/ %run-all.r

***end-run-quiet***

end-time: now/precise
print ["       in" difference end-time start-time newline]
system/options/quiet: store-quiet-mode
change-dir store-current-dir
either batch-mode [
	quit/return either qt/test-run/failures > 0 [1] [0]
][
	print ["The test output was logged to" qt/log-file]
	ask "hit enter to finish"
	print ""
	qt/test-run/failures
]
library(plyr)
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)

# read in house sales data
path = system.file(package='RIntroBayarea')
sales_file <- paste0(path, "/extdata/house-sales.csv")
sales <- read.csv(sales_file, stringsAsFactors=FALSE)

# read in geolocation data
ad_file <- paste0(path, '/extdata/addresses.csv')
ad <- read.csv(ad_file, stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))

# and prices into numeric values
sales$price <- as.numeric(sales$price)

# check if there are missing vaules in sales or date
any(is.na(sales$price))
any(is.na(sales$date))

# remove missing rows with missing dates
sales <- sales[!is.na(sales$date), ]

# combine sales data with geospatial information
names(sales)
names(ad)

# by common columns
intersect_cols <- intersect(names(sales), names(ad))
geo <- join(sales, ad, by = intersect_cols)

# choose only records with goog quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- subset(geo, quality %in% precise_qual)

# choose cities with at least 20 sales a week
# how many weeks does our dataset cover?
n_weeks <- as.integer((max(precise$date) - min(precise$date)) / 7)

# calculate sales per city
cities <- as.data.frame(table(precise$city))
names(cities) <- c('city', 'freq')

big_cities <- subset(cities, freq > n_weeks * 20)

# see what we actually pick up
ggplot(geo, aes(city)) +
  geom_histogram() +
  geom_hline(yintercept=n_weeks*20)

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- subset(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in tme
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# load financial data (consumer price index)
cpi_file <- paste0(path, "/extdata/finances-cpi-west.csv")
cpi <- read.csv(cpi_file)

# add one last row (same as last available)
cpi <- rbind(cpi, data.frame(year = 2008, month = 11, cpi = cpi$cpi[nrow(cpi)]))

# start after April 2003
cpi <- subset(cpi, (year == 2003 & month >= 4) | year > 2003)

# calculate the ratio, compared to first cpi record
cpi$ratio <- cpi$cpi / cpi$cpi[1]

qplot(year + month / 12, ratio, data = cpi, geom = "line", ylab = "Inflation") + xlab(NULL)
REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	;--                 [objects images shapes sounds strings]
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   40]
		%PlanetaZluta      [600     1300   100    250   40]
		%PlanetaTermiti    [600     1300   100    290   40]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 300 40]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all/case to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | #"S" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 0.5 * length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not any [                              ;I don't use replace command when there is name
							all [block? temp/6 string? temp/7] ;temp/7 is place object's name (if color is not used)
							string? temp/6                     ;temp/6 is place object's name (if color is used) 
						]
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]#' Environment of loaded modules
#'
#' Each module is stored as an environment inside \code{.loaded_modules} with
#' the module’s code location path as its identifier. The path rather than the
#' module name is used because module names are not unique: two modules called
#' \code{a} can exist nested inside modules \code{b} and \code{c}, respectively.
#' Yet these may be loaded at the same time and need to be distinguished.
.loaded_modules = new.env()

is_module_loaded = function (module_path)
    exists(module_path, envir = .loaded_modules)

cache_module = function (module_ns)
    assign(module_path(module_ns), module_ns, envir = .loaded_modules)

get_loaded_module = function (module_path)
    get(module_path, envir = .loaded_modules)

#' Get a module’s path
#'
#' @param module a module environment or namespace
#' @return A character string containing the module’s full path.
module_path = function (module)
    attr(module, 'path')

#' Get a module’s base directory
#'
#' @param module a module environment or namespace
#' @return A character string containing the module’s base directory,
#'  or the current working directory if not invoked on a module.
module_base_path = function (module)
    UseMethod('module_base_path')

module_base_path.default = function (module) {
    if (identical(module, .GlobalEnv))
        script_path()
    else
        module_base_path(parent.env(module))
}

module_base_path.module = function (module)
    dirname(module_path(module))

module_base_path.namespace = function (module)
    dirname(module_path(module))

#' Set the base path of the script.
#'
#' @param path character string containing the relative or absolute path, or
#' \code{NULL} to reset the path
#'
#' @details
#' \emph{modules} needs to know the base path of the topmost calling R script
#' to find relative import locations. In most cases, it can figure the path out
#' automatically. However, in some cases third party packages load files in such
#' a way that \emph{modules} cannot find out the correct path of the script any
#' more. \code{set_script_path} can be used in these cases to set the script
#' path manually.
#' @export
set_script_path = function (path) {
    if (is.null(path))
        rm(., envir = .loaded_modules)
    else
        assign('.', dirname(path), .loaded_modules)
}

#' Return an R script’s path
script_path = function () {
    # Take a best guess at a script’s path. The following calling situations are
    # covered:
    #
    # 1. Explicitly via `set_script_path` set script path
    # 2. Rscript script.r
    # 3. R CMD BATCH script.r
    # 4. Script run interactively (give up, use `getwd()`)

    if (exists('.', envir = .loaded_modules))
        return(get('.', envir = .loaded_modules))

    args = commandArgs()

    file_arg = grep('--file=', args)
    if (length(file_arg) != 0)
        return(dirname(sub('--file=', '', args[file_arg])))

    f_arg = grep('-f', args)
    if (length(f_arg) != 0)
        return(dirname(args[f_arg + 1]))

    getwd()
}

#' Get a module’s name
#'
#' @param module a module environment (default: current module)
#' @return A character string containing the name of the module or \code{NULL}
#'  if called from outside a module.
#' @note A module’s name is the name of a module that it was \code{import}ed
#' with. If the same module is subsequently imported using another qualifie
#' name (from within the same package, say, and hence truncated), the module
#' names of the two module instances may differ, even though the same copy of
#' the byte code is used.
#' This function approximates Python’s magic variable \code{__name__}, and can
#' be used similarly to test whether a module was loaded via \code{import} or
#' invoked directly.
#' @examples
#' \dontrun{
#' cat('This code is always executed.\n')
#'
#' if (is.null(module_name())) {
#'     cat('This code is only executed when the module is run
#'         as stand-alone code via Rscript or R CMD BATCH.\n')
#' }
#' }
#' @export
module_name = function (module = parent.frame())
    UseMethod('module_name', module)

#' @seealso \code{module_name}
#' @export
module_name.default = function (module = parent.frame()) {
    if (identical(module, .GlobalEnv))
        NULL
    else
        module_name(parent.env(module))
}

#' @seealso \code{module_name}
#' @export
module_name.module = function (module = parent.frame())
    strsplit(attr(module, 'name'), ':', fixed = TRUE)[[1]][2]

#' @seealso \code{module_name}
#' @export
module_name.namespace = function (module = parent.frame())
    strsplit(attr(module, 'name'), ':', fixed = TRUE)[[1]][2]
library(plyr)
library(ggplot2)

# read in house sales data
path = system.file(package='RIntroBayarea')
sales_file <- paste0(path, "/extdata/house-sales.csv")
sales <- read.csv(sales_file, stringsAsFactors=FALSE)

# read in geolocation data
ad_file <- paste0(path, '/extdata/addresses.csv')
ad <- read.csv(ad_file, stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))

# and prices into numeric values
sales$price <- as.numeric(sales$price)

# check if there are missing vaules in sales or date
any(is.na(sales$price))
any(is.na(sales$date))

# remove missing rows with missing dates
sales <- sales[!is.na(sales$date), ]

# combine sales data with geospatial information
names(sales)
names(ad)

# by common columns
intersect_cols <- intersect(names(sales), names(ad))
geo <- join(sales, ad, by = intersect_cols)

# choose only records with goog quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- subset(geo, quality %in% precise_qual)

# choose cities with at least 20 sales a week
# how many weeks does our dataset cover?
n_weeks <- as.integer((max(precise$date) - min(precise$date)) / 7)

# calculate sales per city
cities <- as.data.frame(table(precise$city))
names(cities) <- c('city', 'freq')

big_cities <- subset(cities, freq > n_weeks * 20)

# see what we actually pick up
ggplot(geo, aes(city)) +
  geom_histogram() +
  geom_hline(yintercept=n_weeks*20)

# add interesting citie
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- subset(geo, city %in% selected)
install.packages("datasets", dependencies = TRUE)
install.packages("methods", dependencies = TRUE)
install.packages("ggplot2", dependencies = TRUE)
install.packages("knitr", dependencies = TRUE)
install.packages("devtools", dependencies = TRUE)
install.packages("base64enc", dependencies = TRUE)
library(devtools)
options(unzip = "internal")
install_github("ramnathv/rCharts@dev")
## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(6,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL)
                                   ),
                            column(6,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map')
                                                    )

                                   )
                            ),

                          uiOutput('mapOrSetUI'),
                          conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                           jscolorInput('aesValueColor')),

                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          navlistPanel(id='customizeItem',
                            'Labels',
                            tabPanel('Plot Title', value='title',
                                     textInput('plotTitle', '')
                                     ),
                            tabPanel('X Axis Title', value='xlab',
                                        textInput('plotXlab', '')
                            )
                            ),
                          conditionalPanel('true',
                                           h4('Format Text'),
                                           fluidRow(
                                             selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                             selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                             jscolorInput('textColor'),
                                             numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1)
                                             )
                                           ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),



  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

#' Contribution of individual links
#' @param D A list returned by proc_analysis
#' @param .parallel if \code{TRUE}, calculate the jacknife contribution in parallel using the backend provided by foreach
#' @param .progress name of the progress bar to use see \code{\link[plyr]{create_progress_bar}}. Options inlcude "text" and "tk". It only works when \code{parallel = FALSE}
#' @param ... Additional arguments to be passed to PACo
#' @return A list with added object jacknife, containing the mean and upper CI values for each link
#' @export
paco_links <- function(D, .parallel = FALSE, .progress = "none", ...)
{
   HP.ones <- which(D$HP > 0, arr.ind=TRUE)
   SQres.jackn <- matrix(rep(NA, sum(D$HP)^2), sum(D$HP))# empty matrix of jackknifed squared residuals
   colnames(SQres.jackn) <- paste(rownames(D$proc$X),rownames(D$proc$Yrot), sep="-") #colnames identify the H-P link
   t.critical = qt(0.975,sum(D$HP)-1) #Needed to compute 95% confidence intervals.
   nlinks <- sum(D$HP)
   
   # In parallel
   if (.parallel & exists ("foreach")) {
     foreach (i=1:nlinks, .combine = rbind) %dopar% single_paco_link (D, HP.ones, i, ...)
   } else {
   # In sequence 
     if (.parallel & !exists ("foreach")) warning ("No parallel backend registered. Executing sequentially instead.")
     pb <- plyr::create_progress_bar (.progress)
     pb$init (nlinks)
     for(i in c(1:nlinks)) 
     {
       res.Proc.ind <- single_paco_link (D, HP.ones, i, ...)
       SQres.jackn[i, ] <- res.Proc.ind   #Append residuals to matrix of jackknifed squared residuals
       pb$step ()
     } 
     pb$term ()
   }
   
   SQres.jackn <- SQres.jackn^2 #Jackknifed residuals are squared
   SQres <- (residuals(D$proc))^2 # Vector of original square residuals
   #jackknife calculations:
   SQres.jackn <- SQres.jackn*(-(sum(D$HP)-1))
   SQres <- SQres*sum(D$HP)
   SQres.jackn <- t(apply(SQres.jackn, 1, "+", SQres)) #apply jackknife function to matrix
   phi.mean <- apply(SQres.jackn, 2, mean, na.rm = TRUE) #mean jackknife estimate per link
   phi.UCI <- apply(SQres.jackn, 2, sd, na.rm = TRUE) #standard deviation of estimates
   phi.UCI <- phi.mean + t.critical * phi.UCI/sqrt(sum(D$HP))
   D$jackknife <- list(mean = phi.mean, upper = phi.UCI)
   return(D)
}

#PACo setting the ith link = 0
single_paco_link <- function (D, HP.ones, i,...) {
  HP_ind <- D$HP
  HP_ind[HP.ones[i,1],HP.ones[i,2]]=0
  PACo.ind <- PACo(list(H=D$H, P=D$P, HP=HP_ind), method=D$method, ...)
  Proc.ind <- vegan::procrustes(X=PACo.ind$H_PCo, Y=PACo.ind$P_PCo) 
  res.Proc.ind <- c(residuals(Proc.ind))
  res.Proc.ind <- append(res.Proc.ind, NA, after= i-1)
}
library = function (...) suppressMessages(base::library(...))
assign('library', library, globalenv())

library(knitr)
library(modules)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())

## conditional calculated field: mutate and ddply; see documentation for ddply
## groups: use selectInput with multiple=TRUE and selectize = FALSE
## http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information

## GitHub Hosting example: https://gist.github.com/mattbrehmer/5645155
## Alternative to ggplot2: https://github.com/ramnathv/rCharts

#options(error = browser)
# NULL, browser, etc.
options(shiny.error=NULL)
# options(shiny.error=function() {
#   ## skip validation errors
#   if(!inherits(eval.parent(expression(e)), "validation")) browser()
# })
options(shiny.trace = FALSE)  # change to TRUE for trace
#options(shiny.reactlog=TRUE)
options(shiny.maxRequestSize = 100*1024^2)  # Set the upload limit to 100MB
## see https://groups.google.com/forum/#!topic/shiny-discuss/2wgIG3dOEZI

require(shiny); require(reshape); require(ggplot2); require(Hmisc); require(uuid); #require(plotly);
require(tables); require(tools); require(png); require(data.table); require(shinysky); require(Cairo)
require(knitr); require(rmarkdown); require(shinyAce)

options(shiny.usecairo=TRUE)


MoltenMeasuresName <- 'value'
lengthUnique <<- function(x) { length(unique(x)) }
YFunChoices <- c('Sum'='sum','Mean'='mean','Median'='median','Min'='min','Max'='max',
                 'Standard Deviation'='sd','Variance'='var','Count'='length', 'Count (Distinct)'='lengthUnique')
AggFunChoicesDimension <- c('Min'='min','Max'='max',
                            'Count'='length', 'Count (Distinct)'='lengthUnique')
InternalY <- '..y..'


GeomChoices <- c('Text'='text', 'Bar'='bar','Line'='line',
                 'Area'='area',  'Point'='point',
                 'Path'='path','Polygon'='polygon',
                 'Boxplot'='boxplot')
StatChoices <- c('Identity'='identity','Count'='bin','Summary'='summary','Boxplot'='boxplot')


getAesChoices <- function(geom, stat='identity'){
  switch(geom,
         'text'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                           'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                'Color'=c('Alpha'='aesAlpha'),
                                'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                                'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                     'Color'=c('Alpha'='aesAlpha'),
                                     'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                     'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     )
        ),

        'bar'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType','Weight'='aesWeight'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType','Weight'='aesWeight'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'line'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType',
                                           'Grouping'='aesGroup'),
                                'Color'=c('Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType',
                                                'Grouping'='aesGroup'),
                                     'Color'=c('Alpha'='aesAlpha')
                     )
        ),

        'area'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'point'=switch(stat,
                      'bin'=list('Coordinates'=c('X'='aesX'),
                                 'Common'=c('Color'='aesColor','Size'='aesSize',
                                            'Shape'='aesShape'),
                                 'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      ),
                      'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                      'Common'=c('Color'='aesColor','Size'='aesSize',
                                                 'Shape'='aesShape'),
                                      'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      )
        ),

        'boxplot'=switch(stat,
                         'boxplot'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                        'Common'=c('Color'='aesColor','Size'='aesSize',
                                                   'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                        'Color'=c('Border Color'='aesBorderColor',
                                                  'Alpha'='aesAlpha')
                         ),
                         'identity'=list('Coordinates'=c('X'='aesX','Y Middle'='aesMiddle',
                                                         'Y Lower'='aesLower','Y Upper'='aesUpper',
                                                         'Y Min'='aesYmin','Y Max'='aesYmax'),
                                         'Common'=c('Color'='aesColor','Size'='aesSize',
                                                    'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                         'Color'=c('Border Color'='aesBorderColor',
                                                   'Alpha'='aesAlpha')
                         )
        )

  )
}

AesChoicesSimpleList <- unique(unlist(lapply(GeomChoices, getAesChoices), use.names=FALSE))

fonttable <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE,
                        text='
Short,Canonical
mono,Courier
sans,Helvetica
serif,Times
,AvantGarde
,Bookman
,Helvetica-Narrow
,NewCenturySchoolbook
,Palatino
,URWGothic
,URWBookman
,NimbusMon
URWHelvetica,NimbusSan
,NimbusSanCond
,CenturySch
,URWPalladio
URWTimes,NimbusRom
')
FontFamilyChoices <- as.vector(t(as.matrix(fonttable)))
FontFamilyChoices <- FontFamilyChoices[FontFamilyChoices!='']

FontFaceChoices <- c("plain","bold","italic","bold.italic")


#' Default http server configuration for libuv hook.
#' 
#' @param routes list. A named list of routes, with a handler
#'    function for each route. The first unnamed route will be used
#'    as the root. If none is provided, just a 404 status will be returned.
#' @examples
#' \dontrun{
#'   http_server(list('/ping' = function(params, query) 'Hello world!',
#'                    function(params, query) 'Invalid route.'))
#' }
http_server <- function(routes) {
  function(req) {
    params <- extract_params_from_request(req)
    query  <- extract_query_from_request(req)
    route  <- determine_route(routes, req$PATH_INFO)
    environment(route) <- environment()
    result <- route(params, query)
    if (is.microserver_response(result)) unclass(result)
    else unclass(microserver_response(result))
  }
}


#' Minimal function for opening a socket and accepting/responding to
#' requests.
#'
#' @param routes list. A named list of routes.
#' @param port integer. The default is 8103.
#' @importFrom httpuv startServer stopServer service
#' @export
run_server <- function(routes, port = 8103) {
  # A list of default HTTUPV callbacks
  httpuv_callbacks <- list(
    onHeaders = function(req) { NULL },
    call = http_server(routes),
    onWSOpen = function(ws) {
      # print('opening websocket')
    }
  )

  server_id <- httpuv::startServer("0.0.0.0", port, httpuv_callbacks)
  on.exit({ httpuv::stopServer(server_id) }, add = TRUE)

  repeat {
    httpuv::service(1)
    Sys.sleep(0.001)
  }
}

library(ggplot2)
load("city-summary.rdata")


ggplot(bigsum, aes(date, price / 1e6)) + 
  geom_line() + 
  facet_wrap(~ city)
ggsave("cities-price.png", width = 8, height = 6, dpi = 128)

# Smoothing ------------------------------------------------------------------

library(mgcv)
smooth <- function(y, x) {
  as.numeric(predict(gam(y ~ s(x), na.action = na.exclude)))
}

bigsum <- ddply(bigsum, .(city), transform,
  price_s = smooth(price, as.numeric(date)))

ggplot(bigsum, aes(date, price_s / 1e6)) + 
  geom_line() + 
  facet_wrap(~ city)
ggsave(file = "cities-smooth.png", width = 8, height = 6, dpi = 128)

index <- function(y, x) {
  y / y[order(x)[1]]
}
bigsum <- ddply(bigsum, .(city), transform,
  price_si = index(price_s, date))

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city) 
ggsave(file = "cities-index.png", width = 8, height = 6, dpi = 128)

# Simplify  ---------------------------------------------------------

# Show location of peak and plummet
brentwood <- subset(bigsum, city == "Brentwood")
brentwood_sum <- subset(brentwood, as.character(date) %in% c("2006-01-15", "2006-06-04"))
ggplot(brentwood, aes(date, price_si)) +
  geom_line() + 
  geom_point(data = brentwood_sum, colour = "red", size = 5)
ggsave("brentwood.png", width = 8, height = 6, dpi = 128)

covar <- ddply(bigsum, "city", summarise,
  peak = price_si[date == "2006-01-15"],
  plummet = price_si[date == "2006-06-04"]
)

ggplot(covar, aes(peak, plummet)) + 
  geom_point()
ggsave(file = "cities-2d.png", width = 6, height = 6, dpi = 128)

ggplot(covar, aes(peak, plummet)) + 
  geom_point() +
  geom_text(aes(label = city), size = 4, hjust = -0.05)
ggsave(file = "cities-2d-labelled.png", width = 6, height = 6, dpi = 128)


# Try and explain with covariates from the census data ----------------------

covar$delta <- with(covar, plummet - peak)

census <- read.csv("census-city.csv")
covar <- join(covar, census, by = "city")

base <- ggplot(covar, aes(y = delta)) + geom_point()
base + aes(grads)
ggsave(file = "covar-grads.png", width = 6, height = 6, dpi = 128)
base + aes(income)
ggsave(file = "covar-income.png", width = 6, height = 6, dpi = 128)
base + aes(housesold_size)
ggsave(file = "covar-household.png", width = 6, height = 6, dpi = 128)
#' @title Pobieranie danych o szkołach.
#' @description
#' Funkcja pobiera z bazy dane o szkołach - o ich typie i specyfice, nazwie, adresowe i o lokalizacji.
#' @param lata wektor liczb całkowitych - lata, których mają dotyczyć dane (dla każdej szkoły zwrócone zostaną tylko najświeższe dane w ramach tego okresu)
#' @param typySzkol opcjonalny wektor tekstowy z typami szkół, które mają zostać zwrócone (lub NULL - zwraca informacje o wszystkich szkołach)
#' @param idOke wartość logiczna (domyślnie FALSE) - czy dołączać kody OKE szkół?
#' @param daneAdresowe wartość logiczna (domyślnie FALSE) - czy dołączać nazwę i dane adresowe?
#' @param dolaczPaou wartość logiczna (domyślnie FALSE) - czy dołączać szkoły z danych PAOU?
#' @param zrodloDanychODBC opcjonalnie nazwa źródła danych ODBC, dającego dostęp do bazy (domyślnie "EWD")
#' @return data frame
#' @import RODBCext
#' @export
pobierz_dane_szkol <- function(lata, typySzkol=NULL, idOke=FALSE, daneAdresowe=FALSE, dolaczPaou=FALSE, zrodloDanychODBC="EWD"){
  stopifnot(is.numeric(lata)         , length(lata) > 0,
            is.character(typySzkol) | is.null(typySzkol),
            is.logical(idOke)       , length(idOke) == 1,
            is.logical(daneAdresowe), length(daneAdresowe) == 1,
            is.logical(dolaczPaou)  , length(dolaczPaou) == 1,
            is.character(zrodloDanychODBC), length(zrodloDanychODBC) == 1
  )
  stopifnot(idOke %in% c(TRUE, FALSE), daneAdresowe %in% c(TRUE, FALSE), dolaczPaou %in% c(TRUE, FALSE))
  try(suppressWarnings(Sys.setlocale("LC_ALL", "pl_PL.UTF-8")))

  zapytanie = paste0( "SELECT id_szkoly, typ_szkoly, publiczna, dla_doroslych, specjalna, przyszpitalna, artystyczna,
                        d.rok, ",
                      ifelse(daneAdresowe, "d.nazwa, d.miejscowosc, d.adres, d.pna, d.poczta, ", ""),
                      ifelse(idOke       , "d.id_szkoly_oke, ", ""),
                      "d.wielkosc_miejscowosci, id_gminy + 100*id_powiatu + 10000*id_wojewodztwa AS teryt",
                      ifelse( is.null(typySzkol) | any(typySzkol %in% c("LO","LP","T")) ,", d.matura_miedzynarodowa",""),
                      " FROM szkoly AS sz JOIN szkoly_dane AS d USING (id_szkoly)
                      WHERE sz.id_szkoly > 0 AND d.rok IN (", paste0(rep("?", length(lata)), collapse=", "), ")
                        AND d.rok = (SELECT max(rok) FROM szkoly_dane WHERE id_szkoly = d.id_szkoly AND rok IN (", paste0(lata, collapse=", "), "))",
                      ifelse( is.null(typySzkol), "", paste0(" AND sz.typ_szkoly IN (", paste0(rep("?", length(typySzkol)), collapse=", "), ")") ),
                      ifelse( dolaczPaou, "", " AND sz.paou = FALSE"),
                      " ORDER BY id_szkoly")
  dane = if( is.null(typySzkol)){
    as.list(lata)
  } else{
    data.frame(as.list(lata), as.list(typySzkol), stringsAsFactors=FALSE)
  }

  tryCatch({
      P = odbcConnect(zrodloDanychODBC)
      ret = sqlExecute(P, zapytanie, fetch=TRUE, stringsAsFactors=FALSE, data=dane)
    },
    error = stop,
    finally = odbcClose(P)
  )

  ret$typ_szkoly[ret$typ_szkoly=="TRUE"] = "T"
  if (!("SP" %in% typySzkol)) ret = ret[, names(ret) != "id_szkoly_obut"]

  typyWWynikach = typySzkol %in% ret$typ_szkoly
  if (any(!typyWWynikach)) warning("Nie znaleziono żadnych szkół typu/ów: ", paste0(typySzkol[!typyWWynikach], collapse=", "), ".")

  attributes(ret)$lata = lata
  return( ret )
}
### PREPARE DATA

#' Get word assignments from LDA_GIBBS class (output of topmod.lda.fit). This is similar to the documentsums object that comes as the output of lda.collapsed.gibbs.sampler
#' 
#' Get word assignments from LDA_GIBBS class (output of topmod.lda.fit). This is similar to the documentsums object that comes as the output of lda.collapsed.gibbs.sampler
#' LDA assigns a topic to each unique word in a document. If you also want to take into account how often this word occured, the document term matrix (as used in the input for topmod.lda.fit) must be included in the weight.by.dtm argument.
#' 
#' @param m The output from one of the topicmodeling functions in the topicmodels package (e.g., LDA_GIBBS)
#' @param weight.by.dtm If you want to weight the topic assignment of a word to the number of times the word occured, give the document term matrix for this argument
#' @return A matrix where rows are topics and columns are documents. Values represent the number of times the topic is assigned to a word in this document (essentially this is the same as the documentsums object in the output of lda.collapsed.gibbs.samler)
#' @export
documentsums <- function(m, weight.by.dtm=NULL){
  assignments = data.frame(i=m@wordassignments$i, j=m@wordassignments$j, v=m@wordassignments$v)
  if(!is.null(weight.by.dtm)){
    dtm = weight.by.dtm[m@documents,m@terms]
    dtm = data.frame(i=dtm$i, j=dtm$j, count=dtm$v)
    assignments = merge(assignments, dtm, by=c('i','j'), all.x=T)
    docsums = acast(assignments, v ~ i, value.var='count', fun.aggregate=sum)
  } else docsums = acast(assignments, v ~ i, value.var='j', fun.aggregate=length) 
  docsums
}

#' Estimate a topic model using the lda package
#' 
#' Estimate an LDA topic model using the \code{\link{LDA}} function
#' The parameters other than dtm are simply passed to the sampler but provide a workable default.
#' See the description of that function for more information
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{amcat.dtm.create}})
#' @param K the number of clusters
#' @param num.iterations the number of iterations
#' @param alpha the alpha parameter
#' @param eta the eta parameter
#' @return A fitted LDA model (see \code{\link{LDA}})
#' @export
topmod.lda.fit <- function(dtm, method='Gibbs', K=50, num.iterations=500, alpha=50/K, eta=.01, burnin=250) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]
  m = LDA(dtm, k=K, method=method, control=list(iter=num.iterations, burnin=burnin, alpha=alpha, delta=eta))
  m
}

#' Get the topics per document, optionally merged with 
#' 
#' Return a data frame containing article metadata and topic occurence per document
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
topmod.topics.per.document <- function(topics) {
  ids = as.numeric(m@documents)
  cbind(id=ids, data.frame(posterior(m)$topics))
}

#' Add document meta to LDA output
#' 
#' Add a dataframe containing document meta to the output (a list) of \code{\link{lda.collapsed.gibbs.sampler}}. 
#' 
#' @param m The output of \code{\link{LDA}}   
#' @param meta A data.frame with document meta. Has to contain a vector to match the document.ids
#' @param match.by The name of the vector in meta that matches the document.ids 
#' @return The LDA output appended with document meta
#' @export
topmod.order.meta <- function(m, meta, match.by = 'id'){
  meta[match(m@documents, meta[,match.by]),]
}

### PLOT LDA TOPICS

#' Plot all topics
#' 
#' Write plots for all topics with \code{\link{topmod.plot.topic}} in designated folder
#' 
#' @param m The output of \code{\link{topmod.collapsed.gibbs.sampler}}   
#' @param time_var A vector with time stamps (either numeric or Date class) of the same length and order of the documents (rows) in m$document_sums
#' @param category_var A vector with id values of the same length and order of the documents (rows) in m$document_sums
#' @param path The path for a folder where output will be saved
#' @param date_interval The interval for plotting the values over time. Can be: 'day', 'week', 'month' or 'year'
#' @return Nothing
#' @export
topmod.plot.alltopics <- function(m, time_var, category_var, path, date_interval='day', value='total', create_index=T){
  if (!file.exists(path)) dir.create(path)
  for(topic_nr in 1:m@k){
    message('Plotting:', topic_nr)
    fn = file.path(path, paste(topic_nr, ".png", sep=""))
    if (!is.null(fn)) png(fn, width=1280,height=800)
    topmod.plot.topic(m, topic_nr, time_var, category_var, date_interval, value=value)
    if (!is.null(fn)) dev.off()
  }
  par(mfrow=c(1,1), mar=c(3,3,3,3))
  if (create_index) {
    index = create_index(m)
    fn = file.path(path, "index.html")
    write(index,  fn)
    message('Writing ', fn)
    if (interactive()) browseURL(fn)
  }
}

#' Plots topic wordcloud, and attention over time and per category
#' 
#' Plots \code{\link{topmod.plot.wordcloud}}, \code{\link{topmod.plot.time}} and \code{\link{topmod.plot.category}}
#' 
#' @param m The output of \code{\link{topmod.collapsed.gibbs.sampler}}
#' @param The index of the topic (1 to K)
#' @param time_var A vector with time stamps (either numeric or Date class) of the same length and order of the documents (rows) in m$document_sums
#' @param category_var A vector with id values of the same length and order of the documents (rows) in m$document_sums
#' @param date_interval The interval for plotting the values over time. Can be: 'day', 'week', 'month' or 'year'
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @return Nothing, just plots
#' @export
topmod.plot.topic <- function(m, topic_nr, time_var, category_var, date_interval='day', pct=F, value='total'){
  par(mar=c(4.5,3,2,1), cex.axis=1.7)
  layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE), widths=c(3,1), heights=c(1,3))
  topmod.plot.time(m, topic_nr, time_var, date_interval, pct=pct, value=value)
  topmod.plot.wordcloud(m, topic_nr)
  topmod.plot.category(m, topic_nr, category_var, pct=pct, value=value)
  par(mfrow=c(1,1), mar=c(3,3,3,3))
}

#' Change date object to date_interval
#' 
#' Change date object to date_interval
#' 
#' @param time_var A vector of Date values
#' @param date_interval The desired date_interval ('day','week','month', or 'year')
#' @return A vector of Date values
#' @export
topmod.prepare.time.var <- function(time_var, date_interval){
  if(class(time_var) == 'Date'){
    if(date_interval == 'day') time_var = as.Date(format(time_var, '%Y-%m-%d'))
    if(date_interval == 'month') time_var = as.Date(paste(format(time_var, '%Y-%m'),'-01',sep=''))
    if(date_interval == 'week') time_var = as.Date(paste(format(time_var, '%Y-%W'),1), '%Y-%W %u')
    if(date_interval == 'year') time_var = as.Date(paste(format(time_var, '%Y'),'-01-01',sep=''))
  } 
  time_var
}

#' Add empty values for pretty plotting
#' 
#' When plotting a timeline, gaps in date_intervals are ignored. For the attention for topics gaps should be considered as having value 0.   
#' 
#' @param d A data.frame with the columns 'time' (Date) and 'value' (numeric)  
#' @param date_interval The date_interval is required to know what the gaps are
#' @return A data.frame with the columns 'time' (Date) and 'value' (numeric)  
#' @export
topmod.fill.time.gaps <- function(d, date_interval){
  if(class(d$time) == 'numeric'){
    for(t in min(d$time):max(d$time)) 
      if(!t %in% d$time) d = rbind(d, data.frame(time=t, value=0))
  }
  if(class(d$time) == 'Date'){
    date_sequence = seq.Date(from=min(d$time), to=max(d$time), by=date_interval)
    for(i in 1:length(date_sequence)){
      t = date_sequence[i]
      if(!t %in% d$time) d = rbind(d, data.frame(time=t, value=0))
    }
  }
  d[order(d$time),]
}

#' Prepares the topic values per document for plotting 
#' 
#' Prepares the topic values per document for plotting
#' 
#' @param m The output of \code{\link{LDA}}
#' @param break_var A break vector to aggregate topic values per document
#' @param The index of the topic (1 to K)
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @return The aggregated/transformed topic values
#' @export
topmod.prepare.plot.values <- function(m, break_var, topic_nr, pct=F, value='total', filter=NULL){
  docsums = documentsums(m)
  hits = docsums[topic_nr,]
  d = aggregate(hits, by=list(break_var=break_var), FUN='sum') 
  if(value == 'relative'){
    total_hits = colSums(docsums)  
    totals = aggregate(total_hits, by=list(break_var=break_var), FUN='sum')
    d$x = d$x / totals$x
  }
  if(pct == T) d$x = d$x / sum(d$x)
  d
}


#' Plots topic values over time
#' 
#' Plots the attention for a topic over time
#' 
#' @param m The output of \code{\link{LDA}}
#' @param The index of the topic (1 to K)
#' @param time_var A vector with time stamps (either numeric or Date class) of the same length and order of the documents (rows) in m$document_sums
#' @param date_interval The interval for plotting the values over time. Can be: 'day', 'week', 'month' or 'year'
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @param return.values Logical. If true, data that is plotted is returned as a data.frame
#' @return data.frame for plotted values
#' @export
topmod.plot.time <- function(m, topic_nr, time_var, date_interval='day', pct=F, value='total', return.values=F){
  par(mar=c(3,3,3,1))
  time_var = topmod.prepare.time.var(time_var, date_interval)  
  d = topmod.prepare.plot.values(m, break_var=time_var, topic_nr=topic_nr, pct=pct, value=value)
  colnames(d) = c('time','value')
  d = topmod.fill.time.gaps(d, date_interval)
  plot(d$time, d$value, type='l', xlab='', main='', ylab='', xlim=c(min(d$time), max(d$time)), ylim=c(0, max(d$value)), bty='L', lwd=5, col='darkgrey')
  par(mar=c(3,3,3,3))
  if(return.values==T) d
}

#' Plots topic values per category
#' 
#' Plots the attention for a topic per category
#' 
#' @param m The output of \code{\link{LDA}}
#' @param The index of the topic (1 to K)
#' @param category_var A vector with id values of the same length and order of the documents (rows) in m$document_sums
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @param return.values Logical. If true, data that is plotted is returned as a data.frame
#' @return data.frame for plotted values
#' @export
topmod.plot.category <- function(m, topic_nr, category_var, pct=F, value='total', return.values=F){
  par(mar=c(15,3,1,2))
  d = topmod.prepare.plot.values(m, break_var=category_var, topic_nr=topic_nr, pct=pct, value=value)
  colnames(d) = c('category','value')
  barplot(as.matrix(t(d[,c('value')])), main='', beside=TRUE,horiz=FALSE,
          density=NA,
          col='darkgrey',
          xlab='',
          ylab="",
          axes=T, names.arg=d$category, cex.names=1.2, cex.axis=1.2, adj=1, las=2)
  par(mar=c(3,3,3,3))
  if(return.values==T) d
}

#' Plot wordcloud for LDA topic
#' 
#' Plots a wordcloud of the top words per topic
#' 
#' @param m The output of \code{\link{LDA}}
#' @param topic_nr The index of the topic (1 to K)
#' @return Nothing, just plots
#' @export
topmod.plot.wordcloud <- function(m, topic_nr){
  x = posterior(m)$terms[topic_nr,]
  x = sort(x, decreasing=T)[1:100]
  x = x[!is.na(x)]
  names = sub("/.*", "", names(x))
  freqs = x
  pal <- brewer.pal(6,"YlGnBu")
  wordcloud(names, freqs, scale=c(10,.5), min.freq=1, max.words=Inf, random.order=FALSE, rot.per=.15, colors=pal)
}

#' Create an index file for plot.all.topics
topmod_create_index <- function(m) {
  html = c('<html>', 
           '<head><link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"></head>',
           '<body><div class="row">')
  for (i in 1:nrow(m@beta)) {
    chunk = paste('<div class="col-xs-6 col-md-2 col-lg-3"><a href="', i, '.png"',
                  ' class="thumbnail"><img src="',i,'.png"></a></div>', sep='')
    html = c(html, chunk)
  }
  html = c(html, "</div></body></html>")
  paste(html, collapse="\n")
}
#' Cast data.frame to sparse matrix
#' 
#' Create a sparse matrix from matching vectors of row indices, column indices and values
#' 
#' @param rows a vector of row indices: [i,]
#' @param columns a vector of column indices: [,j]
#' @param values a vector of the values for each (non-zero) cell: [i,j] = value
#' @return a sparse matrix of the dgTMatrix class (\code{\link{Matrix}} package) 
#' @export
cast.sparse.matrix <- function(rows, columns, values=NULL) {
  if(is.null(values)) values = rep(1, length(rows))
  d = data.frame(rows=rows, columns=columns, values=values)
  if(nrow(d) > nrow(unique(d[,c('rows','columns')]))){
    message('(Duplicate row-column matches occured. Values of duplicates are added up)')
    d = aggregate(values ~ rows + columns, d, FUN='sum')
  }
  unit_index = unique(d$rows)
  char_index = unique(d$columns)
  sm = spMatrix(nrow=length(unit_index), ncol=length(char_index),
                match(d$rows, unit_index), match(d$columns, char_index), d$values)
  rownames(sm) = unit_index
  colnames(sm) = char_index
  sm
}

#' Create a document term matrix from a list of tokens
#' 
#' Create a \code{\link{DocumentTermMatrix}} from a list of document ids, terms, and frequencies. 
#' 
#' @param documents a vector of document names/ids
#' @param terms a vector of words of the same length as documents
#' @param freqs a vector of the frequency a a term in a document
#' @return a document-term matrix  \code{\link{DocumentTermMatrix}}
#' @export
dtm.create <- function(documents, terms, freqs=rep(1, length(documents))) {
  # remove NA terms
  d = data.frame(ids=documents, terms=terms, freqs=freqs)
  if (sum(is.na(d$terms)) > 0) {
    warning("Removing ", sum(is.na(d$terms)), "rows with missing term names")
    d = d[!is.na(d$terms), ]
  }
  sparsemat = cast.sparse.matrix(rows=d$ids, columns=d$terms, values=d$freqs)
  as.DocumentTermMatrix(sparsemat, weighting=weightTf)
}

#' Compute some useful corpus statistics for a dtm
#' 
#' Compute a number of useful statistics for filtering words: term frequency, idf, etc.
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
term.statistics <- function(dtm) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]    # get rid of empty rows/columns
  vocabulary = colnames(dtm)
  data.frame(term = vocabulary,
             characters = nchar(vocabulary),
             number = grepl("[0-9]", vocabulary),
             nonalpha = grepl("\\W", vocabulary),
             termfreq = col_sums(dtm),
             docfreq = col_sums(dtm > 0),
             reldocfreq = col_sums(dtm > 0) / nDocs(dtm),
             tfidf = tapply(dtm$v/row_sums(dtm)[dtm$i], dtm$j, mean) * log2(nDocs(dtm)/col_sums(dtm > 0)))
}

#' Compute the chi^2 statistic for a 2x2 crosstab containing the values
#' [[a, b], [c, d]]
chi2 <- function(a,b,c,d) {
  ooe <- function(o, e) {(o-e)*(o-e) / e}
  tot = 0.0 + a+b+c+d
  a = as.numeric(a)
  b = as.numeric(b)
  c = as.numeric(c)
  d = as.numeric(d)
  (ooe(a, (a+c)*(a+b)/tot)
   +  ooe(b, (b+d)*(a+b)/tot)
   +  ooe(c, (a+c)*(c+d)/tot)
   +  ooe(d, (d+b)*(c+d)/tot))
}

#' Compare two corpora
#' 
#' Compare the term use in corpus dtm with a refernece corpus dtm.ref, returning relative frequencies
#' and overrepresentation using various measures
#' 
#' @param dtm.x the main document-term matrix
#' @param dtm.y the 'reference' document-term matrix
#' @param smooth the smoothing parameter for computing overrepresentation
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
corpora.compare <- function(dtm.x, dtm.y, smooth=.001) {
  freqs = term.statistics(dtm.x)[, c("term", "termfreq")]
  freqs.rel = term.statistics(dtm.y)[, c("term", "termfreq")]
  f = merge(freqs, freqs.rel, all=T, by="term")    
  f[is.na(f)] = 0
  f$relfreq.x = f$termfreq.x / sum(freqs$termfreq)
  f$relfreq.y = f$termfreq.y / sum(freqs.rel$termfreq)
  f$over = (f$relfreq.x + smooth) / (f$relfreq.y + smooth)
  f$chi = chi2(f$termfreq.x, f$termfreq.y, sum(f$termfreq.x) - f$termfreq.x, sum(f$termfreq.y) - f$termfreq.y)
  f
}

#' Plot a word cloud from a dtm
#' 
#' Compute the term frequencies for the dtm and plot a word cloud with the top n topics
#' You can either supply a document-term matrix or provide terms and freqs directly
#' (in which case this is an alias for wordcloud::wordcloud with sensible defaults)
#' 
#' @param dtm the document-term matrix
#' @param nterms the amount of words to plot (default 100)
#' @param freq.fun if given, will be applied to the frequenies (e.g. sqrt)
#' @param terms the terms to plot, ignored if dtm is given
#' @param freqs the frequencies to plot, ignored if dtm is given
#' @param scale the scale to plot (see wordcloud::wordcloud)
#' @param min.freq the minimum frquency to include (see wordcloud::wordcloud)
#' @param rot.per the percentage of vertical words (see wordcloud::wordcloud)
#' @param pal the colour model, see RColorBrewer
#' @export
dtm.wordcloud <- function(dtm=NULL, nterms=100, freq.fun=NULL, terms=NULL, freqs=NULL, scale=c(6, .5), min.freq=1, rot.per=.15, pal=brewer.pal(6,"YlGnBu")) {
  if (!is.null(dtm)) {
    t = term.statistics(dtm)
    terms = t$term
    freqs = t$termfreq
  }
  if (!is.null(nterms)) {
    terms = terms[1:nterms] 
    freqs = freqs[1:nterms]
  }
  if (!is.null(freq.fun)) freqs = freq.fun(freqs)
   
  if (is.null(terms) | is.null(freqs)) stop("Please provide dtm or terms and freqs")
  wordcloud(terms, freqs, 
          scale=scale, min.freq=min.freq, max.words=Inf, random.order=FALSE, 
          rot.per=rot.per, colors=pal)
}
#' Cast data.frame to sparse matrix
#' 
#' Create a sparse matrix from matching vectors of row indices, column indices and values
#' 
#' @param rows a vector of row indices: [i,]
#' @param columns a vector of column indices: [,j]
#' @param values a vector of the values for each (non-zero) cell: [i,j] = value
#' @return a sparse matrix of the dgTMatrix class (\code{\link{Matrix}} package) 
#' @export
cast.sparse.matrix <- function(rows, columns, values=NULL) {
  if(is.null(values)) values = rep(1, length(rows))
  d = data.frame(rows=rows, columns=columns, values=values)
  if(nrow(d) > nrow(unique(d[,c('rows','columns')]))){
    message('(Duplicate row-column matches occured. Values of duplicates are added up)')
    d = aggregate(values ~ rows + columns, d, FUN='sum')
  }
  unit_index = unique(d$rows)
  char_index = unique(d$columns)
  sm = spMatrix(nrow=length(unit_index), ncol=length(char_index),
                match(d$rows, unit_index), match(d$columns, char_index), d$values)
  rownames(sm) = unit_index
  colnames(sm) = char_index
  sm
}

#' Create a document term matrix from a list of tokens
#' 
#' Create a \code{\link{DocumentTermMatrix}} from a list of document ids, terms, and frequencies. 
#' 
#' @param documents a vector of document names/ids
#' @param terms a vector of words of the same length as documents
#' @param freqs a vector of the frequency a a term in a document
#' @return a document-term matrix  \code{\link{DocumentTermMatrix}}
#' @export
dtm.create <- function(documents, terms, freqs=rep(1, length(documents))) {
  # remove NA terms
  d = data.frame(ids=documents, terms=terms, freqs=freqs)
  if (sum(is.na(d$terms)) > 0) {
    warning("Removing ", sum(is.na(d$terms)), "rows with missing term names")
    d = d[!is.na(d$terms), ]
  }
  sparsemat = cast.sparse.matrix(rows=d$ids, columns=d$terms, values=d$freqs)
  as.DocumentTermMatrix(sparsemat, weighting=weightTf)
}

#' Compute some useful corpus statistics for a dtm
#' 
#' Compute a number of useful statistics for filtering words: term frequency, idf, etc.
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
term.statistics <- function(dtm) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]    # get rid of empty rows/columns
  vocabulary = colnames(dtm)
  data.frame(term = vocabulary,
             characters = nchar(vocabulary),
             number = grepl("[0-9]", vocabulary),
             nonalpha = grepl("\\W", vocabulary),
             termfreq = col_sums(dtm),
             docfreq = col_sums(dtm > 0),
             reldocfreq = col_sums(dtm > 0) / nDocs(dtm),
             tfidf = tapply(dtm$v/row_sums(dtm)[dtm$i], dtm$j, mean) * log2(nDocs(dtm)/col_sums(dtm > 0)))
}

#' Compute the chi^2 statistic for a 2x2 crosstab containing the values
#' [[a, b], [c, d]]
chi2 <- function(a,b,c,d) {
  ooe <- function(o, e) {(o-e)*(o-e) / e}
  tot = 0.0 + a+b+c+d
  a = as.numeric(a)
  b = as.numeric(b)
  c = as.numeric(c)
  d = as.numeric(d)
  (ooe(a, (a+c)*(a+b)/tot)
   +  ooe(b, (b+d)*(a+b)/tot)
   +  ooe(c, (a+c)*(c+d)/tot)
   +  ooe(d, (d+b)*(c+d)/tot))
}

#' Compare two corpora
#' 
#' Compare the term use in corpus dtm with a refernece corpus dtm.ref, returning relative frequencies
#' and overrepresentation using various measures
#' 
#' @param dtm.x the main document-term matrix
#' @param dtm.y the 'reference' document-term matrix
#' @param smooth the smoothing parameter for computing overrepresentation
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
corpora.compare <- function(dtm.x, dtm.y, smooth=.001) {
  freqs = term.statistics(dtm.x)[, c("term", "termfreq")]
  freqs.rel = term.statistics(dtm.y)[, c("term", "termfreq")]
  f = merge(freqs, freqs.rel, all=T, by="term")    
  f[is.na(f)] = 0
  f$relfreq.x = f$termfreq.x / sum(freqs$termfreq)
  f$relfreq.y = f$termfreq.y / sum(freqs.rel$termfreq)
  f$over = (f$relfreq.x + smooth) / (f$relfreq.y + smooth)
  f$chi = chi2(f$termfreq.x, f$termfreq.y, sum(f$termfreq.x) - f$termfreq.x, sum(f$termfreq.y) - f$termfreq.y)
  f
}
REBOL [
	Title:	 "Red/System ELF format emitter"
	Author:  "Andreas Bolka, Nenad Rakocevic"
	File:	 %ELF.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Andreas Bolka, Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; NOTE: all "offsets" are offsets into the file (as stored on disk),
;; all "addresses" are virtual addresses (of the process in memory).

context [
	defs: compose [
		;; Required by the linker.
		extensions [
			exe %""
			obj %.o
			lib %.a
			dll %.so
		]

		;; Target-specific Defaults (job-overridable)

		base-address	(to-integer #{08048000})
		page-size		4096

		;; ELF Constants

		elfclass32		1			;; 32-bit object

		elfdata2lsb		1			;; 2's-complement, little endian

		ev-current		1			;; the "current" version we're adhering to

		et-exec			2			;; executable file
		et-dyn			3			;; shared object file

		em-386			3			;; intel 80386
		em-arm			40			;; ARM

		pt-load			1			;; loadable segment
		pt-dynamic		2			;; dynamic linking information
		pt-interp		3			;; dynamic linker ("interpreter") path name
		pt-phdr			6			;; program header table

		pf-x			1			;; executable segment
		pf-w			2			;; writable segment
		pf-r			4			;; readable wegment

		shn-undef		0			;; undefined section

		sht-null		0			;; inactive section header
		sht-progbits	1			;; program-specific data (w/ file extent)
		sht-symtab		2			;; symbol table (for link editing)
		sht-strtab		3			;; string table
		sht-hash		5			;; symbol hash table
		sht-dynamic		6			;; dynamic linking
		sht-nobits		8			;; program-specific data (w/o file extend)
		sht-rel			9			;; relocations (w/o addends)
		sht-dynsym		11			;; symbol table (dynamic linking)

		;; Processor-specific section type
		sht-arm-exidx			1879048193		;; ARM unwind section
		sht-arm-preemption		1879048194		;; Preempton details
		sht-arm-attributes		1879048195		;; ARM attributes section

		shf-write		1			;; dynamically writable section
		shf-alloc		2			;; dynamically allocated section
		shf-execinstr	4			;; dynamically executable section

		stn-undef		0			;; end of a hash chain (undef symtab nr)

		stb-global		1			;; global symbol

		stt-object		1			;; symbol is a data object
		stt-func		2			;; symbol is a code object

		stv-default		0			;; default symbol visibility

		dt-null			0			;; marks the end of the _DYNAMIC array
		dt-needed		1			;; strtable offset of the name of a library
		dt-hash			4			;; address of the symbol hash table
		dt-strtab		5			;; address of the string table
		dt-symtab		6			;; address of the symbol table
		dt-strsz		10			;; total size of the string table (in bytes)
		dt-syment		11			;; size of one symbol table entry (in bytes)
		dt-init			12			;; address of the initialization function
		dt-fini			13			;; address of the termination function
		dt-rel			17			;; address of the relocation table
		dt-relsz		18			;; total size of the relocation table
		dt-relent		19			;; size of one reloc table entry (in bytes)

		r-386-32		1			;; direct 32-bit relocation
		r-386-copy		5			;; copy symbol at runtime

		r-arm-abs32		2			;; direct 32-bit relocation

		stabs-n-undf	0			;; undefined stabs entry
		stabs-n-fun		36			;; function name
		stabs-n-so		100			;; source file name

		arm [
			attributes [
				cpu-raw-name			#{04}
				cpu-name				#{05}
				cpu-arch				#{06}
				cpu-arch-profile		#{07}
				arm-isa-use				#{08}
				thumb-isa-use			#{09}
				fp-arch					#{0A}
				wmmx-arch				#{0B}
				advanced-simd-arch		#{0C}
				abi-pcs-wchar_t			#{12}
				abi-fp-rounding			#{13}
				abi-fp-denormal			#{14}
				abi-fp-exceptions		#{15}
				abi-fp-user-exceptions	#{16}
				abi-fp-number-model		#{17}
				abi-align-needed		#{18}
				abi-align-preserved		#{19}
				abi-enum-size			#{1A}
				abi-hardfp-use			#{1B}
				abi-vfp-args			#{1C}
				abi-wmmx-args			#{1D}
				div-use					#{2C}
			]

			cpu-arch [
				pre-v4				#{00}
				v4					#{01}			;; e.g. SA110
				v4T					#{02}           ;; e.g. ARM7TDMI
				v5T					#{03}           ;; e.g. ARM9TDMI
				v5TE				#{04}           ;; e.g. ARM946E_S
				v5TEJ				#{05}           ;; e.g. ARM926EJ_S
				v6					#{06}           ;; e.g. ARM1136J_S
				v6KZ				#{07}           ;; e.g. ARM1176JZ_S
				v6T2				#{08}           ;; e.g. ARM1156T2F_S
				v6K					#{09}           ;; e.g. ARM1136J_S
				v7					#{0A}          ;; e.g. Cortex A8, Cortex M3
				v6-M				#{0B}          ;; e.g. Cortex M1
				v6S-M				#{0C}          ;; v6_M with the System extensions
				v7E-M				#{0D}          ;; v7_M with DSP extensions
				v8					#{0E}          ;; v8, AArch32
			]

			cpu-arch-profile [
				not-applicable		#{00}		;; pre v7, or cross-profile code
				application			#{41}       ;; 'A' (e.g. for Cortex A8)
				realtime			#{52}       ;; 'R' (e.g. for Cortex R4)
				micro-controller	#{4D}       ;; 'M' (e.g. for Cortex M3)
				system				#{53}       ;; 'S' Application or real-time profile
			]
		]
	]

	;; ELF Structures

	elf-header: make-struct [		;; (Elf32_Ehdr)
		ident-mag0		[char!]		;; 0x7F (EI_MAG0)
		ident-mag1		[char!]		;; "E" (EI_MAG1)
		ident-mag2		[char!]		;; "L" (EI_MAG2)
		ident-mag3		[char!]		;; "F" (EI_MAG3)
		ident-class		[char!]		;; file class
		ident-data		[char!]		;; data encoding
		ident-version	[char!]		;; file version
		ident-osabi		[char!]
		ident-pad1		[integer!]
		ident-pad2		[integer!]
		type			[short]
		machine			[short]
		version			[integer!]
		entry			[integer!]	;; virtual address of program entry point
		phoff			[integer!]	;; file offset to phdr table
		shoff			[integer!]	;; file offset to shdr table
		flags			[integer!]
		ehsize			[short]		;; size-of elf-header
		phentsize		[short]		;; size-of program-header
		phnum			[short]		;; num of "segments" (entries in phdr tab)
		shentsize		[short]		;; size-of section-header
		shnum			[short]		;; num of "sections" (entries in shdr tab)
		shstrndx		[short]		;; shdr table index of .shstrtab section
	] none

	program-header: make-struct [	;; (Elf32_Phdr)
		type			[integer!]
		offset			[integer!]
		vaddr			[integer!]
		paddr			[integer!]
		filesz			[integer!]
		memsz			[integer!]
		flags			[integer!]
		align			[integer!]
	] none

	section-header: make-struct [	;; (Elf32_Shdr)
		name			[integer!]	;; index into .shstrtab
		type			[integer!]
		flags			[integer!]
		addr			[integer!]
		offset			[integer!]
		size			[integer!]
		link			[integer!]
		info			[integer!]
		addralign		[integer!]
		entsize			[integer!]
	] none

	elf-dynamic: make-struct [		;; (Elf32_Dyn)
		tag				[integer!]
		val				[integer!]
	] none

	elf-symbol: make-struct [		;; (Elf32_Sym)
		name			[integer!]	;; symbol strtab index (zero: unnamed sym)
		value			[integer!]	;; absolute value, address, ...
		size			[integer!]	;; associated symbol size (if any)
		info			[char!]		;; symbol type and binding attributes
		other			[char!]		;; symbol visibility
		shndx			[short]		;; section this symbol is associated with
	] none

	elf-relocation: make-struct [	;; (Elf32_Rel)
		offset			[integer!]
		info-sym		[char!]
		info-type		[char!]
		info-unused		[short]
	] none

	stab-entry: make-struct [
		strx			[integer!]
		type			[char!]
		other			[char!]
		desc			[short]
		value			[integer!]
	] none

	machine-word: make-struct [
		value			[integer!]
	] none

	;; ------------------------------------------------------------------------

	;; The macro structure of our generated ELF binaries.
	default-structure: [
		;; Standard metadata:		[type		flags				align]
		segment "rx"				[load		[r x]				page] [
			struct "ehdr"
			segment "phdr"			[phdr	  	[r]					byte]
			segment "interp"		[interp	  	[r]					byte] [
				section ".interp"	[progbits 	[alloc]				byte]
			]
			section ".hash"			[hash	  	[alloc]				word]
			section ".dynstr"		[strtab	  	[alloc]				byte]
			section ".dynsym"		[dynsym	  	[alloc]				word]
			section ".rel.text"		[rel	  	[alloc]				word]
			section ".text"			[progbits 	[alloc execinstr]	word]
		]

		segment "rw"				[load	  	[r w]				page] [
			section ".data"			[progbits 	[write alloc]		word]
			section ".data.rel.ro"	[progbits 	[write alloc]		word]
			segment "dynamic"		[dynamic  	[r w]				word] [
				section ".dynamic"	[dynamic  	[write alloc]		word]
			]
		]

		section ".stab"				[progbits	[]					word]
		section ".stabstr"			[strtab		[]					byte]

		section ".shstrtab"			[strtab	  	[]					byte]
		section ".ARM.attributes"	[arm-attributes []				byte]
		struct "shdr"
	]

	;; The main entry point called from the linker.
	build: func [
		job [object!]
		/local
			base-address dynamic-linker
			libraries imports exports natives
			structure segments sections commands layout
			data-size
			get-address get-offset get-size get-meta get-data set-data
			relro-offset
	] [
		base-address: case [
			job/type = 'dll [0]
			true			[any [job/base-address defs/base-address]]
		]
		dynamic-linker: any [job/dynamic-linker ""]

		set [libraries imports] collect-import-names job
		exports: collect-exports job
		natives: collect-natives job

		structure: copy default-structure

		if job/target <> 'ARM [
			remove-elements structure [".ARM.attributes"]
		]

		if empty? dynamic-linker [
			remove-elements structure [".interp"]
		]

		if empty? imports [
			remove-elements structure [
				".interp"
			]
		]

		if all [empty? imports empty? exports] [
			remove-elements structure [
				".hash"
				".dynstr"
				".dynsym"
				".dynamic"
			]
		]

		unless job/debug? [
			remove-elements structure [".stab" ".stabstr"]
		]

		data-size: size-of job/sections/data/2
		if job/debug? [
			data-size: data-size + linker/get-debug-lines-size job
		]
		if zero? data-size [
			remove-elements structure [".data"]
		]
		
		dynamic-size: calc-dynamic-size job/type job/symbols

		segments: collect-structure-names structure 'segment
		sections: collect-structure-names structure 'section

		commands: compose/deep [
			"rx"			skip (base-address)
			"rw"			skip (defs/page-size)

			".hash"			meta [link ".dynsym"]
			".dynsym"		meta [link ".dynstr" info ".interp"]
			".rel.text"		meta [link ".dynsym" info ".text"]
			".dynamic"		meta [link ".dynstr"]
			".stab"			meta [link ".stabstr"]

			"ehdr"			size elf-header
			"phdr"			size [program-header	length? segments]
			".hash"			size [machine-word		2 + 2 + (length? imports) + ((length? exports) / 2)]
			".dynsym"		size [elf-symbol		1 + (length? imports) + ((length? exports) / 2)]
			".rel.text"		size [elf-relocation	length? imports]
			".data"			size (data-size)
			".data.rel.ro"	size [machine-word		length? imports]
			".dynamic"		size [elf-dynamic		dynamic-size + length? libraries]
			".stab"			size [stab-entry		2 + ((length? natives) / 2)]
			"shdr"			size [section-header	length? sections]

			".interp"		data (to-c-string dynamic-linker)
			".dynstr"		data (to-elf-strtab compose [(libraries) (imports) (extract exports 2)])
			".text"			data (job/sections/code/2)
			".stabstr"		data (to-elf-strtab join ["%_"] extract natives 2)
			".shstrtab"		data (to-elf-strtab sections)
			".ARM.attributes" data (build-arm-attributes job/ABI)
		]

		layout: layout-binary structure commands

		;; In the following section, we try to minimize the global state passed
		;; around. Instead of just passing LAYOUT to all build-* functions, we
		;; try to pass the minimum amount of information necessary. This makes
		;; the dependencies between those builders more explicit.

		get-address: func [name] [layout/:name/address]
		get-offset: func [name] [layout/:name/offset]
		get-size: func [name] [layout/:name/size]
		get-meta: func [name] [layout/:name/meta]
		get-data: func [name] [layout/:name/data]

		has-element: func [name] [found? find/skip layout name 2]

		set-data: func [name builder] [
			if has-element name [
				layout/:name/data: do builder
			]
		]

		set-data "ehdr" [
			build-ehdr
				job/os
				job/target
				job/type
				get-offset "phdr"
				get-offset "shdr"
				get-address ".text"
				segments
				sections
		]

		set-data "phdr"
			[build-phdr map-each segment segments [layout/:segment]]

		set-data ".hash"
			[build-hash compose [(imports) (extract exports 2)]]

		set-data ".dynsym" [
			build-dynsym
				imports
				exports
				get-data ".dynstr"
				get-address ".text"
				section-index-of sections ".text"
				get-address ".data"
				section-index-of sections ".data"
		]

		set-data ".rel.text"
			[build-reltext job/target imports get-address ".data.rel.ro"]

		set-data ".data" [
			if job/debug? [
				linker/build-debug-lines
					job
					get-address ".text"
					machine-word
			]
			job/sections/data/2
		]

		set-data ".data.rel.ro"
			[build-relro imports]

		set-data ".dynamic" [
			build-dynamic
				job/type
				job/symbols
				get-address ".text"
				get-address ".hash"
				get-address ".dynstr" get-size ".dynstr"
				get-address ".dynsym"
				get-address ".rel.text" get-size ".rel.text"
				get-data ".dynstr"
				libraries
		]

		set-data ".stab" [
			build-stab
				get-address ".text"
				get-data ".stabstr"
				natives
		]

		set-data "shdr" [
			build-shdr
				flatten map-each name sections [reduce [name layout/:name]]
				commands
				get-data ".shstrtab"
		]

		;; Resolve data references.
		if has-element ".data" [
			linker/resolve-symbol-refs
				job
				get-data ".text"
				get-data ".data"
				get-address ".text"
				get-address ".data"
				machine-word
		]

		;; Resolve import (library function) references.
		if has-element ".data.rel.ro" [
			relro-offset: get-address ".data.rel.ro"
			if job/PIC? [relro-offset: relro-offset - get-address ".text"]
			resolve-import-refs
				job
				imports
				get-data ".text"
				relro-offset
		]

		;; Concatenate the layout data into the output binary.
		job/buffer: copy #{}
		foreach [name values] layout [
			append job/buffer serialize-data values/data			;; Data
			append job/buffer rejoin array/initial values/pad #{00} ;; Padding
		]
		job/buffer
	]

	;; -- ELF structure builders --

	build-ehdr: func [
		target-os [word!]
		target-arch [word!]
		target-type [word!]
		phdr-offset [integer!]
		shdr-offset [integer!]
		text-address [integer!]
		segment-names [block!]
		section-names [block!]
		/local eh
	] [
		eh: make-struct elf-header none
		eh/ident-mag0:		#"^(7F)"
		eh/ident-mag1:		#"E"
		eh/ident-mag2:		#"L"
		eh/ident-mag3:		#"F"
		eh/ident-class:		defs/elfclass32
		eh/ident-data:		defs/elfdata2lsb
		eh/ident-version:	defs/ev-current
		eh/version:			defs/ev-current
		eh/entry:			text-address
		eh/phoff:			phdr-offset
		eh/shoff:			shdr-offset
		eh/flags:			0
		eh/ehsize:			size-of elf-header
		eh/phentsize:		size-of program-header
		eh/phnum:			length? segment-names
		eh/shentsize:		size-of section-header
		eh/shnum:			1 + length? section-names
		eh/shstrndx:		index? find section-names ".shstrtab"

		;; Target-specific header fields.

		eh/ident-osabi: switch/default target-os [
			FreeBSD      [9]
			Linux        [3]
		]	             [0]

		eh/type: select reduce [
			'exe defs/et-exec
			'dll defs/et-dyn
		] target-type

		switch target-arch [
			ia-32	[
				eh/machine: defs/em-386
			]
			arm		[
				eh/machine: defs/em-arm
				eh/flags: to-integer #{05000002} ;; EABI v5
			]
		]

		eh
	]

	build-phdr: func [segments [block!] /local ph] [
		map-each segment segments [
			ph: make-struct program-header none
			ph/type:		lookup-def "pt-" segment/meta/type
			ph/offset:		segment/offset
			ph/vaddr:		segment/address
			ph/paddr:		segment/address
			ph/filesz:		segment/size
			ph/memsz:		segment/size
			ph/flags:		lookup-flags "pf-" segment/meta/flags
			ph/align:		lookup-align segment/meta/align
			ph
		]
	]

	build-hash: func [symbols [block!] /local nsymbols] [
		;; @@ Document lookup algorithm?
		nsymbols: length? symbols
		map-each value collect [
			;; nbucket
			keep 1
			;; nchain
			keep nsymbols + 1
			;; bucket[0] = 1 if nsymbols>0 else 0
			keep min nsymbols 1
			;; chain[0] = undef
			keep defs/stn-undef
			;; chain[i:1..nsymbols-1] = i+1
			for i 2 nsymbols 1 [
				keep i
			]
			;; chain[nsymbols] = undef if nsymbols>0 (else omit)
			if nsymbols > 0 [
				keep defs/stn-undef
			]
		] [
			make-struct machine-word reduce [value]
		]
	]

	build-dynsym: func [
		imports [block!]
		exports [block!]
		dynstr [binary!]
		text-address [integer!]
		text-index [integer!]
		data-address [integer!]
		data-index [integer!]
		/local result entry export-base export-type export-index
	] [
		result: copy []

		;; Symbol #0: undefined symbol
		append result make-struct elf-symbol none

		foreach symbol imports [
			entry: make-struct elf-symbol none
			entry/name: strtab-index-of dynstr symbol
			entry/value: 0 ;; Unknown, for imported symbols.
			entry/info: to-elf-symbol-info defs/stb-global defs/stt-func
			entry/other: defs/stv-default
			entry/shndx: defs/shn-undef
			append result entry
		]

		foreach [symbol meta] exports [
			set [export-base export-type export-index] case [
				meta/type = 'global [
					reduce [data-address defs/stt-object data-index]
				]
				true [
					reduce [text-address defs/stt-func text-index]
				]
			]
			entry: make-struct elf-symbol none
			entry/name: strtab-index-of dynstr symbol
			entry/value: export-base + meta/offset
			entry/info: to-elf-symbol-info defs/stb-global export-type
			entry/size: meta/size
			entry/other: defs/stv-default
			entry/shndx: export-index
			append result entry
		]

		result
	]

	build-reltext: func [
		target-arch [word!]
		symbols [block!]
		relro-address [integer!]
		/local rel-type result entry
	] [
		rel-type: select reduce [
			'ia-32 defs/r-386-32
			'arm defs/r-arm-abs32
		] target-arch
		result: copy []
		repeat i length? symbols [ ;; 1..n, 0 is undef
			entry: make-struct elf-relocation none
			entry/offset: rel-address-of/index relro-address (i - 1)
			entry/info-sym: rel-type
			entry/info-type: i
			append result entry
		]
		result
	]

	build-relro: func [symbols [block!]] [
		;; @@ Use NOBITS section (filesize 0, memsize n) instead?
		array/initial length? symbols make-struct machine-word none
	]

	build-dynamic: func [
		job-type [word!]
		symbols [hash!]
		text-address [integer!]
		hash-address [integer!]
		dynstr-address [integer!]
		dynstr-size [integer!]
		dynsym-address [integer!]
		reltext-address [integer!]
		reltext-size [integer!]
		dynstr [binary!]
		libraries [block!]
		/local entries spec
	] [
		entries: copy []

		;; One DT_NEEDED for each dynamic library:
		foreach library libraries [
			repend entries ['needed strtab-index-of dynstr library]
		]

		if job-type = 'dll [
			if spec: select symbols '***-dll-entry-point [
				repend entries ['init text-address + spec/2 - 1]
			]
			if spec: select symbols 'on-unload [
				repend entries ['fini text-address + spec/2 - 1]
			]
		]
				
		;; Static _DYNAMIC entries:
		append entries reduce [
			'hash	hash-address
			'strtab	dynstr-address
			'symtab	dynsym-address
			'strsz	dynstr-size
			'syment	size-of elf-symbol
			'rel	reltext-address
			'relsz	reltext-size
			'relent	size-of elf-relocation
			'null	0
		]

		map-each [tag value] entries [
			make-struct elf-dynamic reduce [lookup-def "dt-" tag value]
		]
	]

	build-stab: func [
		text-address [integer!] stabstr [binary!] natives [block!]
		/local r s
	] [
		collect [
			;; The first synthetic entry (required) holds the number of
			;; non-synthetic entries as well as the size of the string table.
			s: make-struct stab-entry none
			s/type: defs/stabs-n-undf
			s/desc: 1 + ((length? natives) / 2)
			s/value: size-of stabstr
			keep s

			;; One source file stab (N_SO) is required before any other stabs.
			s: make-struct stab-entry none
			s/type: defs/stabs-n-so
			s/value: text-address
			s/strx: 1 ;; @@ Use a real source name (instead of "%_")
			keep s

			foreach [name offset] natives [
				s: make-struct stab-entry none
				s/type: defs/stabs-n-fun
				s/value: text-address + offset
				s/strx: strtab-index-of stabstr name
				keep s
			]
		]
	]

	build-shdr: func [
		sections [block!] commands [block!] shstrtab [binary!]
		/local names sh name section
	] [
		names: extract sections 2
		join reduce [
			make-struct section-header none
		] map-each [name section] sections [
			sh: make-struct section-header none
			sh/name:		strtab-index-of shstrtab name
			sh/type:		lookup-def "sht-" section/meta/type
			sh/flags:		lookup-flags "shf-" section/meta/flags
			sh/addr:		section/address
			sh/offset:		section/offset
			sh/size:		section/size
			sh/link:		section-index-of names select section/meta 'link
			sh/info:		section-index-of names select section/meta 'info
			sh/addralign:	lookup-align section/meta/align
			sh/entsize:		find-entry-size commands name
			sh
		]
	]

	build-arm-attributes: func [
		ABI			[word! none!]
		/local section sub-section attributes attrs
	][
		attrs: defs/arm/attributes
		attributes: rejoin [
			attrs/cpu-arch				defs/arm/cpu-arch/v5T
			attrs/arm-isa-use			#{01}			;; yes
			attrs/abi-pcs-wchar_t		#{04}			;; 4 bytes
			attrs/abi-fp-denormal		#{01}			;; needed
			attrs/abi-fp-exceptions		#{01}			;; needed
			attrs/abi-fp-number-model	#{03}			;; IEEE-754
			attrs/abi-align-needed		#{01}			;; 8-byte
			attrs/abi-align-preserved	#{01}			;; 8-byte, except leaf SP
			attrs/abi-enum-size			#{02}			;; at least 32 bits
			attrs/div-use				#{01}			;; not allowed
		]
		if ABI = 'hard-float [
			append attributes rejoin [
				attrs/abi-hardfp-use	#{03}
				attrs/abi-vfp-args		#{01}
			]
		]
		sub-section: rejoin [
			#{01}					;; file tag
			to-bin32 5 + length? attributes
			attributes
		]
		section: rejoin [
			to-binary "aeabi^@"		;; vendor-name
			sub-section
		]
		rejoin [
			#{41}					;; version A
			to-bin32 4 + length? section
			section
		]
	]

	;; -- Job helpers --

	collect-import-names: func [job [object!] /local libraries symbols] [
		libraries: copy []
		symbols: copy []
		foreach [libname libuses] job/sections/import/3 [
			append libraries libname
			foreach [symbol callsites] libuses [
				append symbols symbol
			]
		]
		reduce [libraries symbols]
	]

	collect-exports: func [
		{Collect a list of exported objects: symbol, type, offset and size. As
		the object size is not yet stored in the symbol or exports table, we
		have to compute it here.}
		job [object!]
		/local current-tail code-tail data-tail symbol-offset symbol-size
	] [
		if  not find job/sections 'export [return make block! 0]

		code-tail: length? job/sections/code/2
		data-tail: length? job/sections/data/2
		collect [
			foreach [meta symbol] reverse copy job/symbols [
				catch [
					case [
						find [import native-ref] meta/1 [
							throw 'continue
						]
						'global = meta/1 [
							symbol-offset: meta/2
							symbol-size: data-tail - symbol-offset
							data-tail: symbol-offset
						]
						'native = meta/1 [
							;; Code symbols have 1-based offsets, data symbols
							;; have 0-based offsets in job/symbols ...
							symbol-offset: meta/2 - 1
							symbol-size: code-tail - symbol-offset
							code-tail: symbol-offset
						]
						true [
							make error! reform ["Unhandled symbol type:" meta/1]
						]
					]
					if find job/sections/export/3 symbol [
						keep compose/deep [
							(form symbol) [
								type (meta/1)
								offset (symbol-offset)
								size (symbol-size)
							]
						]
					]
				]
			]
		]
	]

	collect-natives: func [job [object!]] [
		collect [
			foreach [name meta] job/symbols [
				if meta/1 = 'native [
					keep reduce [(join name ":F") (meta/2 - 1)]
				]
			]
		]
	]

	resolve-import-refs: func [
		job [object!] symbols [block!] code [binary!] relro-offset [integer!]
		/local rel
	] [
		rel: make-struct machine-word none
		foreach [libname libimports] job/sections/import/3 [
			foreach [symbol callsites] libimports [
				rel/value: rel-address-of/symbol relro-offset symbols symbol
				foreach callsite callsites [
					change/part at code callsite serialize-data rel size-of rel
				]
			]
		]
	]

	;; -- File structure/file commands helpers --

	remove-elements: func [structure elements /local begin mark name children] [
		parse structure [
			any [
				begin: (children: none)
				word! ;; type
				set name string!
				opt [block!] ;; meta
				opt [set children block!]
				mark: (
					if children [remove-elements children elements]
					if any [find elements name  attempt [empty? children]] [
						mark: remove/part begin mark
					]
				) :mark
			]
		]
	]

	collect-structure-names: func [
		structure [block!] filter [word! block!] /local result type name
	] [
		result: copy []
		parse structure elements-rule: [
			any [
				set type word!
				set name string!
				opt [block!] ;; meta
				(if filter = type [append result name])
				opt [into [elements-rule]]
			]
		]
		result
	]

	find-skip: func [commands [block!] name [string!]] [
		any [select commands reduce [name 'skip] 0]
	]

	find-size: func [commands [block!] name [string!] /local data spec] [
		if data: select commands reduce [name 'data] [
			return size-of data
		]

		if spec: select commands reduce [name 'size] [
			;; size spec variant 1: `value`
			if integer? spec [return spec]

			;; size spec variant 2: `word` (bound)
			if word? spec [return size-of get spec]

			;; size spec variant 3: `[element num-elements]` (bound, unreduced)
			set [element num-elements] reduce spec
			return num-elements * size-of element
		]

		make error! reform ["Unknown node size:" name]
	]

	find-entry-size: func [commands [block!] name [string!] /local spec] [
		;; Items with a `[element num-elements]` size command have an entry
		;; size, everything else does not.
		either block? spec: select commands reduce [name 'size] [
			size-of first reduce spec
		] [
			0
		]
	]

	merge-meta: func [
		commands [block!] name [string!] meta [block!] /local result
	] [
		append
			reduce ['type meta/1 'flags meta/2 'align meta/3]
			any [select commands reduce [name 'meta] []]
	]

	calc-dynamic-size: func [job-type [word!] symbols [hash!] /local size] [
		size: 9
		if job-type = 'dll [
			if find symbols '***-dll-entry-point [
				size: size + 1
			]
			if find symbols 'on-unload [
				size: size + 1
			]
		]
		size
	]

	complete-sizes: func [
		structure [block!] commands [block!] /local total size name children
	] [
		;; This could be inlined into LAYOUT-BINARY, but having it explicit as
		;; a second pass makes makes things more clear.
		total: 0
		parse structure [
			any [
				word! ;; type
				set name string!
				opt [block!] ;; meta
				[
					set children block!
					(
						total: total + size: complete-sizes children commands
						repend commands [name 'size size]
					)
				|
					(
						size: find-size commands name
						;; Ensure all leaf nodes are padded to 32-bit multiples.
						if not zero? pad: (4 - (size // 4)) // 4 [ ;; @@ Make alignment target-specific.
							repend commands [name 'pad pad]
						]
						total: total + size + pad
					)
				]
			]
		]
		total
	]

	layout-binary: func [
		{Given a file structure and file layout commands, generate a full file
		"layout". A file layout collects the type, offset, address, size,
		metadata and data for each element in the file's structure.}
		structure [block!] commands [block!]
		/local layout emit offset address elements-rule name type meta size
	] [
		layout: copy []

		emit: func [n t o a s m d /local p] [
			p: any [select commands reduce [name 'pad] 0]
			repend layout [
				n reduce [
					'type t 'offset o 'address a 'size s 'pad p 'meta m 'data d
				]
			]
			p
		]

		offset: 0
		address: 0

		complete-sizes structure commands

		parse structure elements-rule: [
			any [
				(meta: copy [])
				set type word!
				set name string!
				opt [set meta block!]
				(
					address: address + find-skip commands name
					size: find-size commands name
					meta: merge-meta commands name meta
					data: select commands reduce [name 'data]
				)
				[
					into [
						(emit name type offset address size meta data)
						elements-rule
					]
				|
					(
						padding: emit name type offset address size meta data
						address: address + size + padding
						offset: offset + size + padding
					)
				]
			]
		]

		layout
	]

	;; -- Definitions lookup --

	lookup-def: func [prefix [string! word!] suffix [string! word!]] [
		defs/(to-word join prefix suffix)
	]

	lookup-flags: func [prefix [string! word!] flags [block!] /local value] [
		value: 0
		foreach flag flags [
			value: value or lookup-def prefix flag
		]
		value
	]

	lookup-align: func [align [word!]] [
		select reduce [
			'byte 1
			'word size-of machine-word
			'page defs/page-size
		] align
	]

	;; -- Helpers for creating/using ELF structures --

	strtab-index-of: func [strtab [binary!] string [string!]] [
		-1 + index? find strtab to-c-string string
	]

	section-index-of: func [
		sections [block!] section [string! none!] /local pos
	] [
		either pos: find sections section [index? pos] [0]
	]

	rel-address-of: func [
		base [integer!]
		/symbol syms [block!] sym [string!]
		/index ind [integer!]
	] [
		base + ((size-of machine-word) * any [ind (-1 + index? find syms sym)])
	]

	to-c-string: func [data [string! binary!]] [join as-binary data #{00}]

	to-elf-strtab: func [items [block!]] [
		join #{00} map-each item items [to-c-string form item]
	]

	to-elf-symbol-info: func [binding [integer!] type [integer!]] [
		(shift/left binding 4) + (type and 15)
	]

	;; -- Helpers for working with various binary data intermediaries --

	serialize-data: func [data [block! object! binary! none!]] [
		case [
			block? data		[rejoin map-each item data [serialize-data item]]
			struct? data	[form-struct data]
			binary? data	[data]
			none? data		[#{}]
		]
	]

	size-of: func [data [block! object! binary! none!]] [
		length? serialize-data data
	]

	;; -- Misc helpers --

	flatten: func [items] [collect [foreach item items [keep item]]]
]
#' Conduct an aggregate query on amcat
#'
#' This function is similar to using the 'show table' function in AmCAT. It allows you to specify a
#' number of queries and get the number of hits per search term, per period, etc.
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param axis1 The first grouping (break/group by) variable, e.g. year, month, week, day, or medium
#' @param axis2 The second grouping (break/group by) variable, e.g. medium. Do not use a date interval here.
#' @param ... additional arguments to pass to the AmCAT API. 
#' @return A data frame with hits per group
#' @export
amcat.aggregate <- function(conn, queries, labels=queries, sets, axis1=NULL, axis2=NULL, ...) {
  result = NULL
  queries = as.character(queries)
  for (i in 1:length(queries)) {
    if (!is.na(queries[i])) {
      
      r = tryCatch(amcat.getobjects(conn,"aggregate", filters=list(q=queries[i], sets=sets, axis1=axis1, axis2=axis2, ...)),
                   error=function(e) {warning("Error on querying '", labels[i], "': ", e$message); NULL})
      if (is.null(r)) next
      if (nrow(r) > 0) {
        if (names(r)[1] == "count") {
          r$query = labels[i]
          result = rbind(result, r)
        } else {
          warning(paste("Error on querying",labels[i]))
        }
      }
    }
  }  
  # convert axis1 to Date object if needed
  if (!is.null(axis1))
    if (axis1 %in% c("year", "quarter", "month", "week", "day")) result[, axis1] = as.Date(result[, axis1])
  return(result)
}

#' Conduct a query on amcat
#'
#' This function is similar to using the 'show article list' function in AmCAT. It allows you to specify a
#' number of queries and get document metadata and number of hits per document
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param ... additional arguments to pass to the AmCAT API, e.g. extra filters
#' @return A data frame with hits per article
#' @export
amcat.hits <- function(conn, queries, labels=queries, sets, minimal=T, ...) {
  result = NULL
  for (i in 1:length(queries)) {
    q = paste("count", queries[i], sep="#")
    r = tryCatch(amcat.getobjects(conn, "search",filters=list(q=q, col="hits", sets=sets, minimal=minimal, ...)),
                 error=function(e) {warning("Error on querying '", labels[i], "': ", e$message); NULL})
    if (is.null(r)) next    
    if (nrow(r) > 0) {
      r$query = labels[i]
      result = rbind(result, r)
    } else {
      warning(paste("Query",labels[i]," produced no results"))
    }
  }
  return(result)
}
#' Default http server configuration for libuv hook.
#' 
#' @param routes list. A named list of routes, with a handler
#'    function for each route. The first unnamed route will be used
#'    as the root. If none is provided, just a 404 status will be returned.
#' @examples
#' \dontrun{
#'   http_server(list('/ping' = function(params, query) 'Hello world!',
#'                    function(params, query) 'Invalid route.'))
#' }
http_server <- function(routes) {
  function(req) {
    params <- extract_params_from_request(req)
    query  <- extract_query_from_request(req)
    route  <- determine_route(routes, req$PATH_INFO)
    result <- route(params, query)
    if (is.microserver_response(result)) unclass(result)
    else unclass(microserver_response(result))
  }
}


#' Minimal function for opening a socket and accepting/responding to
#' requests.
#'
#' @param routes list. A named list of routes.
#' @param port integer. The default is 8103.
#' @importFrom httpuv startServer stopServer service
#' @export
run_server <- function(routes, port = 8103) {
  # A list of default HTTUPV callbacks
  httpuv_callbacks <- list(
    onHeaders = function(req) { NULL },
    call = http_server(routes),
    onWSOpen = function(ws) {
      # print('opening websocket')
    }
  )

  server_id <- httpuv::startServer("0.0.0.0", port, httpuv_callbacks)
  on.exit({ httpuv::stopServer(server_id) }, add = TRUE)

  repeat {
    httpuv::service(1)
    Sys.sleep(0.001)
  }
}

#' gets the current screen width.
#'
#' It's highly OS specific, I do ignore if it works on OSX

getConsoleWidth <- function() {
  width <- getOption("width", NULL)
  if(is.numeric(width)) {
    width
  } else {
    os <- .Platform$OS.type  
    if ( os  %in% c("unix", "Darwin" )) {
      as.numeric(system('tput cols', intern=TRUE))
    } else {
      return(tryCatch({
        txt <- system('cmd /c "mode con /status | grep  \"Colonne:\"',
                      intern=TRUE)
        txt <- unlist(strsplit(txt, ":"))[2]
        as.numeric(txt)
      }, error = function (err) {
        ## please God forgive me
        80
      }))
    }
  }
}

#' Classe S4 per ProgressBar
#'
#' @name ProgressBar
#' @rdname ProgressBar
#' @aliases ProgressBar-class
#' @title ProgressBar with labels
#' @slot value current value 
#' @slot min minimum value
#' @slot max maximum value
#' @slot char char to use as token for progress
#' @slot width current screen width, autoevaluated
#' @slot time time since the beginning of ProgressBar
#' @exportClass ProgressBar
#' @export ProgressBar
#' @import methods

ProgressBar <- setClass(
  "ProgressBar",
  representation(
    value= "numeric",
    min="numeric",                        
    max="numeric",
    char="character",
    width="numeric",
    time="POSIXct"))


setMethod(
  "initialize",
  signature("ProgressBar"),
  function(.Object, min=0, max=1, char="=") {
    .Object@min <- min
    .Object@max <- max
    .Object@char <- char
    .Object@width <- getConsoleWidth()
    .Object@time <- Sys.time()
    return(.Object)
  })

#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @docType methods
#' @rdname kill-methods



setGeneric(
  "kill",
  function(x){
    standardGeneric("kill")
  })
#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @aliases kill,ProgressBar-method

setMethod(
  "kill",
  signature("ProgressBar"),
  function(x) {
    cat("\n", file = stderr())
    flush.console()
  })

#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @docType methods
#' @rdname update-methods
#' @export

setGeneric(
  "update",
  function(x, value, label="") {
    standardGeneric("update")
  })
#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @export
#' @rdname update
#' @aliases update,ProgressBar,ANY-method

setMethod(
  "update",
  signature("ProgressBar", "ANY"),
  function(x, value, label="") {    
    x@value  <- value
    min <- x@min
    if(value == min) {
      x@time <- Sys.time()
    }    
    max <- x@max
    char <- x@char
    elapsed <- as.numeric(difftime(Sys.time(),  x@time, units="secs"))
    V <- value/elapsed
    eta <- (max - value) / V
    eta <- if(value == min) {
      "--:--"
    } else if(eta > 3600) {
      sprintf("%02i:%02i:%02i", as.integer(floor(eta/3600)),
              as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    } else {
      sprintf("%02i:%02i", as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    }
    
    if (!is.finite(value) || value < min || value > max)
      return()
    
    nw <- nchar(char,"w")
    pad <- 12 + nchar(eta)
    nlabel <- nchar(label)
    width <- trunc(x@width/nw) - pad - nlabel
    nb <- round(width * (value - min)/(max - min))
    pc <- round(100 * (value - min)/(max - min))
    if(nlabel > 0) {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% - %s %s", pc, label, eta)), collapse = ""),
          file = stderr())
    } else {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% %s", pc, eta)), collapse = ""),
          file = stderr())
      
    }
    flush.console()
    invisible(x)
  })
#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list()
IMMA.parameters  <- list()
IMMA.definitions <- list()

# Core section
IMMA.attachments[[100]] <- 'core'

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH')

# For each parameter, provide an array specifying:
#    Its length in characters, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)
#ICOADS attachment
IMMA.attachments[[1]] = 'icoads';
IMMA.parameters[[1]]  = c('BSI','B10','B1','DCK','SID','PT',
                          'DUPS','DUPC','TC','PB','WX','SX',
			  'C2','SQZ','SQA','AQZ','AQA','UQZ',
			  'UQA','VQZ','VQA','PQZ','PQA','DQZ',
			  'DQA','ND','SF','AF','UF','VF','PF',
			  'RF','ZNC','WNC','BNC','XNC','YNC',
			  'PNC','ANC','GNC','DNC','SNC','CNC',
			  'ENC','FNC','TNC','QCE','LZ','QCZ')
IMMA.definitions[[1]] = list(
    'BSI'  = list( 1, NULL,  NULL,  NULL, NULL, 1., 1 ),
    'B10'  = list( 3, 1.,    648.,  NULL, NULL, 1., 1 ),
    'B1'   = list( 2, 0.,    99.,   NULL, NULL, 1., 1 ),
    'DCK'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'SID'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'PT'   = list( 2, 0.,    15.,   NULL, NULL, 1., 1 ),
    'DUPS' = list( 2, 0.,    14.,   NULL, NULL, 1., 1 ),
    'DUPC' = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'TC'   = list( 1, 0.,    1.,    NULL, NULL, 1., 1 ),
    'PB'   = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'WX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'SX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'C2'   = list( 2, 0.,    40.,   NULL, NULL, 1., 1 ),
    'SQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'SQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'AQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'AQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'UQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'UQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'VQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'VQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'PQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'PQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'DQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'DQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'ND'   = list( 1, 1.,    2.,    NULL, NULL, 1., 1 ),
    'SF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'AF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'UF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'VF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'PF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'RF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'ZNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'WNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'BNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'XNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'YNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'PNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ANC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'GNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'DNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'SNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'CNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ENC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'FNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'TNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'QCE'  = list( 2, 0.,    63.,   NULL, NULL, 1., 1 ),
    'LZ'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'QCZ'  = list( 2, 0.,    31.,   NULL, NULL, 1., 1 )
)
# IMMT2 attachment
IMMA.attachments[[2]] = 'immt2'
IMMA.parameters[[2]]  = c('OS','OP','FM','IX','W2','SGN',
                          'SGT','SGH','WMI','SD2','SP2',
			  'SH2','IS','ES','RS','IC1','IC2',
			  'IC3','IC4','IC5','IR','RRR','TR',
			  'QCI','QI1','QI2','QI3','QI4',
			  'QI5','QI6','QI7','QI8','QI9',
			  'QI10','QI11','QI12','QI13','QI14',
			  'QI15','QI16','QI17','QI18','QI19',
			  'QI20','QI21','HDG','COG','SOG',
			  'SLL','SLHH','RWD','RWS')
IMMA.definitions[[2]] = list(
    'OS'   = list( 1, 0.,   6.,   NULL,  NULL,  1.,  1 ),
    'OP'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'FM'   = list( 2, 0.,   8.,   NULL,  NULL,  1.,  1 ),
    'IX'   = list( 1, 1.,   7.,   NULL,  NULL,  1.,  1 ),
    'W2'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGN'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGT'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'SGH'  = list( 2, 0.,   50.,  56.,   99.,   1.,  1 ),
    'WMI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SD2'  = list( 2, 0.,   38.,  NULL,  NULL,  1.,  1 ),
    'SP2'  = list( 2, 0.,   30.,  99.,   99.,   1.,  1 ),
    'SH2'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'IS'   = list( 1, 1.,   5.,   NULL,  NULL,  1.,  1 ),
    'ES'   = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'RS'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'IC1'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC2'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC3'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC4'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC5'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IR'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'RRR'  = list( 3, 0.,   999., NULL,  NULL,  1.,  1 ),
    'TR'   = list( 1, 1.,   9.,   NULL,  NULL,  1.,  1 ),
    'QCI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI1'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI2'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI3'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI4'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI5'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI6'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI7'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI8'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI9'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI10' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI11' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI12' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI13' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI14' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI15' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI16' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI17' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI18' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI19' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI20' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI21' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'HDG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'COG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'SOG'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLL'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLHH' = list( 3, -99., 99.,  NULL,  NULL,  1.,  1 ),
    'RWD'  = list( 3, 1.,   362., NULL,  NULL,  1.,  1 ),
    'RWS'  = list( 3, 0.0,  99.9, NULL,  NULL,  0.1, 1 )
)
# Model quality control attachment
IMMA.attachments[[3]] = 'mqc';
IMMA.parameters[[3]]  = c('CCCC','BUID','BMP','BSWU','SWU',
                          'BSWV','SWV','BSAT','BSRH','SRH',
			  'SIX','BSST','MST','MSH','BY',
			  'BM','BD','BH','BFL')
IMMA.definitions[[3]] = list(
    'CCCC' = list( 4, 65.,   90.,    NULL,  NULL,  NULL,  3 ),
    'BUID' = list( 6, 48.,   57.,    65.,   90.,   NULL,  3 ),
    'BMP'  = list( 5, 870.0, 1074.6, NULL,  NULL,  0.1,   1 ),
    'BSWU' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWU'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSWV' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWV'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSAT' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSRH' = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SRH'  = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SIX'  = list( 1, 2.,    3.,     NULL,  NULL,  1.,    1 ),
    'BSST' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'MST'  = list( 1, 0.,    9.,     NULL,  NULL,  1.,    1 ),
    'MSH'  = list( 3, 0.,    999.,   NULL,  NULL,  1.,    1 ),
    'BY'   = list( 4, 0.,    9999.,  NULL,  NULL,  1.,    1 ),
    'BM'   = list( 2, 1.,    12.,    NULL,  NULL,  1.,    1 ),
    'BD'   = list( 2, 1.,    31.,    NULL,  NULL,  1.,    1 ),
    'BH'   = list( 2, 0.,    23.,    NULL,  NULL,  1.,    1 ),
    'BFL'  = list( 2, 0.,    99.,    NULL,  NULL,  1.,    1 )
)
# Metadata attachment
IMMA.attachments[[4]] = 'metadata'
IMMA.parameters[[4]]  = c('C1M','OPM','KOV','COR','TOB','TOT',
                          'EOT','LOT','TOH','EOH','SIM','LOV',
			  'DOS','HOP','HOT','HOB','HOA','SMF',
			  'SME','SMV')
IMMA.definitions[[4]] = list(
    'C1M' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'OPM' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'KOV' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'COR' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'TOB' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOT' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOH' = list( 1, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOH' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'SIM' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOV' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'DOS' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'HOP' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOT' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOB' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOA' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'SMF' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SME' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SMV' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 )
)
# Historical attachment
IMMA.attachments[[5]] = 'historical'
IMMA.parameters[[5]]  = c('WFI','WF','XWI','XW','XDI','XD',
                       'SLPI','TAI','TA','XNI','XN')
IMMA.definitions[[5]] = list(
    'WFI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'WF'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XWI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XW'   = list( 3, NULL,  NULL,  NULL,  NULL,  0.1,   1 ),
    'XDI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XD'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SLPI' = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TAI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TA'   = list( 4, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XNI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XN'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 )
)
# Supplemental attachment
IMMA.attachments[[99]] = 'supplemental'
IMMA.parameters[[99]]  = c('SUPD')
IMMA.definitions[[99]] = list(
    'SUPD' = list( NULL,  NULL,  NULL,  NULL,  NULL,  NULL,  3 )
)

#' Find out which attachment a parameter is in
#'
#' IMMA data are divided into core parameters and optional attachments
#' this function gives the attachment number of a parameter name.
#'
#' Attachment 100 is core. 
#'
#' @export
#' @param parameter - Name of parameter to be found
#' @return the number of the attachment containing that parameter.
IMMA.whichAttachment <- function(parameter) {
    for(i in c(100,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

#' Check the value for a parameter is inside its acceptable range(s)
#'
#' Flags data which is physically impossibe and can't be written in IMMA.
#'
#' The IMMA format constrains the possible ranges of numeric parameters
#'  data outside those ranges can't be written in the format.This function
#'  tests all the data for a selected paramete is inside the acceptable range.
#'
#' @export
#' @param ob Observations data frame.
#' @param parameter - Name of parameter to be tested
#' @return for each observbation, TRUE if within range (or no range defined), FALSE if
#'  outside range.
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[7] == 3 ) {
        return(result); 
    }
  
    w<-which(!is.null(ob[[parameter]]) & !is.na(ob[[parameter]]) &
             ((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] ))
        |    ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= ob[[parameter]] )))
    if(length(w)<length(ob[[parameter]])) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        definitions<-IMMA.definitionsFor(parameter)

        # Treat differently according to type
        if(definitions[7]==3) { # Character, just print
          w<-which(!is.null(ob[[parameter]]))
          if(length(w)>0) {
              if(!is.null(definitions[1])) {
                 Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],ob[[parameter]][w])
              } else {  # Unspecified length, supplementary only - use length of data
                 Result[w]<-sprintf("%s%s",Result[w],ob[[parameter]][w])
              }
          }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
              if(!is.null(definitions[1])) {
                 Result[!w]<-sprintf(sprintf("%%s%%.%ss",definitions[1]),Result[!w],' ')
              } else {  # Unspecified length, supplementary only - use length of data
                 Result<-sprintf("%s%s",Result[!w],' ')
              }
          }
        }
        if(definitions[7]==1) { # Integer - check, scale, round and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             Result[w]<-sprintf(sprintf("%%s%%.%dd",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
        if(definitions[7]==2) { # Base36 - check, scale, convert and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             enc<-IMMA.encode_base36(round)
             Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
      }
    # Done all the parameters, add the ID and length to the start
    # (except for core)
    if ( attachment != 100 ) {
        if ( attachment == 99 ) {
            Result = sprintf(" 0%s",Result)
        } else {
            Result = sprintf("%2d%s",nchar(Result)+4,Result)
        }
        Result = sprintf("%2d%s",attachment,Result)
    }

    return(Result)
  }

# Make a string version of the whole record
IMMA.packString <- function(ob) {
    Result = rep('',length(ob$YR))
    for(attachment in c(100,1,2,3,4,5,99)) {
      w<-IMMA.hasAttachment(ob,attachment)
      if(length(w)>0) {
        Result[w]<-sprintf("%s%s",Result,IMMA.encodeAttachment(ob[w,],attachment))
      }
    }
    return(Result)
}

# Unpack the string version of an attachment into a data frame
IMMA.decodeAttachment <- function(ob.strings,attachment){
   Result<-list()
   pstart<-1
   for ( parameter in IMMA.parameters[[attachment]]) {
      definitions<-IMMA.definitionsFor(parameter)
      if(!is.null(definitions[[1]])) {
         pstring<-substr(ob.strings,pstart,pstart+definitions[[1]]-1)
         pstart<-pstart+definitions[[1]]
         pstring<-sub("^\\s+", "", pstring) # strip leading blanks
      } else { # Special case for variable length supplemental
         pstring<-substring(ob.strings,pstart)
      }
      w<-which(nchar(pstring)==0)        # all blank - set to missing
      
      if(definitions[7]==3) { # Character,add directly
        if(length(w)>0) {
           is.na(pstring[w])<-TRUE
        }
        Result[[parameter]]<-pstring
      }
      if(definitions[7]==2) { # Base36 - convert, scale and add
        pint<-integer(length(pstring))
        if(length(w)>0) {
           is.na(pint[w])<-TRUE
        }
        if(length(w)<length(pint)) {
          pint[-w]<-IMMA.decode_base36(pstring[-w])
        }
        Result[[parameter]]<-pint*definitions[[6]]
      }
      if(definitions[7]==1) { # numeric data - scale and add
        pint<-as.integer(pstring)
        if(length(w)>0) {
           is.na(pint[w])<-TRUE
        }
        Result[[parameter]]<-pint*definitions[[6]]
      }
    }
   return(as.data.frame(Result,stringsAsFactors=FALSE))
}

# Unpack from string format into a data frame
IMMA.unpack <- function(ob.strings) {

   # split the strings into a separate vector for each attachment
   atsplit<-list()
   # Core is always present and first
   atsplit[[100]]<-substr(ob.strings,1,108)
   ob.strings<-substring(ob.strings,109)
   w<-which(nchar(ob.strings)>4)
   while(length(w)>0) {
     att.no<-as.integer(substr(ob.strings[w],1,2))
     att.len<-as.integer(substr(ob.strings[w],3,4))
     for(attachment in c(1,2,3,4,5)) {
        w2<-which(att.no==attachment)
        if(length(w2)>0) {
          atsplit[[attachment]][w][w2]<-substr(ob.strings[w][w2],5,att.len)
          ob.strings[w][w2]<-substring(ob.strings[w][w2],att.len+1)
        }
      }
     attachment<-99 # No set length - use the rest of the string
     w2<-which(att.no==attachment)
     if(length(w2)>0) {
       atsplit[[attachment]][w][w2]<-substring(ob.strings[w][w2],5)
       ob.strings[w][w2]<-''
     }
     w<-which(nchar(ob.strings)>4)
   }

   # Now create the data frame
   Result<-IMMA.decodeAttachment(atsplit[[100]],100)
   for(attachment in  c(1,2,3,4,5,99)) {
     flagName<-sprintf("has.%s",IMMA.attachments[[attachment]])
     Result[[flagName]]<-FALSE
     if(length(atsplit[[attachment]])>0) {
       w<-which(nchar(atsplit[[attachment]])>0)
       Result[[flagName]][w]<-TRUE
       if(length(w)<length(atsplit[[attachment]])) {
         atsplit[[attachment]][!w]<-''
       }
       Result<-cbind(Result,IMMA.decodeAttachment(atsplit[[attachment]],attachment))
     }
   }
   return(Result)
}


#' Read in all the IMMA records from a connection
#'
#' Keeps the data internally in a data frame - size
#'  depends on which attachments are present in the source.
#'
#' Currently only supports IMMA0 format.
#'
#' @export
#' @param con Connection to read data from - or string, see readLines().
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
   l<-readLines(con=con,n=n)
   return(IMMA.unpack(l))
}
  
library(zoo)
library(Matrix)
library(tm)

#' Call a frog (Dutch lemmatizer and dependency parser) instance running in daemon mode
#' 
#' See http://ilk.uvt.nl/frog/
#' To install frog and run as daemon (assuming debian/ubuntu), run:
#' $ sudo apt-get install frog frogdata ucto
#' $ frog -S 9772
#' 
#' A separate call to frog is made for each text in the text input vector.
#' 
#' Note that if something is wrong, it is quite possible that this function will totall hang
#' your R session as it is waiting for output on the socket, so use with caution!
#' 
#' @param text: The text(s) to parse
#' @param host: The hostname for the frog server
#' @param port: The port the frog server is listening on
#' @param verbose: If true, output a message for each document
#' @return a data frame of tokens with columns for lemma, pos, etc 
#' @export
call_frog <- function(text, host="localhost", port=9772, verbose=T) {
  # establish connection and add finalizing code
  socket <- make.socket(host, port)
  on.exit(close.socket(socket))
  # call frog, ending with EOT
  result <- NULL
  for (i in 1:length(text)) {
    t = text[i]
    if (verbose) message("Frogging document ",i,": ", nchar(t), " characters")
    tokens = do_call_frog(socket, t)
    tokens$docid = i
    result = rbind(result, tokens)
  }
  result[, c(ncol(result), ncol(result)-1, 1:(ncol(result)-2))]
}

#' Do the actual call to frog, returning the data frame
do_call_frog <- function(socket, text) {
  write.socket(socket, text)
  write.socket(socket, "\nEOT\n")
  # read until 'READY' is found
  output <- ""
  while (!grepl("\nREADY\n$", output)) {
    output = paste(output, read.socket(socket), sep="")  
  }
  output = gsub("READY\n$", "", output)
  # read output and label columns
  con <- textConnection(output)
  result = read.csv(con, sep='\t', header=F)
  colnames(result) <- c("position", "word", "lemma", "morph", "pos", "prob",
                        "ner", "chunk", "parse1", "parse2")
  result$majorpos = gsub("\\(.*", "", result$pos)
  
  # assign sentence number by assigning number when position == 1 and filling down into NA cells using zoo::na.locf
  result$sent[result$position == 1] = 1:sum(result$position == 1)
  if(is.na(result$sent[1])) result$sent[1] = 1
  result$sent = na.locf(result$sent)
  
  result
}

#' Create a document term matrix from a token list
#' 
#' @param docs: a vector that identifies to which document a token belongs
#' @param terms: a vector of terms of length equal to docs
#' @param freqs: an optional vector giving the frequency of each term
#' @param weighting: the optional weighting for tm (default: term frequency)
#' @return an object of type DocumentTermMatrix (from the tm package)
#' @export
create_dtm <- function(docs, terms, freqs=rep(1, length(terms)), weighting=weightTf) {
  d = data.frame(doc=docs, term=terms, freq=freqs)
  d = aggregate(freq ~ doc + term, d, FUN='sum')
  docnames = unique(d$doc)
  termnames = unique(d$term)
  sm = spMatrix(nrow=length(docnames), ncol=length(termnames),
                match(d$doc, docnames), match(d$term, termnames), d$freq)
  rownames(sm) = docnames
  colnames(sm) = termnames
  as.DocumentTermMatrix(sm, weighting=weighting)
}


REBOL [
	Title:		"Red/System ARM code emitter"
	Author:		"Andreas Bolka, Nenad Rakocevic"
	File:		%ARM.r
	Tabs:	 4
	Rights:		"Copyright (C) 2011-2012 Andreas Bolka, Nenad Rakocevic. All rights reserved."
	License:	"BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

make-profilable make target-class [
	target:				'ARM
	little-endian?:		yes
	struct-align-size:	4
	ptr-size:			4
	default-align:		4
	stack-width:		4
	stack-slot-max:		8							;-- size of biggest datatype on stack (float64!)
	args-offset:		8							;-- stack frame offset to arguments (fp + lr)
	branch-offset-size:	4							;-- size of branch instruction
	locals-offset:		4							;-- offset from frame pointer to local variables (catch ID + addr)
	insn-size:			4

	
	need-divide?: 		none						;-- if TRUE, include division routine in code
	div-sym:			'_div_
	
	conditions: make hash! [
	;-- name ----------- signed --- unsigned --
		overflow?		 #{60}		-
		not-overflow?	 #{70}		-	
		=				 #{00}		-
		<>				 #{10}		-
		signed?			 -			-
		unsigned?		 -			-
		even?			 -			-
		odd?			 -			-
		<				 #{b0}		#{30}
		>=				 #{a0}		#{20}
		<=				 #{d0}		#{90}
		>				 #{c0}		#{80}
	]
	
	byte-flag: 			#{00400000}					;-- trigger byte access in opcode
	
	pools: context [								;-- literals pools management
		active?:	  no							;-- yes => store in pools, no => store inlined
		values:		  make block! 2000				;-- [value instruction-pos sym-spec ...]
		entry-points: make block! 100				;-- insertion points candidates for pools between functions
		ins-points:	  make block! 100				;-- insertion points candidates for pools inlined in code
		pools:		  make block! 1					;-- [pool-pos [value-ref ...] inline? ...]
		limit:		  4088							;-- reachability max distance (insn<->pool, 4092 - insn - branching)
		verbose:	  0								;-- if > 0, output debug logs
		
		pools-stats: has [list][
			print "--- Pools:"
			list: pools
			forskip list 3 [
				print ["pos:" list/1 ", literals:" length? list/2]
			]
			print "---"
		]
		
		;-- Collect a literal value to be stored in a pool
		collect: func [value [integer!] /spec s [word! get-word! block!] /with opcode [binary!] /local pos][
			either active? [
				insert pos: tail values reduce [value emitter/tail-ptr s]
				emit-reloc-addr/only next pos
				emit-i32 any [opcode #{e59f0000}]
				pos
			][
				emit-i32 any [opcode #{e59f0000}]	;-- LDR r0, [pc, #0]	; offset 0 => value
				emit-i32 #{ea000000}				;-- B <after_value>
				if spec [
					spec: switch type?/word s [
						get-word! [emitter/get-symbol-ref to word! s]
						word!	  [emitter/symbols/:s]
						block!	  [s]
					]
					
					emit-reloc-addr spec/3
				]				
				emit to-bin32 value					;-- emit value
			]
		]
		
		;-- Collect a possible position in code for a literals pool
		mark-entry-point: func [name][
			if verbose > 0 [print ["new entry-point:" emitter/tail-ptr "(after" name #")"]]
			
			append entry-points emitter/tail-ptr
		]
		
		mark-ins-point: has [pos][
			pos: emitter/tail-ptr
			if pos <> pick tail ins-points -1 [append ins-points pos]
		]
		
		insert-jmp-point: func [idx [integer!] offset [integer!]][			
			update-values-index idx 4				;-- move values references by 4 bytes
			update-entry-points idx 4				;-- move entry-points by 4 bytes
		]
		
		get-pool: does [all [not empty? pools skip tail pools -3]]
		
		make-pool: func [/ins /local bound base list pool refs][
			if all [
				not ins
				(entry-points/1 - first any [get-pool [1]]) >= limit
			][
				ins: true
			]
			list: either ins [ins-points][entry-points]
			
			if all [
				not empty? pools
				empty? second pool: get-pool	;-- remove last pool if empty
			][
				clear pool
			]
			either ins [
				base: ins-points/1				;-- start search on first available insertion point
				while [list/1 - base < limit][	;-- search farthest reachable point (accounting for fake entry)
					list: next list
				]
				list: back list					;-- limit exceeded, back to last reachable
			][
				unless empty? pools [
					bound: second last second get-pool	;-- start search after last stored literal entry position in code
					while [list/1 < bound][
						list: next list
					]
					if tail? list [
						compiler/throw-error "[ARM emitter] suitable pool position not found!"
					]
				]
			]
				
			if verbose > 0 [print ["^/* making a new pool, at:" list/1 ", inlined?:" ins]]
			
			repend pools [list/1 refs: make block! 50 to logic! ins]	;-- create a new pool entry
			
			either ins [
				remove/part ins-points next list	;-- clear all ins-points before pool position
				repend/only refs [0 0 none]			;-- insert fake literal in pool (place-holder for B insn) 
			][
				entry-points: next list				;-- move to next possible position
			]
			get-pool								;-- return a reference on the last pool structure
		]
				
		update-values-index: func [idx [integer!] offset [integer!]][		
			forskip values 3 [			
				if values/2 >= idx [values/2: values/2 + offset]
			]			
		]
		
		;-- Update functions entry points after a pool insertion
		update-entry-points: func [pool-idx [integer!] offset [integer!] /strict /local refs comp ep][
			comp: get pick [greater? greater-or-equal?] to logic! strict
			
			ep: head entry-points
			forall ep [if comp ep/1 pool-idx [ep/1: ep/1 + offset]]
			
			forskip pools 3 [if comp pools/1 pool-idx [pools/1: pools/1 + offset]]

			foreach [name spec] emitter/symbols [	;-- move functions entry-points and references
				if find [native native-ref] spec/1 [
					if all [spec/2 spec/2 >= pool-idx][spec/2: spec/2 + offset]
					unless empty? refs: spec/3 [
						forall refs [if refs/1 >= pool-idx [refs/1: refs/1 + offset]]
					]
				]
			]
		]

		;-- Update functions entry points after a pool insertion
		update-refs-part: func [floor [integer!] ceil [integer!] offset [integer!] /local refs ep ip][
			forskip values 3 [
				if values/2 - 4 > ceil [break]
				if values/2 - 4 >= floor [values/2: values/2 + offset]
			]
			values: head values
			
			ep: head entry-points
			forall ep [
				if ep/1 - 4 > ceil [break]
				if ep/1 - 4 > floor [ep/1: ep/1 + offset]
			]

			ip: head ins-points
			forall ip [
				if ip/1 - 4 > ceil [break]
				if ip/1 - 4 > floor [ip/1: ip/1 + offset]
			]

			forskip pools 3 [
				if pools/1 - 4 > ceil [break]
				if pools/1 - 4 > floor [pools/1: pools/1 + offset]
			]
			pools: head pools

			foreach [name spec] emitter/symbols [	;-- move functions entry-points and references
				if find [native native-ref] spec/1 [
					if all [spec/2 spec/2 >= floor spec/2 - 4 < ceil][spec/2: spec/2 + offset]
					unless empty? refs: spec/3 [
						forall refs [
							if refs/1 - 4 > ceil [break]
							if refs/1 - 4 >= floor [refs/1: refs/1 + offset]
						]
					]
				]
			]
		]
		
		find-close-pool: func [pool-idx [integer!] ins-idx [integer!] /local pool][
			pool: find/skip pools pool-idx 3
			until [
				pool: skip pool 3
				if tail? pool [
					if limit > entry-points/1 [return make-pool]	;-- see if next entry-point is reachable
					return make-pool/ins							; @@ temp change
					;compiler/throw-error "[ARM emitter] unable to find a reachable pool!"
				]
				limit > (abs pool/1 + (4 * length? pool/2) - (ins-idx + 8))
			]
			pool
		]
		
		;-- Create literal pools lists and put literals pointers inside according to their distance
		populate-pools: has [index pos offset pool][
			if verbose > 0 [print "^/=== Populate stage ==="]
			
			forskip values 3 [
				index: values/2
				if empty? pools [make-pool]

				pool: get-pool
				pos: pool/1 + (4 * length? pool/2)	;-- pos: offset of value entry in the pool buffer

				offset: pos - index
				if verbose > 0 [prin [offset #" "]]

				either positive? offset [			;-- test if pool is before or after caller
					if limit <= offset [				;-- if pool is too far ahead
						pool: make-pool/ins			;-- make a new pool at next possible insertion position
					]
				][
					if limit <= abs offset [			;-- if pool too far behind,
						pool: make-pool				;-- make a new pool at next possible position @@ > 4088 case
						pos: pool/1
					]
				]
				append/only pool/2 values			;-- insert literal value in the pool
			]
			sort/skip pools 3
		]
		
		;-- Move literal values that became out-of-range to a closer pool
		adjust-pools: has [pool-size value ins-idx spec entry-pos offset][
			if verbose > 0 [print "^/=== Adjust stage ===" pools-stats]
			
			foreach [pool-idx value-refs inline?] pools [
				pool-size: 4 * length? value-refs
				update-values-index pool-idx pool-size
				update-entry-points/strict pool-idx pool-size
			]
		
			foreach [pool-idx value-refs inline?] pools [
				if verbose > 0 [print ["^/processing pool:" pool-idx]]
				if inline? [value-refs: next value-refs]	;-- skip first fake entry (for branch insn)
				
				forall value-refs [		
					set [value ins-idx spec] value-refs/1
					
					entry-pos: 4 * (-1 + index? value-refs)	;-- offset of value entry in the pool
					offset: pool-idx + entry-pos - (ins-idx + 8)	;-- relative jump offset to the entry				
					if verbose > 0 [prin [offset #" "]]
				
					offset:	abs offset

					if offset >= limit [
						pool: find-close-pool pool-idx ins-idx
						if verbose > 0 [print ["^/* out-of-range:" offset ", moving to pool:" pool/1]]
						append/only pool/2 value-refs/1
						remove value-refs
						value-refs: back value-refs

						update-refs-part pool-idx pool/1 -4

						;update-values-index pool-idx -4
						;update-entry-points/strict pool-idx -4
						;
						;update-values-index pool/1 4
						;update-entry-points/strict pool/1 4
					]
				]
			]
		]
		
		;-- Build pools buffers and insert them in native code buffer
		commit-pools: has [buffer value ins-idx spec entry-pos offset code back? buf-size][
			if verbose > 0 [print "^/=== Commit stage ===" pools-stats]
			buffer: make binary! 800						;-- reserve pool buffer for 200 values (average estimate)

			foreach [pool-idx value-refs inline?] pools [
				if verbose > 0 [print ["^/- pool:" pool-idx ", len:" length? value-refs]]
				clear buffer
				
				buf-size: 4 * length? value-refs
				if inline? [
					append buffer reverse rejoin [			;-- B <buf-size>	; branch over the pool buffer
						#{ea} to-bin24 shift buf-size - 8 2
					]
					value-refs: next value-refs				;-- skip place-holder value				
				]
				insert/dup at emitter/code-buf pool-idx null buf-size
				
				forall value-refs [		
					set [value ins-idx spec] value-refs/1
					
					append buffer reverse debase/base to-hex value 16
										
					entry-pos: 4 * (-1 + index? value-refs)	;-- offset of value entry in the pool
					offset: pool-idx + entry-pos - (ins-idx + 8)	;-- relative jump offset to the entry				
					back?: negative? offset 
					if verbose > 0 [prin [offset #" "]]
					
					offset:	abs offset

					if offset >= limit [
						compiler/throw-error "[ARM emitter] adjusting failed!"
					]
					offset: reverse to-12-bit offset
					
					code: at emitter/code-buf ins-idx
					change code offset or copy/part code 4	;-- add relative jump offset to instruction
					if back? [code/3: #"^(7F)" and code/3]	;-- encode a negative offset

					if spec [
						spec: switch type?/word spec [
							get-word! [emitter/get-func-ref to word! spec]
							word!	  [emitter/symbols/:spec]
							block!	  [spec]
						]
						append spec/3 pool-idx + entry-pos	;-- add symbol back-reference for linker
					]
				]
				change at emitter/code-buf pool-idx buffer	;-- insert pool in code buffer
			]
		]
		
		process: does [
			unless empty? values [
				populate-pools
				adjust-pools
				commit-pools
			]	
			clear entry-points: head entry-points
			clear ins-points
			clear values
			clear pools
		]
	]
	
	emit-reloc-addr: func [spec [block!] /only][
		unless only [append spec emitter/tail-ptr]	;-- save reloc position
		unless empty? emitter/chunks/queue [				
			append/only 							;-- record reloc reference
				second last emitter/chunks/queue
				either only [spec][back tail spec]
		]
	]
	
	emit-divide: has [base][
		;-- Unsigned division code is from http://www.virag.si/2010/02/simple-division-algorithm-for-arm-assembler/
		;-- Original routine extended to handle signed division using code from:
		;-- "ARM System Developer's Guide", p.238, ISBN: 1-55860-874-5
		;-- registers usage:
		;-- 	- on entering: r0: dividend, r1: divisor, r4: mode (0: division, 1: modulo, 2: remainder)
		;--		- on exit: r0: quotient, r1: remainder or r0: modulo/remainder
		;--		- registers modified: r0-r3, r5, ip
		
		if verbose >= 3 [print "^/>>>emitting DIVIDE intrinsic"]
		
		base: emitter/tail-ptr
		
		foreach opcode [	
							; .divide	
			#{e3510000}			; CMP r1, #0			; if divisor = 0
			#{092d4000}			; PUSHEQ {lr}			; push calling address for error location
			#{03a0000d}			; MOVEQ r0, #13			; integer divide by zero error code
			#{092d0001}			; PUSHEQ {r0}
			#{0a000000}			; BEQ ***-on-quit		; call runtime error handler
			#{e1500001}			; CMP r0, r1			; if dividend = divisor
			#{0a00000b}			; BEQ .equal
			#{e1a03000}			; MOV r3, r0			; r3: dividend
			#{e1a05001}			; MOV r5, r1			; r5: divisor
			#{e3500000}			; CMP r0, #0			; if dividend < 0
			#{42603000}			; RSBMI r3, r0, #0		;	r3: -dividend
			#{e3510000}			; CMP r1, #0			; if divisor < 0
			#{42615000}			; RSBMI r5, r1, #0		;	r5: -divisor
			#{e3500102}			; CMP r0, #1<<31		; if r3 = -2^31 (special case for -2^31)
			#{0a000006}			; BEQ .ispowerof2		; or
			#{e1530005}			; CMP r3, r5			; if r3 <= divisor
			#{8a000004}			; BHI .ispowerof2			
			#{e1a01000}			; MOV r1, r0			; remainder: dividend
			#{e3a00000}			; MOV r0, #0			; quotient: 0
							; .equal
			#{03a00001}			; MOVEQ r0, #1			; if dividend = divisor, quotient: 1
			#{03a01000}			; MOVEQ r1, #0			;	remainder: 0
			#{ea000024}			; B .divide_end			; jump to remainder epilog
							; .ispowerof2
			#{e2413001}			; SUB r3, r1, #1		; r3: divisor - 1
			#{e1130001}			; TST r3, r1			; if divisor is a power of 2 (divisor & (divisor - 1))
			#{1a00000c}			; BNE .notpowerof2
			#{e1a03000}			; MOV r3, r0			; save dividend
			#{e1a02001}			; MOV r2, r1			; save divisor
							; .powerof2
			#{31a000c0}			; MOVCC r0, r0, ASR#1	; divide by 2 (but not on first pass)
			#{e1b010a1}			; MOVS r1, r1, LSR#1	; until power of 2 reached (carry set)
			#{3afffffc}			; BCC .powerof2
			#{e2621000}			; RSB r1, r2, #0		; 2's complement of divisor
			#{e0031001}			; AND r1, r3, r1		; r1: dividend and -divisor
			#{e0431001}			; SUB r1, r3, r1		; compute remainder = (dividend - (dividend and -divisor))
			#{e3530102}			; CMP r3, #1<<31		; if r3 = -2^31 (special case for -2^31)
			#{0a000017}			; BEQ .divide_end		; 	jump to end
			#{e3530000}			; CMP r3, #0			; if dividend < 0
			#{40411002}			; SUBMI r1, r1, r2		;	adjust remainder (remainder = remainder - divisor)
			#{ea000014}			; B .divide_end
							; .notpowerof2
			#{e1b02001}			; MOVS r2, r1			; r2: divisor
			#{e212c102}			; ANDS ip, r2, #1<<31	; if r2 < 0, ip: #80000000
			#{42622000}			; RSBMI r2, r2, #0		; if r2 < 0, r2: -r2 (2's complement)
			#{e1b01000}			; MOVS r1, r0			; r1: dividend
			#{e03cc041}			; EORS ip, ip, r1 ASR#32 ; if r1 < 0, ip: ip xor r1>>32
			#{22611000}			; RSBCS r1, r1, #0		; if r1 < 0, r1: -r1 (2's complement)
			
			#{e3a00000}			; MOV r0, #0     		; clear R0 to accumulate result
			#{e3a03001}			; MOV r3, #1     		; set bit 0 in R3, which will be shifted left then right
							; .start
			#{e1520001}			; CMP r2, r1
			#{91a02082}			; MOVLS r2, r2, LSL#1	; shift R2 left until it is about to be bigger than R1
			#{91a03083}			; MOVLS r3, r3, LSL#1	; shift R3 left in parallel in order to flag how far we have to go
			#{9afffffb}			; BLS      start
							; .next
			#{e1510002}			; CMP r1, r2      		; carry set if R1>R2 (don't ask why)
			#{20411002}			; SUBCS r1, r1, r2      ; subtract R2 from R1 if this would
														; give a positive answer
			#{20800003}			; ADDCS r0, r0, r3   	; and add the current bit in R3 to
											  			; the accumulating answer in R0.
			#{e1b030a3}			; MOVS r3, r3, LSR#1	; Shift R3 right into carry flag
			#{31a020a2}			; MOVCC r2, r2, LSR#1	; and if bit 0 of R3 was zero, also
												   		; shift R2 right.
			#{3afffff9}			; BCC next				; If carry not clear, R3 has shifted
			
							; .epilog					; back to where it started, and we can end
			#{e1b0c08c}			; MOVS ip, ip, LSL#1	; C: bit 31, N: bit 30
			#{22600000}			; RSBCS	r0, r0, #0		; if C = 1, r0: -r0 (2's complement)
			#{42611000}			; RSBMI	r1, r1, #0		; if N = 1, r1: -r1 (2's complement)								
							; .divide_end				; r0: quotient, r1: remainder
			#{e3340000}			; TEQ r4, #0			; if not modulo/remainder op,
			#{01a0f00e}			; MOVEQ pc, lr			; 	return from sub-routine
			
			;-- Adjust modulo result to be mathematically correct:
			;-- 	if modulo < 0 [
			;--			if divisor < 0 [divisor: negate divisor]
			;--			modulo: modulo + divisor
			;--		]
			#{e1b00001}			; MOVS r0, r1			; r0: modulo or remainder
			#{e3340002}			; TEQ r4, #2			; if r1 <> rem,
			#{01a0f00e}			; MOVEQ pc, lr			; 	return from sub-routine
			#{e3500000}			; CMP r0, #0	 		; if r0 >= 0, (modulo)
			#{51a0f00e}			; MOVPL pc, lr			; 	return from sub-routine
			#{e3520000}			; CMP r2, #0	 		; if r2 < 0 (divisor)
			#{41e00000}			; RSBMI	r0, r0, #0		;	r0: -r0 (2's complement)
			#{e0800002}			; ADD r0, r0, r2		; r0: r0 + r2
			#{e1a0f00e}			; MOV pc, lr			; return from sub-routine
 		][
 			emit-i32 opcode
 		]
 		;-- link it with runtime error handler
 		append emitter/symbols/***-on-quit/3 base + (4 * insn-size)
	]
	
	;-- Check if div-sym is not user-defined, else provide a unique replacement symbol
	make-div-sym: has [retry][
		if select emitter/symbols div-sym [
			retry: 3								;-- try 3 times, then spit an error to user face ;)
			until [
				div-sym: to word! rejoin ["_div_" random "0123456798"]
				if zero? retry: retry - 1 [
					compiler/throw-error "Unable to create divide symbol!"
				]
				none? emitter/symbols/:div-sym
			]
		]
		div-sym
	]
	
	call-divide: func [mod? [word! none!] /local refs][
		refs: third either need-divide? [
			emitter/symbols/:div-sym
		][
			div-sym: make-div-sym
			need-divide?: yes
			emitter/add-native div-sym				;-- add an entry for the divide pseudo-function
		]
		
		emit-i32 join #{e3a040} switch/default mod? [ ;-- MOV r4, #0|1|2
			mod [#"^(01)"]							;-- modulo
			rem [#"^(02)"]							;-- remainder
		][null]										;-- division
		
		emit-reloc-addr refs
		emit-i32 #{eb000000}						;-- BL .divide
	]
	
	on-init: does [
		if PIC? [
			emit-i32 #{e1a0900f}					;-- MOV sb, pc
			emit-i32 #{e2499008}					;-- SUB sb, #8
		]
	]
	
	on-finalize: does [
		if need-divide? [
			emitter/symbols/:div-sym/2: emitter/tail-ptr
			emit-divide
		]
		if pools/active? [pools/process]			;-- trigger pools processing on end of code generation
	]
	
	on-global-prolog: func [runtime? [logic!]][
		pools/active?: compiler/job/literal-pool?
		if runtime? [need-divide?: no]
	]
	
	on-global-epilog: func [runtime? [logic!]][
		if all [
			not runtime?
			compiler/job/runtime?
			compiler/job/need-main?
		][
			emit-pop								;-- pop zero padding
			emit-pop								;-- pop CATCH_ALL barrier
			emit-i32 #{e8bd0800}					;-- POP {fp}
			emit-epilog '***_start [] 7 * 4 0		;-- restore all before returning in __libc_start_main()
		]
		unless runtime? [
			pools/mark-entry-point 'global			;-- add end of global code section as pool entry-point
		]
	]
	
	on-root-level-entry: does [
		pools/mark-ins-point
	]
	
	count-floats: func [spec [block!] /local cnt][
		cnt: 0
		parse spec [any [into ['float! | 'float64! | 'float32!] (cnt: cnt + 1) | skip]]		
		cnt
	]
	
	extract-arguments: func [spec [block!] /local cnt][
		spec: copy spec
		clear find spec first [return:]
		clear find spec /local
		if string? spec/1 [remove spec]
		if block?  spec/1 [remove spec]
		remove-each value spec [not block? value]
		head reverse spec
	]
	
	arguments-on-stack?: func [args [block!] /cdecl /local total][
		total: 0
		forall args [
			if args/1 <> #_ [						;-- bypass place-holder marker
				total: total + argument-size? args/1 to logic! cdecl
				if total > 16 [return args]
			]
		]
		none
	]
	
	to-bin24: func [v [integer! char!]][
		copy skip debase/base to-hex to integer! v 16 1
	]
	
	;-- Convert a 12-bit integer offset to a 32-bit hexa LE
	to-12-bit: func [offset [integer!]][
		#{00000FFF} and debase/base to-hex offset 16
	]
	
	to-shift-imm: func [value [integer!]][
		reverse to-bin32 shift/left value 7
	]

	instruction-buffer: make binary! 4
	
	f-inc: func [op [binary!] idx [integer!]][
		either zero? idx [op][op or debase/base to-hex shift/left idx 12 16]
	]
	
	;-- Overloaded emit to print reversed binary series for easier reading
	emit: func [bin [binary! char! block!]][
		if verbose >= 4 [print [">>>emitting code:" mold reverse copy bin]]
		append emitter/code-buf bin
	]

	emit-i32: func [bin [binary! char! block!]] [
		;; To allow more natural emission of 32-bit instructions, "emit-i32"
		;; collects data in big-endian and emits it as 32-bit chunks in the
		;; target's native endianness.
		insert tail instruction-buffer bin
		if 4 <= length? instruction-buffer [
			emit to-bin32 to integer! take/part instruction-buffer 4
		]
	]
	
	;-- Polymorphic code generation
	emit-poly: func [opcode [binary!] /with offset [integer!]][
		if with 	 [opcode: opcode or to-12-bit offset]
		if width = 1 [opcode: opcode or byte-flag]	;-- 16-bit access not supported
		emit-i32 opcode
	]
	
	rotate-left: func [value [integer!] bits [integer!]][
		either bits < 4 [
			switch bits [
				0 [value]
				1 [(shift/left value and 255 2) or shift/logical value 30]
				2 [(shift/left value and 16 4) or shift/logical value 28]
				3 [(shift/left value and 3 6) or shift/logical value 26]
			]
		][
			shift/logical value 32 - (bits * 2)		;-- * 2 => rotation on even positions
		]
	]
	
	ror-position?: func [value [integer!] /local c][
		;-- Test if an integer can be represented using the 8-bit + 4-bit-ROR format
		c: 0
		foreach mask [
			255  									;-- 2#{00000000000000000000000011111111}
			-1073741761								;-- 2#{11000000000000000000000000111111}
			-268435441								;-- 2#{11110000000000000000000000001111}
			-67108861								;-- 2#{11111100000000000000000000000011}
			-16777216								;-- 2#{11111111000000000000000000000000}
			1069547520								;-- 2#{00111111110000000000000000000000}
			267386880								;-- 2#{00001111111100000000000000000000}
			66846720								;-- 2#{00000011111111000000000000000000}
			16711680								;-- 2#{00000000111111110000000000000000}
			4177920									;-- 2#{00000000001111111100000000000000}
			1044480									;-- 2#{00000000000011111111000000000000}
			261120									;-- 2#{00000000000000111111110000000000}
			65280									;-- 2#{00000000000000001111111100000000}
			16320									;-- 2#{00000000000000000011111111000000}
			4080									;-- 2#{00000000000000000000111111110000}
			1020									;-- 2#{00000000000000000000001111111100}
		][
			if value and mask = value [return c]
			c: c + 1
		]
		none
	]

	emit-load-imm32: func [value [integer! char!] /reg n [integer!] /local neg? bits opcode][
		value: to integer! value
		if neg?: negative? value [value: complement value]

		either bits: ror-position? value [	
			opcode: rejoin [						;-- MOVS r0|rN, #imm8, bits	; v = imm8 (ROR bits)x2
				#{e3} 
				pick [#{f0} #{b0}] neg?				;-- emit MVNS instead, if required
				to char! bits
				to char! rotate-left value bits
			]
			if reg [opcode: opcode or debase/base to-hex shift/left n 12 16]
			emit-i32 opcode
		][
			opcode: #{e59f0000}						;-- LDR r0|rN, [pc, #offset]
			if reg [opcode: opcode or debase/base to-hex shift/left n 12 16]
			
			pools/collect/with either neg? [complement value][value] opcode
		]
	]
	
	emit-op-imm32: func [opcode [binary!] value [integer! char!] /local bits][
		opcode: copy opcode
		either bits: ror-position? value: to integer! value [
			opcode/3: (to char! opcode/3) or to char! bits
			opcode/4: to char! rotate-left value bits
		][
			pools/collect/with value #{e59f3000}	;-- LDR r3, [pc, #offset]
			opcode/1: #"^(FD)" and to char! opcode/1
			opcode/4: #"^(03)"
		]
		emit-i32 opcode
	]
	
	emit-float: func [d-code [binary!] s-code [binary!]][
		emit-i32 either width = 8 [d-code][s-code]
	]
	
	emit-load-local: func [opcode [binary!] offset [integer!] /float][
		if negative? offset [
			opcode: copy opcode
			opcode/2: #"^(7F)" and opcode/2			;-- clear bit 23 (U)
		]
		if float [offset: offset / 4]
		offset: to-12-bit abs offset
		;if alt [opcode: opcode or #{00001000}]		;-- use r1 instead of r0 
		emit-i32 opcode or offset
	]
	
	emit-float-variable: func [
		name [word! object!] gcode [binary!] lcode [binary!]
		/local offset
	][
		if object? name [name: compiler/unbox name]

		either offset: select emitter/stack name [	;-- local variable case
			emit-load-local/float lcode offset
		][											;-- global variable case
			pools/collect/spec/with 0 name #{e59f3000}	;-- LDR r3, [pc, #offset]
			if PIC? [emit-i32 #{e0833009}]				;-- ADD r3, sb
			emit-i32 gcode
		]
	]

	emit-variable: func [
		name  [word! object!]
		gcode [binary! block! none!]
		pcode [binary! block! none!]
		lcode [binary! block!]
		/alt										;-- use alternative register (r1)
		/local offset opcode Rn
	][
		if object? name [name: compiler/unbox name]

		either offset: select emitter/stack name [	;-- local variable case
			emit-load-local lcode offset
		][											;-- global variable case
			opcode: #{e59f0000}
			
			either alt [
				opcode: opcode or #{00001000}		;-- use r1 instead of r0
			][
				if all [gcode not zero? Rn: gcode/3 and #"^(F0)"][
					opcode: copy opcode
					opcode/3: to char! Rn			;-- use same Rn
				]
			]
			pools/collect/spec/with 0 name opcode	;-- LDR r0|r1|Rn, [pc, #offset]
			opcode: get pick [pcode gcode] PIC?
			if opcode [emit-i32 opcode]
		]
	]
	
	emit-variable-64: func [
		name [word!] gcode [binary!] l-low [binary!] l-high [binary!]
	][
		if object? name [name: compiler/unbox name]
		
		either offset: select emitter/stack name [	;-- local variable case
			emit-load-local l-low offset
			emit-load-local l-high offset + 4
		][
			pools/collect/spec/with 0 name #{e59f2000}	;-- LDR r2, [pc, #offset]
			if PIC? [emit-i32 #{e0822009}]				;-- ADD r2, sb
			emit-i32 gcode
		]
	]
	
	emit-variable-poly: func [						;-- polymorphic variable access generation
		name [word! object!]
		g-code [binary!]							;-- opcodes for global variables
		p-code [binary! none!]						;-- opcodes for global variables
		l-code [binary! block!]						;-- opcodes for local variables
		/alt
	][
		with-width-of name [
			if width = 1 [
				g-code: g-code or byte-flag
				if p-code [p-code: p-code or byte-flag]
				l-code: l-code or byte-flag
			]
			either alt [
				emit-variable/alt name g-code p-code l-code
			][
				emit-variable name g-code p-code l-code
			]
			if all [
				PIC?
				none? p-code
				none? select emitter/stack name
			][										;-- no specific PIC opcode case (LDM/STM)
				emit-i32 pick [
					#{e0811009}						;-- ADD r1, sb
					#{e0800009}						;-- ADD r0, sb
				] to logic! alt
				emit-i32 g-code
			]
		]
	]
	
	emit-load-symbol: func [name [word!]][
		emit-variable name
			#{e5900000}								;-- LDR r0, [r0]		; global
			#{e7900009}								;-- LDR r0, [r0, sb]	; PIC
			#{e59b0000}								;-- LDR r0, [fp, #[-]n]	; local
	]
	
	emit-move-alt: does [emit-i32 #{e1a01000}]		;-- MOV r1, r0

	emit-swap-regs: func [/alt][
		either alt [
			emit-i32 #{e1a0c002}					;-- MOV r12, r2
			emit-i32 #{e1a02000}					;-- MOV r2, r0
			emit-i32 #{e1a0000c}					;-- MOV r0, r12	
		][
			emit-i32 #{e1a0c001}					;-- MOV r12, r1
			emit-move-alt
			emit-i32 #{e1a0000c}					;-- MOV r0, r12
		]
	]
	
	emit-move-path-alt: does [
		emit-i32 #{e1a02000}						;-- MOV r2, r0
	]
	
	emit-save-last: does [
		last-saved?: yes
		either find [float! float64!] compiler/last-type/1 [
			emit-i32 #{e92d0003}					;-- PUSH {r0,r1}
		][
			emit-i32 #{e92d0001}					;-- PUSH {r0}
		]
	]

	emit-restore-last: does [
		unless find [float! float64! float32!] compiler/last-type/1 [
			emit-i32 #{e8bd0002}		   			;-- POP {r1}
		]
	]

	emit-casting: func [value [object!] alt? [logic!] /local old type][
		type: compiler/get-type value/data	
		case [
			value/type/1 = 'logic! [
				if verbose >= 3 [print [">>>converting from" mold/flat type/1 "to logic!"]]
				old: width
				set-width/type type/1
				either alt? [
					if width = 1 [										; 16-bit not supported
						emit-i32 #{e20110ff}		;-- AND r1, r1, #ff
					]
					emit-i32 #{e3510000}			;-- CMP r1, 0
					emit-i32 #{13a01001}			;-- MOVNE r1, #1
				][
					if width = 1 [										; 16-bit not supported
						emit-i32 #{e20000ff}		;-- AND r0, r0, #FF
					]
					emit-i32 #{e3500000}			;-- CMP r0, 0
					emit-i32 #{13a00001}			;-- MOVNE r0, #1
				]
				width: old
			]
			all [value/type/1 = 'integer! type/1 = 'byte!][
				if verbose >= 3 [print ">>>converting from byte! to integer! "]
				emit-i32 pick [
					#{e20110ff}						;-- AND r1, r1, #ff				
					#{e20000ff}						;-- AND r0, r0, #ff
				] alt?
			]
			all [find [float! float64!] value/type/1 find [float32! integer!] type/1][
				if verbose >= 3 [print [">>>converting from" mold/flat type/1 "to float!"]]
				either alt? [
					emit-i32 #{ee001a10}			;-- FMSR s0, r1
				][
					emit-i32 #{ee000a10}			;-- FMSR s0, r0
				]
				emit-i32 #{eeb70ac0}				;-- FCVTDS d0, s0
				emit-i32 #{ec510b10}				;-- FMRRD r0, r1, d0
			]
			all [value/type/1 = 'float32! find [float! float64!] type/1][
				if verbose >= 3 [print [">>>converting from float! to float32!"]]
				; @@ handle alt case?
				emit-i32 #{ec410b10}				;-- FMDRR d0, r1, r0
				emit-i32 #{eeb70bc0}				;-- FCVTSD s0, d0
				emit-i32 #{ee100a10}				;-- FMRS r0, s0
			]
		]
	]
	
	emit-load-literal: func [type [block! none!] value][
		unless type [type: compiler/get-type value]
		emit-load-literal-ptr second emitter/store-value none value type
	]
	
	emit-load-literal-ptr: func [spec [block!]][
		pools/collect/spec 0 spec					;-- r0: value
		if PIC? [emit-i32 #{e0800009}]				;-- ADD r0, sb
	]
	
	emit-access-register: func [reg [word!] set? [logic!] value /local opcode][
		if verbose >= 3 [print [">>>emitting ACCESS-REGISTER" mold value]]
		if all [set? not tag? value][emit-load value]

		unless reg = 'r0 [
			opcode: copy #{e1a00000}
			reg: to integer! next form reg
			either set? [
				opcode/3: to char! shift/left reg 4
			][
				opcode/4: to char! reg
			]
			emit-i32 opcode							;-- MOV <reg>, r0	; set
		]											;-- MOV r0, <reg>	; get
	]
	
	emit-fpu-get: func [
		/type
		/options option [word!]
		/masks mask [word!]
		/cword
		/local value bit 
	][
		unless type [
			emit-i32 #{eef10a10}					;-- FMRX r0, FPSCR
		]
		case [
			type [
				; hardcoded value for now (FPU_VFP)
				emit-load-imm32 3					;-- MOV r0, <FPU_TYPE_VFP>
			]
			options [
				set [value bit] switch/default option [
					rounding  		[[#{00C00000} 22]]
					flush-to-zero	[[#{01000000} 24]]
					NaN-mode		[[#{02000000} 25]]
				][
					compiler/throw-error ["invalid FPU option name:" option]
				]
				emit-op-imm32 #{e2000000} to integer! value  ;-- AND r0, r0, #mask
			]
			masks [
				bit: switch/default mask [
					precision	[12]
					underflow	[11]
					overflow	[10]
					zero-divide [9]
					denormal	[15]
					invalid-op  [8]
				][
					compiler/throw-error ["invalid FPU mask name:" mask]
				]
				emit-op-imm32 #{e2000000} shift/left 1 bit  ;-- AND r0, r0, #mask
			]
			;cword []									;-- control word is already in eax
		]
		unless any [type cword][						;-- align result on right side
			emit-i32 #{e1a00020} or to-shift-imm bit	;-- LSR r0, r0, #bit
			if masks [emit-i32 #{e2200001}]				;-- EOR r0, #1		; invert 0<=>1
		]
	]

	emit-fpu-set: func [
		value
		/options option [word!]
		/masks mask [word!]
		/cword
		/local bit
	][
		value: to integer! value
		unless cword [emit-i32 #{eef10a10}]			;-- FMRX r0, FPSCR
		
		case [
			options [
				set [mask bit] switch/default option [
					rounding  		[[#{00C00000} 22]]
					flush-to-zero	[[#{01000000} 24]]
					NaN-mode		[[#{02000000} 25]]
				][
					compiler/throw-error ["invalid FPU option name:" option]
				]
				emit-op-imm32 #{e2000000} complement to integer! mask  ;-- AND r0, r0, #mask
				emit-op-imm32 #{e3800000} shift/left to integer! value bit	;-- OR r0, r0, LSL #value, #bit
			]
			masks [
				bit: switch/default mask [
					precision	[12]
					underflow	[11]
					overflow	[10]
					zero-divide [9]
					denormal	[15]
					invalid-op  [8]
				][
					compiler/throw-error ["invalid FPU mask name:" mask]
				]
				emit-op-imm32 #{e3800000} shift/left 1 bit  ;-- OR r0, r0, #mask
			]
		]
		emit-i32 #{eee10a10}						;-- FMXR FPSCR, r0
	]
	
	emit-fpu-update: emit-fpu-init: none			;-- not used for now
	
	emit-get-pc: does [
		emit-i32 #{e1a0000f}						;-- MOV r0, pc
	]

	emit-set-stack: func [value /frame][
		if verbose >= 3 [print [">>>emitting SET-STACK" mold value]]
		unless tag? value [emit-load value]
		either frame [
			emit-i32 #{e1a0b000}					;-- MOV fp, r0
		][
			emit-i32 #{e1a0d000}					;-- MOV sp, r0
		]
	]

	emit-get-stack: func [/frame][
		if verbose >= 3 [print ">>>emitting GET-STACK"]
		either frame [
			emit-i32 #{e1a0000b}					;-- MOV r0, fp
		][
			emit-i32 #{e1a0000d}					;-- MOV r0, sp
		]
	]

	emit-pop: does [
		if verbose >= 3 [print ">>>emitting POP"]
		emit-i32 #{e8bd0001}						;-- POP {r0}
	]
	
	emit-pop-float: func [idx [integer!] /with type [block!]][
		if with [width: select emitter/datatypes type/1]
		emit-float
			f-inc #{ed9d0b00} idx	;-- FLDD d<idx>, [sp]		; double precision float
			f-inc #{ed9d0a00} idx	;-- FLDS s<idx>, [sp]		; single precision float
			
		emit-i32 join #{e28dd0}		;-- ADD sp, sp, width		; adjust stack pointer
			to char! width
	]
	
	emit-push-float: func [idx [integer!] type [block!]][
		width: select emitter/datatypes type/1
		emit-float
			f-inc #{ed8d0b00} idx	;-- FSTD [sp], d<idx>		; double precision float
			f-inc #{ed8d0a00} idx	;-- FSTS [sp], s<idx>		; single precision float

		emit-i32 join #{e24dd0}		;-- SUB sp, sp, width		; adjust stack pointer
			to char! width
	]
	
	emit-not: func [value [word! char! tag! integer! logic! path! string! object!] /local opcodes type boxed][
		if verbose >= 3 [print [">>>emitting NOT" mold value]]

		if object? value [boxed: value]
		value: compiler/unbox value
		if block? value [value: <last>]

		opcodes: [
			logic!	 [emit-i32 #{e2200001}]			;-- EOR r0, #1		; invert 0<=>1
			byte!	 [emit-i32 #{e1e00000}]			;-- MVN r0, r0
			integer! [emit-i32 #{e1e00000}]			;-- MVN r0, r0
		]
		switch type?/word value [
			logic! [
				emit-load not value
			]
			char! [
				emit-load value
				do opcodes/byte!
			]
			integer! [
				emit-load value
				do opcodes/integer!
			]
			word! [
				emit-load value
				type: either boxed [
					emit-casting boxed no
					boxed/type/1
				][
					first compiler/resolve-aliased compiler/get-variable-spec value
				]
				if find [pointer! c-string! struct!] type [ ;-- type casting trap
					type: 'logic!
				]
				switch type opcodes
			]
			tag! [
				if boxed [
					emit-casting boxed no
					compiler/last-type: boxed/type
				]
				switch compiler/last-type/1 opcodes
			]
			string! [								;-- type casting trap
				emit-load value
				if boxed [emit-casting boxed no]
				do opcodes/logic!
			]
			path! [
				emitter/access-path value none
				either boxed [
					emit-casting boxed no
					switch boxed/type/1 opcodes 
				][
					type: compiler/resolve-path-type value
					compiler/last-type: type
					switch type/1 opcodes
				]
			]
		]
	]
	
	emit-boolean-switch: does [
		emit-i32 #{e3a00000}						;--		  MOV r0, #0	; (FALSE)
		emit-i32 #{ea000000}						;--		  B _exit
		emit-i32 #{e3a00001}						;--		  MOV r0, #1	; (TRUE)
													;-- _exit:
		reduce [4 12]								;-- [offset-TRUE offset-FALSE]
	]

	emit-load: func [
		value [char! logic! integer! word! string! path! paren! get-word! object! decimal!]
		/alt
		/with cast [object!]
		/local type offset spec
	][
		if verbose >= 3 [print [">>>loading" mold value]]

		switch type?/word value [
			char! [
				emit-load-imm32 to integer! value
			]
			logic! [
				emit-load-imm32 to integer! value
			]
			integer! [
				emit-load-imm32 value
			]
			decimal! [
				either all [cast cast/type/1 = 'float32!][
					emit-load-imm32 to integer! IEEE-754/to-binary32 value
				][
					spec: emitter/store-value none value [float!]
					pools/collect/spec/with 0 spec/2 #{e59f3000}	;-- LDR r3, [pc, #offset]
					if PIC? [emit-i32 #{e0833009}]					;-- ADD r3, sb
					emit-i32 #{e8930003} 							;-- LDM r3, {r0,r1}
				]
			]
			word! [
				type: compiler/get-variable-spec value
				either find [float! float64!] type/1 [
					emit-variable-poly value
						#{e8900003} 				;-- LDM r0, {r0,r1}		; global
						none
						#{e59b0000}					;-- LDR r0, [fp, #[-]n]	; local, low bits @@ test!!
					
					if offset: select emitter/stack value [
						emit-load-local #{e59b1000} offset + 4	;-- LDR r1, [fp, #[-]n+4]	; local, high bits
					]
				][
					either alt [
						emit-variable-poly/alt value
							#{e5911000}				;-- LDR r1, [r1]		; global
							#{e7911009}				;-- LDR r1, [r1, sb]	; PIC
							#{e59b1000}				;-- LDR r1, [fp, #[-]n]	; local
					][
						emit-variable-poly value
							#{e5900000} 			;-- LDR r0, [r0]		; global
							#{e7900009}				;-- LDR r0, [r0, sb]	; PIC
							#{e59b0000}				;-- LDR r0, [fp, #[-]n]	; local
					]
				]
			]
			get-word! [
				either offset: select emitter/stack to word! value [
					emit-i32 either negative? offset [
						#{e24b00}					;-- SUB r0, fp, n
					][
						#{e28b00}					;-- ADD r0, fp, n
					]
					emit-i32 to-bin8 abs offset
				][
					pools/collect/spec 0 value
					if PIC? [emit-i32 #{e0800009}]	;-- ADD r0, sb
				]
			]
			string! [
				emit-load-literal [c-string!] value
			]
			path! [
				emitter/access-path value none
			]
			paren! [
				emit-load-literal none value
			]
			object! [
				unless any [block? value/data value/data = <last>][
					either alt [
						emit-load/alt/with value/data value
					][
						emit-load/with value/data value
					]
					set-width value
				]
			]
		]
	]
	
	emit-store: func [
		name [word!] value [char! logic! integer! word! string! paren! tag! get-word! decimal!]
		spec [block! none!]
		/local store-qword store-word store-byte type
	][
		if verbose >= 3 [print [">>>storing" mold name mold value]]
		if value = <last> [value: 'last]			;-- force word! code path in switch block
		if logic? value [value: to integer! value]	;-- TRUE -> 1, FALSE -> 0

		store-qword: [
			emit-variable-64 name
				#{e8820003}							;-- STM r2, {r0,r1}			; global, low + high
				#{e58b0000}							;-- STR r0, [fp, #[-]n]		; local, low bits
				#{e58b1000}							;-- STR r1, [fp, #[-]n]		; local, high bits
		]
		store-word: [
			emit-variable/alt name
				#{e5010000}							;-- STR r0, [r1]			; global
				#{e7810009}							;-- STR r0, [r1, sb]		; PIC
				#{e58b0000}							;-- STR r0, [fp, #[-]n]		; local
		]
		store-byte: [
			emit-variable/alt name
				#{e5410000}							;-- STRB r0, [r1]			; global
				#{e7c10009}							;-- STRB r0, [r1, sb]		; PIC
				#{e5cb0000}							;-- STRB r0, [fp, #[-]n]	; local
		]

		switch type?/word value [
			char! [
				do store-byte
			]
			integer! [
				do store-word
			]
			decimal! [
				type: compiler/get-variable-spec name
				either type/1 = 'float32! [
					do store-word
				][
					do store-qword
				]
			]
			word! [
				set-width name
				switch width [
					1 [do store-byte]
					4 [do store-word]
					8 [do store-qword]
				]
			]
			get-word! [
				unless find emitter/stack to word! value [
					pools/collect/spec 0 value
					if PIC? [emit-i32 #{e0800009}]	;-- ADD r0, sb
				]
				do store-word
			]
			string! paren! [
				do store-word
			]
		]
	]
	
	emit-init-path: func [name [word!]][
		emit-load-symbol name
	]

	emit-access-path: func [
		path [path! set-path!] spec [block! none!] /short /local offset type saved
	][
		if verbose >= 3 [print [">>>accessing path:" mold path]]

		unless spec [
			spec: second compiler/resolve-type path/1
			emit-load path/1
		]
		if short [return spec]

		saved: width
		type: first compiler/resolve-type/with path/2 spec
		set-width/type type							;-- adjust operations width to member value size

		offset: emitter/member-offset? spec path/2
		if width = 8 [								;-- 64-bit value case
			emit-poly/with #{e5901000} offset + 4	;-- LDR r1, [r0, offset+4]	; high bits
		]
		emit-poly/with #{e5900000} offset			;-- LDR[B] r0, [r0, offset]
		width: saved
	]
	
	emit-load-index: func [idx [word!]][
		unless compiler/local-variable? idx [idx: compiler/resolve-ns idx]
		emit-variable idx
			#{e5933000}								;-- LDR r3, [r3]		; global
			#{e7933009}								;-- LDR r3, [r3, sb]	; PIC
			#{e59b3000}								;-- LDR r3, [fp, #[-]n]	; local
		emit-i32 #{e2433001}						;-- SUB r3, r3, #1		; one-based index
	]

	emit-c-string-path: func [path [path! set-path!] parent [block! none!] /local opcodes idx][
		unless parent [emit-init-path path/1]
		opcodes: pick [[							;-- store path opcodes --
			#{e5402000}								;-- STRB r2, [r0]		; first
			#{e7c02003}								;-- STRB r2, [r0, r3] 	; nth | variable index
		][											;-- load path opcodes --
			#{e5500000}								;-- LDRB r0, [r0]		; first
			#{e7d00003}								;-- LDRB r0, [r0, r3]	; nth | variable index
		]] set-path? path

		either integer? idx: path/2 [
			either zero? idx: idx - 1 [				;-- indexes are one-based
				emit-i32 opcodes/1
			][
				emit-load-imm32/reg idx 3			;-- LDR r3, #idx
				emit-i32 opcodes/2
			]
		][
			emit-load-index idx
			emit-i32 opcodes/2
		]
	]
	
	emit-pointer-path: func [
		path [path! set-path!] parent [block! none!] /local opcodes idx type scale
	][
		opcodes: pick [[							;-- store path opcodes --
			#{e5002000}								;-- STR[B] r2, [r0]
			#{e7802003}								;-- STR[B] r2, [r0, r3]
			#{e0822003}								;-- ADD r2, r2, r3
			#{e8820003}								;-- STM r2, {r0,r1}
		][											;-- load path opcodes --
			#{e5900000}								;-- LDR[B] r0, [r0]
			#{e7900003}								;-- LDR[B] r0, [r0, r3]
			#{e0800003}								;-- ADD r0, r0, r3
			#{e8900003} 							;-- LDM r0, {r0,r1}
		]] set-path? path

		type: either parent [
			compiler/resolve-type/with path/1 parent
		][
			emit-init-path path/1
			compiler/resolve-type path/1
		]
		set-width/type type/2/1						;-- adjust operations width to pointed value size
		idx: either path/2 = 'value [1][path/2]
		scale: emitter/size-of? type/2/1

		if all [set-path? path not parent width = 8][
			emit-swap-regs/alt
		]

		either integer? idx [
			either zero? idx: idx - 1 [				;-- indexes are one-based
				either width = 8 [
					emit-i32 opcodes/4
				][
					emit-poly opcodes/1
				]
			][
				emit-load-imm32/reg idx * scale 3	;-- LDR r3, #idx
				either width = 8 [
					emit-i32 opcodes/3
					emit-i32 opcodes/4
				][
					emit-poly opcodes/2
				]
			]
		][
			emit-load-index idx
			if scale > 1 [
				emit-i32 #{e1a03003}				;-- LSL r3, r3, #log2(scale)
					or debase/base to-hex shift/left power-of-2? scale 7 16
			]
			either width = 8 [
				emit-i32 opcodes/3
				emit-i32 opcodes/4
			][
				emit-poly opcodes/2
			]
		]
	]
	
	emit-load-path: func [path [path!] type [word!] parent [block! none!] /local idx][
		if verbose >= 3 [print [">>>loading path:" mold path]]

		switch type [
			c-string! [emit-c-string-path path parent]
			pointer!  [emit-pointer-path  path parent]
			struct!   [emit-access-path   path parent]
		]
	]
	
	emit-store-path: func [path [set-path!] type [word!] value parent [block! none!] /local idx offset size][
		if verbose >= 3 [print [">>>storing path:" mold path mold value]]
		
		size: emitter/size-of? compiler/get-type value
													;-- @@ separate 64/32-bit conventions, too messy...
		unless value = <last> [
			if parent [emit-i32 #{e1a02000}]		;-- MOV r2, r0		; save value/address
			emit-load value							; @@ generates duplicate value loading sometimes
			if all [not parent size = 8][
				emit-i32 #{e1a02000}				;-- MOV r2, r0		; save value/address
			]
			if size <> 8 [emit-swap-regs/alt]			;-- save value/restore address
		]

		switch type [
			c-string! [emit-c-string-path path parent]
			pointer!  [emit-pointer-path  path parent]
			struct!   [
				unless parent [
					parent: emit-access-path/short path parent
					if size = 8 [emit-swap-regs/alt] ;-- save value/restore address
				]
				type: first compiler/resolve-type/with path/2 parent
				set-width/type type					;-- adjust operations width to member value size

				either zero? offset: emitter/member-offset? parent path/2 [
					either width = 8 [
						emit-i32 #{e8820003}		;-- STM r2, {r0,r1}		; r2 = address
					][
						emit-poly #{e5002000}		;-- STR r2, [r0]		; r2 = value
					]
				][
					emit-load-imm32/reg offset 3
					either width = 8 [
						emit-i32 #{e0822003}		;-- ADD r2, r2, r3
						emit-i32 #{e8820003}		;-- STM r2, {r0,r1}		; r2 = address
					][
						emit-poly #{e7802003}		;-- STR r2, [r0, r3]	; r2 = value
					]
				]
			]
		]
	]
	
	patch-exit-call: func [code-buf [binary!] ptr [integer!] exit-point [integer!]][
		change 
			at code-buf ptr
			reverse to-bin24 shift exit-point - ptr - (2 * branch-offset-size) 2
	]
	
	emit-exit: does [
		if verbose >= 3 [print ">>>exiting function"]
		emit-reloc-addr emitter/exits
		emit-i32 #{ea000000}						;-- B <disp>
	]
	
	emit-branch: func [
		code 	[binary!]
		op 		[word! block! logic! none!]
		offset  [integer! none!]
		/back?
		/local distance opcode jmp
	][
		distance: (length? code) - (any [offset 0]) - 4	;-- offset from the code's head
		if back? [distance: negate distance + 12]	;-- 8 (PC offset) + one instruction
		
		op: either not none? op [					;-- explicitly test for none
			op: case [
				block? op [							;-- [cc] => keep
					op: op/1
					either logic? op [pick [= <>] op][op]	;-- [logic!] or [cc]
				]
				logic? op [pick [= <>] op]			;-- test for TRUE/FALSE
				'else 	  [opposite? op]			;-- 'cc => invert condition
			]
			either '- = third op: find conditions op [	;-- lookup the code for the condition
				op/2								;-- condition defined only for signed
			][
				pick op pick [2 3] signed?			;-- choose code between signed and unsigned
			]
		][
			#{e0}									;-- unconditional jump
		]
		unless back? [
			if same? head code emitter/code-buf [
				pools/insert-jmp-point emitter/tail-ptr distance	;-- update code indexes affected by the insertion
			]
		]
		opcode: reverse rejoin [
			op or #{0a} to-bin24 shift distance 2
		]		
		insert any [all [back? tail code] code] opcode
		4											;-- opcode length
	]

	emit-push: func [
		value [char! logic! integer! word! block! string! tag! path! get-word! object! decimal!]
		/with cast [object!]
		/cdecl
		/local push-last push-last64 spec type
	][
		if verbose >= 3 [print [">>>pushing" mold value]]
		if block? value [value: <last>]
		
		push-last:  [emit-i32 #{e92d0001}]			;-- PUSH {r0}
		push-last64: [emit-i32 #{e92d0003}]			;-- PUSH {r0,r1}

		switch type?/word value [
			tag! [									;-- == <last>
				type: either cast [cast/type][compiler/last-type]
				do either find [float! float64!] type/1 [
					push-last64
				][
					push-last
				]
			]
			logic! [
				emit-load-imm32 to integer! value	;-- MOV r0, #0|#1
				do push-last
			]
			char! [
				emit-load-imm32 to integer! value	;-- MOV r0, #imm8
				do push-last
			]
			integer! [
				emit-load-imm32/reg value 3
				emit-i32 #{e92d0008}				;-- PUSH {r3}
			]
			decimal! [
				either all [cast cast/type/1 = 'float32! not cdecl][
					emit-load-imm32 to integer! IEEE-754/to-binary32 value
					do push-last
				][
					spec: emitter/store-value none value [float!]
					pools/collect/spec/with 0 spec/2 #{e59f2000}	;-- LDR r2, [pc, #offset]
					if PIC? [emit-i32 #{e0822009}]	;-- ADD r2, sb
					emit-i32 #{e8920003} 			;-- LDM r2, {r0,r1}
					emit-i32 #{e92d0003}			;-- PUSH {r0,r1}
				]
			]
			word! [
				type: compiler/get-variable-spec value
				either any [
					find [float! float64!] type/1 
					all [cast find [float! float64!] cast/type/1]
				][
					emit-load value
					do push-last64
				][
					emit-load-symbol value
					do push-last
				]
			]
			get-word! [
				emit-load value
				do push-last						;-- PUSH &value
			]
			string! [
				emit-load-literal [c-string!] value
				do push-last						;-- PUSH value
			]
			path! [
				emitter/access-path value none
				compiler/last-type: either cast [
					emit-casting cast no
					cast/type
				][
					compiler/resolve-path-type value
				]
				emit-push <last>
			]
			object! [
				unless path? value/data [
					emit-casting value no
				]
				either cdecl [
					emit-push/with/cdecl value/data value
				][
					emit-push/with value/data value
				]
			]
		]
	]
	
	emit-bitshift-op: func [name [word!] a [word!] b [word!] args [block!] /local c value][
		switch b [
			ref [
				emit-variable args/2
					#{e5d03000}						;-- LDRB r3, [r0]			; global
					#{e7d03009}						;-- LDRB r3, [r0, sb]		; PIC
					#{e5db3000}						;-- LDRB r3, [fp, #[-]n]	; local
			]
			reg [emit-i32 #{e1a03001}]				;-- MOV r3, r1
		]
		opcode: select [
			<<  [
				#{e1a00000}							;-- LSL r0, r0, #b
				#{e1a00310}							;-- LSL r0, r0, r3
			]
			>>  [
				#{e1a00040}							;-- ASR r0, r0, #b
				#{e1a00350}							;-- ASR r0, r0, r3
			]
			-** [
				#{e1a00020}							;-- LSR r0, r0, #b
				#{e1a00330}							;-- LSR r0, r0, r3
			]
		] name
	
		emit-i32 either b = 'imm [
			opcode/1 or to-shift-imm args/2
		][
			opcode/2
		]
		
		if b = 'imm [
			c: select [1 7 2 15 4 31] width
			value: compiler/unbox args/2		
			unless all [0 <= value value <= c][		
				compiler/backtrack name
				compiler/throw-error rejoin [
					"a value in 0-" c " range is required for this shift operation"
				]
			]
		]
	]
	
	emit-bitwise-op: func [name [word!] a [word!] b [word!] args [block!] /local code][		
		code: select [
			and [#{e0000001}]						;-- AND r0, r0, r1	; commutable op
			or  [#{e1800001}]						;-- OR  r0, r0, r1	; commutable op
			xor [#{e0200001}]						;-- EOR r0, r0, r1	; commutable op
		] name

		switch b [
			imm [
				emit-load-imm32/reg compiler/unbox args/2 1	;-- MOV r1, #value
				emit-i32 code						;-- <OP> r0, r0, r1
			]
			ref [
				emit-load/alt args/2
				if object? args/2 [emit-casting args/2 yes]
				emit-i32 code
			]
			reg [emit-i32 code]						;-- <OP> r0, r0, r1		; commutable op
		]
	]
	
	emit-comparison-op: func [name [word!] a [word!] b [word!] args [block!] /local op-poly arg2][
		op-poly: [
			switch width [
				1 [
					emit-i32 #{e1a03c00}			;-- MOV r3, r0, LSL #24
					emit-i32 #{e1533c01}			;-- CMP r3, r1, LSL #24
				]
				;2 []								;-- 16-bit not supported
				4 [emit-i32 #{e1500001}]			;-- CMP r0, r1		; not commutable op
			]
		]		
		arg2: either object? args/2 [compiler/cast args/2][args/2]
		
		switch b [
			imm [
				switch width [
					1 [
						emit-i32 join #{e35000}		;-- CMP r0, #imm8
							to char! arg2
					]
					;2 []							;-- 16-bit not supported
					4 [
						emit-load-imm32/reg arg2 1	;-- r1: arg2	
						emit-i32 #{e1500001}		;-- CMP r0, r1		; not commutable op
					]
				]
			]
			ref [
				emit-load/alt args/2
				if object? args/2 [emit-casting args/2 yes]
				do op-poly
			]
			reg [
				do op-poly
			]
		]
	]
	
	emit-math-op: func [
		name [word!] a [word!] b [word!] args [block!]
		/local mod? scale c type arg2 op-poly
	][
		;-- r0 = a, r1 = b
		if find mod-rem-op name [					;-- work around unaccepted '// and '%
			mod?: select mod-rem-func name			;-- convert operators to words (easier to handle)
			name: first [/]							;-- work around unaccepted '/ 
		]
		arg2: compiler/unbox args/2

		if all [
			find [+ -] name							;-- pointer arithmetic only allowed for + & -
			type: compiler/resolve-aliased compiler/resolve-expr-type args/1
			not compiler/any-pointer? compiler/resolve-expr-type args/2	;-- no scaling if both operands are pointers		
			scale: switch type/1 [
				pointer! [emitter/size-of? type/2/1]		  ;-- scale factor: size of pointed value
				struct!  [emitter/member-offset? type/2 none] ;-- scale factor: total size of the struct
			]
			scale > 1
		][
			either compiler/literal? arg2 [
				arg2: arg2 * scale					;-- 'b is a literal, so scale it directly
			][
				either b = 'reg [
					emit-swap-regs					;-- swap r0, r1		; put operands in right order
					emit-i32 #{e92d0002}			;-- PUSH {r1}		; save r1 (a) from corruption
				][									;-- 'b will now be stored in reg, so save 'a
					emit-i32 #{e92d0001}			;-- PUSH {r0}		; save r0 (a) from corruption
					emit-move-alt					;-- MOV r1, r0
					emit-load args/2
				]
				emit-math-op '* 'reg 'imm reduce [arg2 scale]	;@@ refactor that using barrel shifter
				emit-i32 #{e8bd0002}				;-- POP {r1}		; restore pointer in r1
				if name = '- [emit-swap-regs]		;-- swap r0, r1		; put operands in right order
				b: 'reg
			]
		]
		;-- r0 = a, r1 = b
		switch name [
			+ [
				op-poly: [emit-i32 #{e0800001}]		;-- ADD r0, r0, r1	; commutable op
				switch b [
					imm [
						emit-op-imm32 #{e2800000} arg2 ;-- ADD r0, r0, #value
					]
					ref [
						emit-load/alt arg2
						do op-poly
					]
					reg [do op-poly]
				]
			]
			- [
				op-poly: [emit-i32 #{e0400001}] 	;-- SUB r0, r0, r1	; not commutable op
				switch b [
					imm [
						emit-op-imm32 #{e2400000} arg2 ;-- SUB r0, r0, #value
					]
					ref [
						emit-load/alt arg2
						do op-poly
					]
					reg [do op-poly]
				]
			]
			* [
				op-poly: [emit-i32 #{e0000091}]		;-- MUL r0, r0, r1 	; commutable op
				switch b [
					imm [
						either all [
							not zero? arg2
							c: power-of-2? arg2		;-- trivial optimization for b=2^n
						][
							emit-i32 #{e1a00000}	;-- LSL r0, r0, #log2(b)
								or to-shift-imm c
						][
							emit-load-imm32/reg args/2 1	;-- MOV r1, #value
							do op-poly
						]
					]
					ref [
						emit-i32 #{e92d0002}		;-- PUSH {r1}	; save r1 from corruption
						emit-load/alt args/2
						do op-poly
						emit-i32 #{e8bd0002}		;-- POP {r1}
					]
					reg [do op-poly]
				]
			]
			/ [
				switch b [
					imm [
						emit-i32 #{e92d0002}		;-- PUSH {r1}	; save r1 from corruption
						emit-load-imm32/reg args/2 1 ;-- MOV r1, #value
					]
					ref [
						emit-i32 #{e92d0002}		;-- PUSH {r1}	; save r1 from corruption
						emit-load/alt args/2
					]
				]
				call-divide mod?
				
				if any [							;-- in case r1 was saved on stack
					all [b = 'imm any [mod? not c]]
					b = 'ref
				][
					emit-i32 #{e8bd0002}			;-- POP {r1}
				]
			]
		]
		;TBD: test overflow and raise exception ? (or store overflow flag in a variable??)
		; JNO? (Jump if No Overflow)
	]
	
	emit-integer-operation: func [name [word!] args [block!] /local a b sorted? left right][
		if verbose >= 3 [print [">>>inlining op:" mold name mold args]]

		set-width args/1							;-- set reg/mem access width
		set [a b] get-arguments-class args
		last-saved?: no								;-- reset flag

		;-- First operand processing
		left:  compiler/unbox args/1
		right: compiler/unbox args/2

		switch to path! reduce [a b] [
			imm/imm	[emit-load-imm32 left]			;-- MOV r0, a
			imm/ref [emit-load args/1]				;-- r0 = a
			imm/reg [								;-- r0 = b
				if path? right [
					emit-load args/2				;-- late path loading
				]
				emit-move-alt						;-- MOV r1, r0
				emit-load-imm32 left				;-- MOV r0, a		; r0 = a, r1 = b
			]
			ref/imm [emit-load args/1]
			ref/ref [emit-load args/1]
			ref/reg [								;-- r0 = b
				if path? right [
					emit-load args/2				;-- late path loading
				]
				emit-move-alt						;-- MOV r1, r0
				emit-load args/1					;-- r0 = a, r1 = b
			]
			reg/imm [								;-- r0 = a (or r1 = a if last-saved)
				if path? left [
					emit-load args/1				;-- late path loading
				]
				if last-saved? [emit-swap-regs]		;-- swap r0, r1	; r0 = a
			]
			reg/ref [								;-- r0 = a (or r1 = a if last-saved)
				if path? left [
					emit-load args/1				;-- late path loading
				]
				if last-saved? [emit-swap-regs]		;-- swap r0, r1	; r0 = a
			]
			reg/reg [								;-- r0 = b, r1 = a
				if path? left [
					if any [
						args/2 = <last>				;-- inlined statement
						block? right				;-- function call
					][				 				;-- r1 = b
						emit-swap-regs				;-- swap r0, r1
						sorted?: yes				;-- r0 = a, r1 = b
					]
					emit-load args/1				;-- late path loading
				]
				if path? right [
					emit-swap-regs					;-- swap r0, r1	; r0 = b, r1 = a
					emit-load args/2
				]
				unless sorted? [emit-swap-regs]		;-- swap r0, r1	; r0 = a, r1 = b
			]
		]
		if object? args/1 [emit-casting args/1 no]	;-- do runtime conversion if required

		;-- Operator and second operand processing
		either all [object? args/2 find [imm reg] b][
			emit-casting args/2 yes					;-- do runtime conversion if required
		][
			implicit-cast right
		]
		case [
			find comparison-op name [emit-comparison-op name a b args]
			find math-op	   name	[emit-math-op		name a b args]
			find bitwise-op	   name	[emit-bitwise-op	name a b args]
			find bitshift-op   name [emit-bitshift-op   name a b args]
		]
	]
	
	emit-vfp-casting: func [value [object!] /right [logic!] /local type][
		type: compiler/get-type value/data	
		case [
			all [find [float! float64!] value/type/1 find [float32! integer!] type/1][
				either right [
					emit-i32 #{eeb71ac1}			;-- FCVTDS d1, s2
				][
					emit-i32 #{eeb70ac0}			;-- FCVTDS d0, s0
				]
			]
			all [value/type/1 = 'float32! find [float! float64!] type/1][
				either right [
					emit-i32 #{eeb71bc1}			;-- FCVTSD s2, d1
				][
					emit-i32 #{eeb70bc0}			;-- FCVTSD s0, d0
				]
			]
		]
	]

	emit-float-operation: func [name [word!] args [block!] /local a b left right spec size saved][
		if verbose >= 3 [print [">>>inlining float op:" mold name mold args]]
		
		set [a b] get-arguments-class args

		;-- First operand processing
		left:  compiler/unbox args/1
		right: compiler/unbox args/2
		set-width args/1
		saved: width

		switch a [									;-- load left operand in d0 or s0
			imm [
				either width = 4 [
					emit-load-imm32/reg to integer! IEEE-754/to-binary32 left 3
					emit-i32 #{ee003a10}			;-- FMSR s0, r3
				][
					spec: emitter/store-value none args/1 compiler/get-type args/1
					pools/collect/spec/with 0 spec/2 #{e59f3000}	;-- LDR r3, [pc, #offset]
					if PIC? [emit-i32 #{e0833009}]	;-- ADD r3, sb
					emit-i32 #{ed930b00}			;-- FLDD d0, [r3]
				]
			]
			ref [
				set-width left
				either width = 8 [
					emit-float-variable args/1
						#{ed930b00} 				;-- FLDD d0, [r3]			; global
						#{ed9b0b00}					;-- FLDD d0, [fp, #[-]n]	; local
				][
					emit-float-variable args/1
						#{ed930a00} 				;-- FLDS s0, [r3]			; global
						#{ed9b0a00}					;-- FLDS s0, [fp, #[-]n]	; local
				]
				if object? args/1 [emit-vfp-casting args/1]
			]
			reg [
				if block? left [
					either b = 'reg [
						emit-pop-float 0
					][
					 	emit-float 
					 		#{ec410b10}				;-- FMDRR d0, r1, r0
					 		#{ee000a10}				;-- FMSR s0, r0
					]
				]
				if path? left [
					if all [b = 'reg not path? right][
						emit-push <last>			;-- push right result on stack
					]
					emit-load args/1				;-- late path loading
					emit-float 
						#{ec410b10}					;-- FMDRR d0, r1, r0
						#{ee000a10}					;-- FMSR s0, r0
				]
				if object? args/1 [emit-vfp-casting args/1]
			]
		]
	
		switch b [									;-- load right operand in d1 or s2
			imm [
				set-width args/2
				either width = 4 [
					emit-load-imm32/reg to integer! IEEE-754/to-binary32 right 3
					emit-i32 #{ee013a10}			;-- FMSR s2, r3
				][
					spec: emitter/store-value none args/2 compiler/get-type args/2
					pools/collect/spec/with 0 spec/2 #{e59f3000}	;-- LDR r3, [pc, #offset]
					if PIC? [emit-i32 #{e0833009}]	;-- ADD r3, sb
					emit-i32 #{ed931b00}			;-- FLDD d1, [r3]
				]
			]
			ref [
				set-width right
				either width = 8 [
					emit-float-variable args/2
						#{ed931b00} 				;-- FLDD d1, [r3]			; global
						#{ed9b1b00}					;-- FLDD d1, [fp, #[-]n]	; local
				][
					emit-float-variable args/2
						#{ed931a00} 				;-- FLDS s2, [r3]			; global
						#{ed9b1a00}					;-- FLDS s2, [fp, #[-]n]	; local
				]
				if object? args/2 [emit-vfp-casting/right args/2]
			]
			reg [
				set-width right
				if path? right [
					emit-load args/2
					emit-float 
						#{ec410b11}					;-- FMDRR d1, r1, r0
						#{ee010a10}					;-- FMSR s2, r0
				]
				if block? right [
					if path? left [emit-pop-float 0]
					emit-float 
						#{ec410b11}					;-- FMDRR d1, r1, r0
						#{ee010a10}					;-- FMSR s2, r0
				]
				if object? args/2 [emit-vfp-casting/right args/2]
			]
		]
		width: saved
		
		case [
			find comparison-op name [
				emit-float 							;-- load immediate from data segment
					#{eeb40b41}						;-- FCMPD d0, d1
					#{eeb40a41}						;-- FCMPS s0, s2
				emit-i32 #{eef1fa10}				;-- FMSTAT				; transfer flags to CPU
			]
			find math-op name [
				either width = 8 [
					either find mod-rem-op name [
						emit-i32 #{ee802b01}		;-- FDIVD  d2, d0, d1
						emit-i32 #{eebd4bc2}		;-- FTOSID s8, d2		; round towards 0
						emit-i32 #{eeb02b40}		;-- FCPYD  d2, d0		; d2 = dividend
						emit-i32 #{eeb80bc4}		;-- FSITOD d0, s8		; d0 = INT(q)
						emit-i32 #{ee002b41}		;-- FNMACD d2, d0, d1	; d2 = d2 - d0 * d1
					][
						emit-i32 switch name [		;-- double precision math
							+ [#{ee302b01}]			;-- FADDD d2, d0, d1
							- [#{ee302b41}]			;-- FSUBD d2, d0, d1
							* [#{ee202b01}]			;-- FMULD d2, d0, d1
							/ [#{ee802b01}]			;-- FDIVD d2, d0, d1
						]
					]
					emit-i32 #{ec510b12}			;-- FMRRD r0, r1, d2	; move result to CPU
				][
					either find mod-rem-op name [
						emit-i32 #{ee802a01}		;-- FDIVS  s4, s0, s2
						emit-i32 #{eebd4ac2}		;-- FTOSIS s8, s4		; round towards 0
						emit-i32 #{eeb02a40}		;-- FCPYS  s4, s0		; s4 = dividend
						emit-i32 #{eeb80ac4}		;-- FSITOS s0, s8		; s0 = INT(q)
						emit-i32 #{ee002a41}		;-- FNMACS s4, s0, s2	; s4 = s4 - s0 * s2
					][
						emit-i32 switch name [		;-- single precision math
							+ [#{ee302a01}]			;-- FADDS s4, s0, s2
							- [#{ee302a41}]			;-- FSUBS s4, s0, s2
							* [#{ee202a01}]			;-- FMULS s4, s0, s2
							/ [#{ee802a01}]			;-- FDIVS s4, s0, s2
						]
					]
					emit-i32 #{ee120a10}			;-- FMRS r0, s4			; move result to CPU
				]
			]
			true [
				compiler/throw-error "unsupported operation on floats"
			]
		]
	]
	
	emit-APCS-header: func [
		args [block!] cconv [word!] attribs [block! none!]
		/local reg bits offset type size stk freg
	][
		either args/1 = #custom [
			repeat reg min args/2/1 4 [
				emit-i32 #{e8bd00} 					;-- POP {rn[,rn+1]}
				emit-i32 to char! shift/left 1 reg - 1
			]
			stack-width * max 0 args/2/1 - 4		;-- return extra args on stack count
		][
			if issue? args/1 [args: args/2]
			reg: freg: stk: 0
		
			foreach arg reverse args [				;-- arguments are on stack in reverse order	
				if arg <> #_ [						;-- bypass place-holder marker
					type: compiler/get-type arg
					
					either all [
						compiler/job/ABI = 'hard-float
						find [float! float64! float32!] type/1
						any [none? attribs not find attribs 'variadic]	;-- 'typed is not using hf ABI
					][
						emit-pop-float/with freg type
					 	freg: freg + 1
					][
						size: either all [
							cconv = 'cdecl
							type/1 = 'float32!
						][
							8						;-- promote to C double
						][
							emitter/size-of? type
						]
						if reg >= 4 [stk: stk + any [size 4]] ;-- account for extra args on stack
															  ;-- ANY: workaround special variables from start.reds
						set [bits offset] either 8 = size [
							either reg <= 2 [
								if odd? reg [
									emit-load-imm32/reg 0 1
									reg: reg + 1	;-- start 64-bit value on even register
								]
								[3 2]				;-- use 2 regs
							][
								[0 2]				;-- no space in regs to store a 64-bit value
							]
						][
							[1 1]					;-- use 1 reg
						]

						if all [reg < 4 not zero? bits][
							emit-i32 #{e8bd00} 		;-- POP {rn[,rn+1]}
							emit-i32 to char! shift/left bits reg
						]

						reg: reg + offset
					]
				]
			]
			stk										;-- return extra args on stack count
		]
	]
	
	emit-hf-return: func [spec [block!] /local type][
		if all [
			compiler/job/ABI = 'hard-float
			find [float! float64! float32!] type: select spec first [return:]
		][
			width: select emitter/datatypes type/1
			emit-float
				#{ec510b10}							;-- FMRRD r0, r1, d0
				#{ee100a10}							;-- FMRS r0, s0
		]
	]

	emit-call-syscall: func [args [block!] fspec [block!] attribs [block! none!] /local extra][	; @@ check if it needs stack alignment too
		extra: emit-APCS-header args fspec/3 attribs
		emit-i32 #{e3a070}							;-- MOV r7, <syscall>
		emit-i32 to-bin8 last fspec
		emit-i32 #{ef000000}						;-- SVC 0		; @@ EABI syscall
		unless zero? extra [
			emit-op-imm32 #{e28dd000} extra			;-- ADD sp, sp, extra	; skip extra stack arguments
		]
		emit-hf-return fspec/4
	]
	
	emit-call-import: func [args [block!] fspec [block!] spec [block!] attribs [block! none!] /local extra type][
		extra: emit-APCS-header args fspec/3 attribs
		pools/collect/spec/with 0 spec #{e59fc000}	;-- MOV ip, #(.data.rel.ro + symbol_offset)
		if PIC? [emit-i32 #{e08cc009}]				;-- ADD ip, sb
		emit-i32 #{e59cc000}						;-- LDR ip, [ip]
		emit-i32 #{e12fff3c}						;-- BLX ip
		unless zero? extra [						;-- _next:
			emit-op-imm32 #{e28dd000} extra			;-- ADD sp, sp, extra	; skip extra stack arguments
		]
		emit-hf-return fspec/4
	]
	
	emit-call-native: func [
		args [block!] fspec [block!] spec [block!] attribs [block! none!] /routine name [word!]
		/local extra cb?
	][
		either routine [							;-- test for function! pointer case
			if cb?: any [
				fspec/5 = 'callback
				all [attribs any [find attribs 'cdecl find attribs 'stdcall]]
			][
				extra: emit-APCS-header args fspec/3 attribs
			]
			name: pick tail fspec -2
			
			emit-i32 #{e1a0c000}					;-- MOV r12, r0
			either all [
				'local = last fspec
				find form name slash 
			][
				emitter/access-path load form name none
			][
				emit-load-symbol name
			]
			emit-i32 #{e1a0a000}					;-- MOV r10, r0
			emit-i32 #{e1a0000c}					;-- MOV r0, r12
			emit-i32 #{e120003a}					;-- BLX r10
			if all [extra positive? extra][
				emit-op-imm32 #{e28dd000} extra		;-- ADD sp, sp, extra	; skip extra stack arguments
			]
			if cb? [emit-hf-return fspec/4]
		][
			if issue? args/1 [							;-- variadic call
				emit-push call-arguments-size? args/2	;-- push arguments total size in bytes 
														;-- (required to clear stack on stdcall return)
				emit-i32 #{e28dc004}					;-- ADD ip, sp, #4	; skip last pushed value
				emit-i32 #{e92d1000}					;-- PUSH {ip}		; push arguments list pointer
				total: length? args/2
				if args/1 = #typed [total: total / 3]	;-- typed args have 3 components
				emit-push total							;-- push arguments count
			]
			emit-reloc-addr spec/3
			emit-i32 #{eb000000}					;-- BL <disp>
		]
	]

	patch-call: func [code-buf rel-ptr dst-ptr] [
		;; @@ to-bin24
		change
			at code-buf rel-ptr
			copy/part to-bin32 shift (dst-ptr - rel-ptr - (2 * ptr-size)) 2 3
	]
	
	emit-argument: func [arg fspec [block!]][
		if arg = #_ [exit]							;-- place-holder, no code to emit
		
		either all [
			object? arg
			any [arg/type = 'logic! 'byte! = first compiler/get-type arg/data]
			not path? arg/data
		][
			unless block? arg [emit-load arg]		;-- block! means last value is already in r0 (func call)
			emit-casting arg no
			compiler/last-type: arg/type			;-- for inline unary functions
			emit-push <last>
		][
			if block? arg [arg: <last>]
			either all [
				fspec/3 = 'cdecl 
				compiler/find-attribute fspec/4 'variadic	;-- only for vararg C functions
			][
				emit-push/cdecl arg					;-- promote float32! to float!
			][
				emit-push arg
			]
		]
	]
	
	emit-stack-align: does [
		emit-i32 #{e1a0c00d}						;-- MOV ip, sp
		emit-i32 #{e3cdd007}						;-- BIC sp, sp, #7		; align sp to 8 bytes
		emit-i32 #{e1a0000c}						;-- MOV r0, ip
	]
	
	emit-stack-align-prolog: func [args [block!] /local size tag][
		;-- EABI stack 8 bytes alignment: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0046b/IHI0046B_ABI_Advisory_1.pdf
		; @@ to be optimized: infer stack alignment if possible, to avoid this overhead.
		
		emit-i32 #{e1a0c00d}                        ;-- MOV ip, sp
		emit-i32 #{e3cdd007}						;-- BIC sp, sp, #7		; align sp to 8 bytes
		size: 0
		if issue? tag: args/1 [
			args: args/2
			unless tag = #variadic [size: size + 4]
		]
		if args: arguments-on-stack?/cdecl args [	;-- skip arguments passed in r0-r3
			size: size + call-arguments-size?/cdecl args
		]
		unless zero? size // 8 [
			emit-i32 #{e24dd004}					;-- SUB sp, sp, #4		; ensure call will be 8-bytes aligned
		]
		emit-i32 #{e92d5000}						;-- PUSH {ip,lr}		; save previous sp and lr value
	]

	emit-stack-align-epilog: func [args [block!]][
		emit-i32 #{e8bd5000}						;-- POP {ip,lr}			; use ip as replacement to sp
		emit-i32 #{e1a0d00c}                        ;-- MOV sp, ip			; to workaround SIGILLs on ARMv7
	]
	
	emit-throw: func [value [integer! word!]][
		emit-load value

		emit-i32 #{e1a0d00b}						;-- 		MOV sp, fp		; unwind 1st frame
		emit-i32 #{e8bd4800}						;-- 		POP {fp,lr}
		emit-i32 #{e24bd004}						;-- _loop:	SUB sp, fp, #4
		emit-i32 #{e8bd0004}						;-- 		POP {r2} 		; get flag
		emit-i32 #{e1520000}						;-- 		CMP r2, r0
		emit-i32 #{38bd4800}						;-- 		POPLO {fp,lr} 	; unwind frame if r2 < r0
		emit-i32 #{3afffffa}						;-- 		BLO _loop		; next frame
													;-- _exit:  
		emitter/access-path to set-path! 'system/thrown <last>
		emit-i32 #{e1a0f00e}						;--			MOV pc, lr
	]

	emit-prolog: func [
		name locals [block!] locals-size [integer!]
		/local args-nb attribs args reg freg fargs-nb
	][
		if verbose >= 3 [print [">>>building:" uppercase mold to-word name "prolog"]]
		
		fspec: select compiler/functions name
		attribs: compiler/get-attributes fspec/4
		
		if any [
			fspec/5 = 'callback
			all [attribs any [find attribs 'cdecl find attribs 'stdcall]]
		][
			;; we use a simple prolog, which maintains ABI compliance: args 0-3 are
			;; passed via regs r0-r3, further args are passed on the stack (pushed
			;; right-to-left; i.e. the leftmost argument is at top-of-stack).
			;;
			;; our prolog pushes the first <=4 args right-to-left to the stack
			;;
			;; AAPCS (for external calls & callbacks only)
			;;
			;;	15 = pc
			;;	14 = lr
			;;	13 = sp									(callee saved: fun must preserve)
			;;	12 = "ip" (scratch)
			;;	4-11 = variable register 1-8			(callee saved: fun must preserve)
			;;	11 = "fp"
			;;	2-3 = argument 3-4
			;;  0-1	= argument 1-2 / result
			;;
			;;	stack (sp) at function call must be 8-byte (dword) aligned!
			;;
			;;	c widths: char = i8, short = i16, int & long = i32, long long = i64
			;;	alignment: == size (so char==1, short==2, int/long==4, ptr==4)
			;;	structs aligned at max aligned, padded to multiple of alignment
			
			args-nb: fspec/1
			
			if all [4 < args-nb name <> '***_start][
				compiler/throw-error "[ARM emitter] more than 4 arguments in callbacks, not yet supported"
			]
			emit-i32 #{e92d4ff0}					;-- STMFD sp!, {r4-r11, lr}
			emit-i32 #{ed2d8b10}					;-- FSTMD sp!, {d8-d15}

			args: fspec/4
			either all [compiler/job/ABI = 'hard-float not empty? args][
				reg: freg: 1
				args: extract-arguments args		;-- cleanup and reverse arguments order
				fargs-nb: count-floats args
				
				foreach arg args [					;-- process in reverse order
					either find [float! float64! float32!] arg/1 [
						emit-push-float fargs-nb - freg arg 		 ;-- push in reverse order
						freg: freg + 1
					][
						emit-i32 #{e92d00}		;-- PUSH {r<n>}
						emit-i32 to char! shift/left 1 args-nb - reg ;-- push in reverse order
						reg: reg + 1
					]
				]
			][
				repeat i args-nb [
					emit-i32 #{e92d00}				;-- PUSH {r<n>}
					emit-i32 to char! shift/left 1 args-nb - i	;-- push in reverse order
				]
			]
			if PIC? [
				emit-i32 #{e1a0900f}				;-- MOV sb, pc
				pools/collect emitter/tail-ptr + 1 + 2 ;-- +1 adjustment for CALL first opcode
				emit-i32 #{e0499000}				;-- SUB sb, r0
			]
		]
			
		;-- Red/System standard function prolog --	
		
		emit-i32 #{e92d4800}						;-- PUSH {fp,lr}
		emit-i32 #{e1a0b00d}						;-- MOV fp, sp
		
		emit-push pick [-2 0] to logic! all [attribs find attribs 'catch]	;-- push catch flag
		emit-push 0									;-- keep stack aligned on 64-bit
		
		unless zero? locals-size [
			locals-size: round/to/ceiling locals-size 4
			either locals-size > 255 [
				emit-load-imm32/reg locals-size 4
				emit-i32 #{e04dd004}				;-- SUB sp, sp, r4
			][
				emit-i32 join #{e24dd0}	to char! locals-size ;-- SUB sp, sp, locals-size
			]
		]
	]

	emit-epilog: func [
		name [word! path!] locals [block!] args-size [integer!] locals-size [integer!]
		/local fspec attribs
	][
		if verbose >= 3 [print [">>>building:" uppercase mold to-word name "epilog"]]
		
		emit-i32 #{e1a0d00b}						;-- MOV sp, fp		; catch flag is skipped
		emit-i32 #{e8bd4800}						;-- POP {fp,lr}

		either compiler/check-variable-arity? locals [
			emit-i32 #{e8bd0004}					;-- POP {r2}		; skip arguments count
			emit-i32 #{e8bd0004}					;-- POP {r2}		; skip arguments pointer
			emit-i32 #{e8bd0004}					;-- POP {r2}		; get stack offset
			emit-i32 #{e08dd002}					;-- ADD sp, sp, r2	; skip arguments list (clears stack)
		][
			unless zero? args-size [
				emit-op-imm32
					#{e28dd000}						;-- ADD sp, sp, args-size
					round/to/ceiling args-size 4
			]
		]
		
		fspec: select/only compiler/functions name
		
		either any [
			fspec/5 = 'callback
			all [
				attribs: compiler/get-attributes fspec/4
				any [find attribs 'cdecl find attribs 'stdcall]
			]
		][
			emit-hf-return fspec/4
			emit-i32 #{ecbd8b10}					;-- FLDMIAD sp!, {d8-d15}
			emit-i32 #{e8bd4ff0}					;-- LDMFD sp!, {r4-r11, lr}
			emit-i32 #{e12fff1e}					;-- BX lr
		][
			emit-i32 #{e1a0f00e}					;-- MOV pc, lr
		]

		pools/mark-entry-point name
	]
]
#' Contribution of individual links
#' @param D A list returned by proc_analysis
#' @param ... Additional arguments to be passed to PACo
#' @return A list with added object jacknife, containing the mean and upper CI values for each link
#' @export
paco_links <- function(D, ...)
{
   HP.ones <- which(D$HP > 0, arr.ind=TRUE)
   SQres.jackn <- matrix(rep(NA, sum(D$HP)^2), sum(D$HP))# empty matrix of jackknifed squared residuals
   colnames(SQres.jackn) <- paste(rownames(D$proc$X),rownames(D$proc$Yrot), sep="-") #colnames identify the H-P link
   t.critical = qt(0.975,sum(D$HP)-1) #Needed to compute 95% confidence intervals.
   for(i in c(1:sum(D$HP))) #PACo setting the ith link = 0
   {
      HP_ind <- D$HP
      HP_ind[HP.ones[i,1],HP.ones[i,2]]=0
      PACo.ind <- PACo(list(H=D$H, P=D$P, HP=HP_ind), method=D$method, ...)
      Proc.ind <- vegan::procrustes(X=PACo.ind$H_PCo, Y=PACo.ind$P_PCo) 
      res.Proc.ind <- c(residuals(Proc.ind))
      res.Proc.ind <- append(res.Proc.ind, NA, after= i-1)
      SQres.jackn[i, ] <- res.Proc.ind   #Append residuals to matrix of jackknifed squared residuals
   } 
   SQres.jackn <- SQres.jackn^2 #Jackknifed residuals are squared
   SQres <- (residuals(D$proc))^2 # Vector of original square residuals
   #jackknife calculations:
   SQres.jackn <- SQres.jackn*(-(sum(D$HP)-1))
   SQres <- SQres*sum(D$HP)
   SQres.jackn <- t(apply(SQres.jackn, 1, "+", SQres)) #apply jackknife function to matrix
   phi.mean <- apply(SQres.jackn, 2, mean, na.rm = TRUE) #mean jackknife estimate per link
   phi.UCI <- apply(SQres.jackn, 2, sd, na.rm = TRUE) #standard deviation of estimates
   phi.UCI <- phi.mean + t.critical * phi.UCI/sqrt(sum(D$HP))
   D$jackknife <- list(mean = phi.mean, upper = phi.UCI)
   return(D)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap", "backtrack", "tswap", "r00"
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42, method="r0")
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="r0")
{
   method <- match.arg(method, c("r0", "r1", "r2", "r00", "c0", "swap", "tswap", "backtrack", "quasiswap"))
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      permuted_HP <- vegan::commsimulator(D$HP, method)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   D$method <- method
   return(D)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap", "backtrack", "tswap", "r00"
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42, method="r0")
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="r0")
{
   method <- match.arg(method, c("r0", "r1", "r2", "r00", "c0", "swap", "tswap", "backtrack", "quasiswap"))
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      permuted_HP <- vegan::commsimulator(D$HP, method)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    zero.eig <- which(abs(D.eig$values)- epsilon < epsilon)
    D.eig$values[zero.eig] <- 0
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            toto.cor$values[zero.eig.cor] <- 0
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap"
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42)
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="NA")
{
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      permuted_HP <- commsimulator(D$HP, method)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}

## conditional calculated field: mutate and ddply; see documentation for ddply
## groups: use selectInput with multiple=TRUE and selectize = FALSE
## http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information

## GitHub Hosting example: https://gist.github.com/mattbrehmer/5645155
## Alternative to ggplot2: https://github.com/ramnathv/rCharts

#options(error = browser)
# NULL, browser, etc.
options(shiny.error=function() {
  ## skip validation errors
  if(!inherits(eval.parent(expression(e)), "validation")) browser()
})
options(shiny.trace = FALSE)  # change to TRUE for trace
#options(shiny.reactlog=TRUE)

require(shiny); require(reshape); require(ggplot2); require(Hmisc); require(uuid); #require(plotly);
require(tables); require(tools); require(png); require(plyr); require(shinysky); require(Cairo)
require(knitr); require(rmarkdown); require(shinyAce)

options(shiny.usecairo=TRUE)


MoltenMeasuresName <- 'value'
YFunChoices <- c('Sum'='sum','Mean'='mean','Median'='median','Min'='min','Max'='max',
                 'Standard Deviation'='sd','Variance'='var')
InternalY <- '..y..'


GeomChoices <- c('Text'='text', 'Bar'='bar','Line'='line',
                 'Area'='area',  'Point'='point',
                 'Path'='path','Polygon'='polygon',
                 'Boxplot'='boxplot')
StatChoices <- c('Identity'='identity','Count'='bin','Summary'='summary','Boxplot'='boxplot')


getAesChoices <- function(geom, stat='identity'){
  switch(geom,
         'text'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                           'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                'Color'=c('Alpha'='aesAlpha'),
                                'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                                'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                     'Color'=c('Alpha'='aesAlpha'),
                                     'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                     'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     )
        ),

        'bar'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType','Weight'='aesWeight'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType','Weight'='aesWeight'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'line'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType',
                                           'Grouping'='aesGroup'),
                                'Color'=c('Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType',
                                                'Grouping'='aesGroup'),
                                     'Color'=c('Alpha'='aesAlpha')
                     )
        ),

        'area'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'point'=switch(stat,
                      'bin'=list('Coordinates'=c('X'='aesX'),
                                 'Common'=c('Color'='aesColor','Size'='aesSize',
                                            'Shape'='aesShape'),
                                 'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      ),
                      'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                      'Common'=c('Color'='aesColor','Size'='aesSize',
                                                 'Shape'='aesShape'),
                                      'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      )
        ),

        'boxplot'=switch(stat,
                         'boxplot'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                        'Common'=c('Color'='aesColor','Size'='aesSize',
                                                   'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                        'Color'=c('Border Color'='aesBorderColor',
                                                  'Alpha'='aesAlpha')
                         ),
                         'identity'=list('Coordinates'=c('X'='aesX','Y Middle'='aesMiddle',
                                                         'Y Lower'='aesLower','Y Upper'='aesUpper',
                                                         'Y Min'='aesYmin','Y Max'='aesYmax'),
                                         'Common'=c('Color'='aesColor','Size'='aesSize',
                                                    'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                         'Color'=c('Border Color'='aesBorderColor',
                                                   'Alpha'='aesAlpha')
                         )
        )

  )
}

AesChoicesSimpleList <- unique(unlist(lapply(GeomChoices, getAesChoices), use.names=FALSE))

fonttable <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE,
                        text='
Short,Canonical
mono,Courier
sans,Helvetica
serif,Times
,AvantGarde
,Bookman
,Helvetica-Narrow
,NewCenturySchoolbook
,Palatino
,URWGothic
,URWBookman
,NimbusMon
URWHelvetica,NimbusSan
,NimbusSanCond
,CenturySch
,URWPalladio
URWTimes,NimbusRom
')
FontFamilyChoices <- as.vector(t(as.matrix(fonttable)))
FontFamilyChoices <- FontFamilyChoices[FontFamilyChoices!='']

FontFaceChoices <- c("plain","bold","italic","bold.italic")


#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list()
IMMA.parameters  <- list()
IMMA.definitions <- list()

# Core section
IMMA.attachments[[100]] <- 'core'

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH')

# For each parameter, provide an array specifying:
#    Its length in characters, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)
#ICOADS attachment
IMMA.attachments[[1]] = 'icoads';
IMMA.parameters[[1]]  = c('BSI','B10','B1','DCK','SID','PT',
                          'DUPS','DUPC','TC','PB','WX','SX',
			  'C2','SQZ','SQA','AQZ','AQA','UQZ',
			  'UQA','VQZ','VQA','PQZ','PQA','DQZ',
			  'DQA','ND','SF','AF','UF','VF','PF',
			  'RF','ZNC','WNC','BNC','XNC','YNC',
			  'PNC','ANC','GNC','DNC','SNC','CNC',
			  'ENC','FNC','TNC','QCE','LZ','QCZ')
IMMA.definitions[[1]] = list(
    'BSI'  = list( 1, NULL,  NULL,  NULL, NULL, 1., 1 ),
    'B10'  = list( 3, 1.,    648.,  NULL, NULL, 1., 1 ),
    'B1'   = list( 2, 0.,    99.,   NULL, NULL, 1., 1 ),
    'DCK'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'SID'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'PT'   = list( 2, 0.,    15.,   NULL, NULL, 1., 1 ),
    'DUPS' = list( 2, 0.,    14.,   NULL, NULL, 1., 1 ),
    'DUPC' = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'TC'   = list( 1, 0.,    1.,    NULL, NULL, 1., 1 ),
    'PB'   = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'WX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'SX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'C2'   = list( 2, 0.,    40.,   NULL, NULL, 1., 1 ),
    'SQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'SQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'AQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'AQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'UQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'UQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'VQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'VQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'PQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'PQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'DQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'DQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'ND'   = list( 1, 1.,    2.,    NULL, NULL, 1., 1 ),
    'SF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'AF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'UF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'VF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'PF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'RF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'ZNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'WNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'BNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'XNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'YNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'PNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ANC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'GNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'DNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'SNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'CNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ENC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'FNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'TNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'QCE'  = list( 2, 0.,    63.,   NULL, NULL, 1., 1 ),
    'LZ'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'QCZ'  = list( 2, 0.,    31.,   NULL, NULL, 1., 1 )
)
# IMMT2 attachment
IMMA.attachments[[2]] = 'immt2'
IMMA.parameters[[2]]  = c('OS','OP','FM','IX','W2','SGN',
                          'SGT','SGH','WMI','SD2','SP2',
			  'SH2','IS','ES','RS','IC1','IC2',
			  'IC3','IC4','IC5','IR','RRR','TR',
			  'QCI','QI1','QI2','QI3','QI4',
			  'QI5','QI6','QI7','QI8','QI9',
			  'QI10','QI11','QI12','QI13','QI14',
			  'QI15','QI16','QI17','QI18','QI19',
			  'QI20','QI21','HDG','COG','SOG',
			  'SLL','SLHH','RWD','RWS')
IMMA.definitions[[2]] = list(
    'OS'   = list( 1, 0.,   6.,   NULL,  NULL,  1.,  1 ),
    'OP'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'FM'   = list( 2, 0.,   8.,   NULL,  NULL,  1.,  1 ),
    'IX'   = list( 1, 1.,   7.,   NULL,  NULL,  1.,  1 ),
    'W2'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGN'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGT'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'SGH'  = list( 2, 0.,   50.,  56.,   99.,   1.,  1 ),
    'WMI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SD2'  = list( 2, 0.,   38.,  NULL,  NULL,  1.,  1 ),
    'SP2'  = list( 2, 0.,   30.,  99.,   99.,   1.,  1 ),
    'SH2'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'IS'   = list( 1, 1.,   5.,   NULL,  NULL,  1.,  1 ),
    'ES'   = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'RS'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'IC1'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC2'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC3'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC4'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC5'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IR'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'RRR'  = list( 3, 0.,   999., NULL,  NULL,  1.,  1 ),
    'TR'   = list( 1, 1.,   9.,   NULL,  NULL,  1.,  1 ),
    'QCI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI1'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI2'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI3'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI4'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI5'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI6'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI7'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI8'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI9'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI10' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI11' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI12' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI13' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI14' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI15' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI16' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI17' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI18' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI19' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI20' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI21' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'HDG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'COG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'SOG'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLL'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLHH' = list( 3, -99., 99.,  NULL,  NULL,  1.,  1 ),
    'RWD'  = list( 3, 1.,   362., NULL,  NULL,  1.,  1 ),
    'RWS'  = list( 3, 0.0,  99.9, NULL,  NULL,  0.1, 1 )
)
# Model quality control attachment
IMMA.attachments[[3]] = 'mqc';
IMMA.parameters[[3]]  = c('CCCC','BUID','BMP','BSWU','SWU',
                          'BSWV','SWV','BSAT','BSRH','SRH',
			  'SIX','BSST','MST','MSH','BY',
			  'BM','BD','BH','BFL')
IMMA.definitions[[3]] = list(
    'CCCC' = list( 4, 65.,   90.,    NULL,  NULL,  NULL,  3 ),
    'BUID' = list( 6, 48.,   57.,    65.,   90.,   NULL,  3 ),
    'BMP'  = list( 5, 870.0, 1074.6, NULL,  NULL,  0.1,   1 ),
    'BSWU' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWU'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSWV' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWV'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSAT' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSRH' = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SRH'  = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SIX'  = list( 1, 2.,    3.,     NULL,  NULL,  1.,    1 ),
    'BSST' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'MST'  = list( 1, 0.,    9.,     NULL,  NULL,  1.,    1 ),
    'MSH'  = list( 3, 0.,    999.,   NULL,  NULL,  1.,    1 ),
    'BY'   = list( 4, 0.,    9999.,  NULL,  NULL,  1.,    1 ),
    'BM'   = list( 2, 1.,    12.,    NULL,  NULL,  1.,    1 ),
    'BD'   = list( 2, 1.,    31.,    NULL,  NULL,  1.,    1 ),
    'BH'   = list( 2, 0.,    23.,    NULL,  NULL,  1.,    1 ),
    'BFL'  = list( 2, 0.,    99.,    NULL,  NULL,  1.,    1 )
)
# Metadata attachment
IMMA.attachments[[4]] = 'metadata'
IMMA.parameters[[4]]  = c('C1M','OPM','KOV','COR','TOB','TOT',
                          'EOT','LOT','TOH','EOH','SIM','LOV',
			  'DOS','HOP','HOT','HOB','HOA','SMF',
			  'SME','SMV')
IMMA.definitions[[4]] = list(
    'C1M' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'OPM' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'KOV' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'COR' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'TOB' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOT' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOH' = list( 1, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOH' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'SIM' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOV' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'DOS' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'HOP' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOT' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOB' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOA' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'SMF' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SME' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SMV' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 )
)
# Historical attachment
IMMA.attachments[[5]] = 'historical'
IMMA.parameters[[5]]  = c('WFI','WF','XWI','XW','XDI','XD',
                       'SLPI','TAI','TA','XNI','XN')
IMMA.definitions[[5]] = list(
    'WFI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'WF'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XWI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XW'   = list( 3, NULL,  NULL,  NULL,  NULL,  0.1,   1 ),
    'XDI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XD'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SLPI' = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TAI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TA'   = list( 4, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XNI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XN'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 )
)
# Supplemental attachment
IMMA.attachments[[99]] = 'supplemental'
IMMA.parameters[[99]]  = c('ATTE','SUPD')
IMMA.definitions[[99]] = list(
    'ATTE' = list( 1,     NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SUPD' = list( NULL,  NULL,  NULL,  NULL,  NULL,  NULL,  3 )
)

# Find out which attachment a parameter is in
IMMA.whichAttachment <- function(parameter) {
    for(i in c(100,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

# Check the value for a parameter is inside its acceptable range(s)
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[7] == 3 ) {
        return(result); 
    }
  
    w<-which(!is.null(ob[[parameter]]) & !is.na(ob[[parameter]]) &
             ((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] )) |
             ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= ob[[parameter]] )))
    if(length(w<length(ob[[parameter]]) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        definitions<-IMMA.definitionsFor(parameter)

        # Treat differently according to type
        if(definitions[7]==3) { # Character, just print
          w<-which(!is.null(ob[[parameter]]))
          if(length(w)>0) {
              if(!is.null(definitions[1])) {
                 Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],ob[[parameter]][w])
              } else {  # Unspecified length, supplementary only - use length of data
                 Result[w]<-sprintf("%s%s",Result[w],ob[[parameter]][w])
              }
          }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
              if(!is.null(definitions[1])) {
                 Result[!w]<-sprintf(sprintf("%%s%%.%ss",definitions[1]),Result[!w],' ')
              } else {  # Unspecified length, supplementary only - use length of data
                 Result<-sprintf("%s%s",Result[!w],' ')
              }
          }
        }
        if(definitions[7]==1) { # Integer - check, scale, round and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             Result[w]<-sprintf(sprintf("%%s%%.%dd",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
        if(definitions[7]==2) { # Base36 - check, scale, convert and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             enc<-IMMA.encode_base36(round)
             Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
      }
    # Done all the parameters, add the ID and length to the start
    # (except for core)
    if ( attachment != 100 ) {
        if ( attachment == 99 ) {
            Result = sprintf(" 0%s",Result)
        } else {
            Result = sprintf("%2d%s",nchar(Result)+4,Result)
        }
        Result = sprintf("%2d%s",attachment,Result)
    }

    return(Result)
  }

# Make a string version of the whole record
IMMA.packString <- function(ob) {
    Result = rep('',length(ob$YR))
    for(attachment in c(100,1,2,3,4,5,99)) {
      w<-IMMA.hasAttachment(ob,attachment)
      if(length(w)>0) {
        Result[w]<-sprintf("%s%s",Result,IMMA.encodeAttachment(ob[w,],attachment))
      }
    }
    return(Result)
}

# Unpack the string version of an attachment into a data frame
IMMA.decodeAttachment <- function(ob.strings,attachment){
   Result<-data.frame()
   pstart<-1
   for ( parameter in IMMA.parameters[[attachment]]) {
      definitions<-IMMA.definitionsFor(parameter)
      pstring<-substr(ob.strings,pstart,pstart+definitions[1])
      pstart<-pstart+definitions[1]
      pstring<-sub("^\\s+", "", pstring) # strip leading blanks
      w<-which(nchar(pstring)==0)        # all blank - set to missing
      
      if(definitions[7]==3) { # Character,add directly
        if(length(w)>0) {
           is.na(pstring[w])<-TRUE
        }
        Result[[parameter]]<-pstring
      }
      if(definitions[7]==2) { # Base36 - convert, scale and add
        pint<-integer(length(pstring))
        if(length(w)>0) {
           is.na(pint[w])<-TRUE
        }
        if(length(w)<length(pint)) {
          pint[-w]<-IMMA.decode_base36(pstring[-w])
        }
        Result[[parameter]]<-pint*dimensions[6]
      }
      if(definitions[7]==1) { numeric data
        pint<-integer(length(pstring))
        if(length(w)>0) {
           is.na(pint[w])<-TRUE
        }
        Result[[parameter]]<-pint*dimensions[6]
      }
    }
   return(Result)
}

# Unpack from string format into a data frame
IMMA.unpack <- function(ob.strings) {

   # split the strings into a separate vector for each attachment
   atsplit<-data.frame()
   # Core is allways present and first
   atsplit[[100]]<-substr(ob.strings,1,108)
   ob.strings<-substring(ob.strings,109)
   w<-which(nchar(ob.strings)>4)
   while(length(w)>0) { 
     
   
}


#' Read in all the IMMA records from a connection
#'
#' Currently only reads the core element - discards attachments
#'
#' I'm not sure how to read variable-format records in an efficient fashion
#'  so at the moment this only looks at the fixed-format component.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
#' gets the current screen width.
#'
#' It's highly OS specific, I do ignore if it works on OSX

getConsoleWidth <- function() {
  os <- .Platform$OS.type
  if ( os  %in% c("unix", "Darwin" )) {
    as.numeric(system('tput cols', intern=TRUE))
  } else {
    return(tryCatch({
      txt <- system('cmd /c "mode con /status | grep  \"Colonne:\"',
                    intern=TRUE)
      txt <- unlist(strsplit(txt, ":"))[2]
      as.numeric(txt)
    }, error = function (err) {
      ## please God forgive me
      80
    }))
  }
}

#' Classe S4 per ProgressBar
#'
#' @name ProgressBar
#' @rdname ProgressBar
#' @aliases ProgressBar-class
#' @title ProgressBar with labels
#' @slot value current value 
#' @slot min minimum value
#' @slot max maximum value
#' @slot char char to use as token for progress
#' @slot width current screen width, autoevaluated
#' @slot time time since the beginning of ProgressBar
#' @exportClass ProgressBar
#' @export ProgressBar
#' @import methods

ProgressBar <- setClass(
  "ProgressBar",
  representation(
    value= "numeric",
    min="numeric",                        
    max="numeric",
    char="character",
    width="numeric",
    time="POSIXct"))


setMethod(
  "initialize",
  signature("ProgressBar"),
  function(.Object, min=0, max=1, char="=") {
    .Object@min <- min
    .Object@max <- max
    .Object@char <- char
    .Object@width <- getConsoleWidth()
    .Object@time <- Sys.time()
    return(.Object)
  })

#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @docType methods
#' @rdname kill-methods



setGeneric(
  "kill",
  function(x){
    standardGeneric("kill")
  })
#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @aliases kill,ProgressBar-method

setMethod(
  "kill",
  signature("ProgressBar"),
  function(x) {
    cat("\n", file = stderr())
    flush.console()
  })

#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @docType methods
#' @rdname update-methods
#' @export

setGeneric(
  "update",
  function(x, value, label="") {
    standardGeneric("update")
  })
#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @export
#' @rdname update
#' @aliases update,ProgressBar,ANY-method

setMethod(
  "update",
  signature("ProgressBar", "ANY"),
  function(x, value, label="") {    
    x@value  <- value
    min <- x@min
    if(value == min) {
      x@time <- Sys.time()
    }    
    max <- x@max
    char <- x@char
    elapsed <- as.numeric(difftime(Sys.time(),  x@time, units="secs"))
    V <- value/elapsed
    eta <- (max - value) / V
    eta <- if(value == min) {
      "--:--"
    } else if(eta > 3600) {
      sprintf("%02i:%02i:%02i", as.integer(floor(eta/3600)),
              as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    } else {
      sprintf("%02i:%02i", as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    }
    
    if (!is.finite(value) || value < min || value > max)
      return()
    
    nw <- nchar(char,"w")
    pad <- 12 + nchar(eta)
    nlabel <- nchar(label)
    width <- trunc(x@width/nw) - pad - nlabel
    nb <- round(width * (value - min)/(max - min))
    pc <- round(100 * (value - min)/(max - min))
    if(nlabel > 0) {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% - %s %s", pc, label, eta)), collapse = ""),
          file = stderr())
    } else {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% %s", pc, eta)), collapse = ""),
          file = stderr())
      
    }
    flush.console()
    invisible(x)
  })
#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 26, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/cogsci_2015/paper/pics/")
source("rscripts/helpers.r")

# get prior expectations
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = paste(priorexpectations$effect, priorexpectations$object)

# histogram of expectations
ggplot(priorexpectations, aes(x=expectation_corr/15)) +
  geom_histogram() +
  scale_x_continuous(name="Expected value of prior distribution") +
  scale_y_continuous(name="Number of cases")
ggsave("priorexpectations-histogram.pdf")


# get prior allstate-probs
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
row.names(priorprobs) = paste(priorprobs$effect, priorprobs$object)
head(priorprobs)

# histogram of expectations
ggplot(priorprobs, aes(x=X15)) +
  geom_histogram() +
  scale_x_continuous(name="Prior all-state probability") +
  scale_y_continuous(name="Number of cases")
ggsave("priorallprobs-histogram.pdf")


#####################################
# plot model predictions: expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

toplot = droplevels(subset(some, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-expectations.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_exps = ggplot(toplot, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Prior expected number of objects") +
  scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Posterior predicted number of objects")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-expectations-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-expectations-uniform-regular.pdf",width=6.5,height=4.5)


# plot model predictions: allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5 & State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-uniform-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-allprobs.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData")
summary(mp)
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" &  State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-allprobs-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-allprobs-uniform-regular.pdf",width=6.5,height=4.5)

library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_exps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_exps_nolegend = p_exps + theme(legend.position="none")
p_probs_nolegend = p_probs + theme(legend.position="none")

#pdf("rsa-predictions-uniform.pdf",width=10,height=4)
pdf("rsa-predictions.pdf",width=10,height=4)
grid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()

s = subset(r, quantifier=="Some" & Proportion == "100")
nrow(s)

library(lmerTest)
m=lmer(normresponse ~ AllPriorProbability + (1+AllPriorProbability|workerid) + (1|Item), data=s)
summary(m)



#####################################
# plot model predictions: wonkiness
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(wr, QUD == "how-many" & Alternatives == "0_basic" & WonkyWorldPrior == .5 & Wonky == "true"))
nrow(toplot)

toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_color_manual(values=c("#F8766D","#00BF7D","#00B0F6")) +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior expected number of objects") +
  scale_y_continuous(breaks=seq(0,1,by=.25),name="Model predicted wonkiness probability")

ggsave("model-wonkiness-uniform.pdf",width=5.5,height=4)#,width=30,height=10)
ggsave("model-wonkiness-binomial.pdf",width=5.5,height=4)#,width=30,height=10)


###############
## EMPIRICAL PLOTS
###############

# expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")

agr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh

min(agr[agr$quantifier == "Some",]$ProportionResponse)
max(agr[agr$quantifier == "Some",]$ProportionResponse)

p_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=quantifier)) +
  geom_point() +
  #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(breaks=seq(1,15,by=2),name="Posterior mean number of objects") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior mean number of objects")  
ggsave(file="meanresponses.pdf",width=5,height=3.7)


# allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData")

# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)
tmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)
ub = subset(agrr, Proportion == "100")
ub = droplevels(ub)

p_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=quantifier)) +
  geom_point() +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(limits=c(0,1),name="Posterior probability of all-state ") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(limits=c(0,1),name="Prior probability of all-state")  
ggsave(file="empirical-allprobs.pdf",width=5,height=3.7)


library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_eexps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_eexps_nolegend = p_eexps + theme(legend.position="none")
p_eprobs_nolegend = p_eprobs + theme(legend.position="none")

pdf("empirical-results.pdf",width=10,height=4)
grid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()


# plot subejct variability for exclusion
ggplot(r[r$Proportion == "0",], aes(x=normresponse,fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)  
ggsave("subject-variability.pdf",width=5.5,height=4)




############
# empirical wonkiness posteriors
############
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData")
head(r)
nrow(r)

ggplot(r, aes(x=response, fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)
ggsave("subject-variability-wonkiness.pdf",width=7,height=25)

toplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN="mean", data=r)
toplot = droplevels(subset(toplot, quantifier %in% c("All","Some","None")))
toplot$Quantifier = factor(tolower(toplot$quantifier), levels=c("all", "none","some"))

ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier)) +
  geom_point() +
  geom_smooth() +
  scale_color_manual(values=c("#F8766D","#00BF7D","#00B0F6")) +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior expected number of objects") +
  scale_y_continuous(breaks=seq(0,1,by=.25),name="Mean empirical wonkiness probability")  
ggsave(file="empirical-wonkiness.pdf",width=5.5,height=4)


######################
### NOAH'S MODEL PREDICTIONS
rsa_allstate = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-allstate.csv",header=F)
head(rsa_allstate)
colnames(rsa_allstate) = c("BinomialCW","PosteriorAllProbability")
ggplot(rsa_allstate, aes(x=BinomialCW,y=PosteriorAllProbability)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Binomial coin weight") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions.pdf",width=4.5,height=3.5)  

rsa_expectation = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectation.csv",header=F)
head(rsa_expectation)
colnames(rsa_expectation) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expectation, aes(x=PriorExpectation/15,y=PosteriorExpectation/15)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior expectation")  
ggsave("noahs-expectation-predictions.pdf",width=4.5,height=3.5)  

rsa_expall = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectedVsallstate.csv",header=F)
head(rsa_expall)
colnames(rsa_expall) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expall, aes(x=PriorExpectation/15,y=PosteriorExpectation)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions-bypriorexp.pdf",width=4.5,height=3.5)  


#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 26, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/cogsci_2015/paper/pics/")
source("rscripts/helpers.r")

# get prior expectations
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = paste(priorexpectations$effect, priorexpectations$object)

# histogram of expectations
ggplot(priorexpectations, aes(x=expectation_corr/15)) +
  geom_histogram() +
  scale_x_continuous(name="Expected value of prior distribution") +
  scale_y_continuous(name="Number of cases")
ggsave("priorexpectations-histogram.pdf")


# get prior allstate-probs
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
row.names(priorprobs) = paste(priorprobs$effect, priorprobs$object)
head(priorprobs)

# histogram of expectations
ggplot(priorprobs, aes(x=X15)) +
  geom_histogram() +
  scale_x_continuous(name="Prior all-state probability") +
  scale_y_continuous(name="Number of cases")
ggsave("priorallprobs-histogram.pdf")


#####################################
# plot model predictions: expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

toplot = droplevels(subset(some, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-expectations.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_exps = ggplot(toplot, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Prior expected number of objects") +
  scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Posterior predicted number of objects")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-expectations-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-expectations-uniform-regular.pdf",width=6.5,height=4.5)


# plot model predictions: allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5 & State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-uniform-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-allprobs.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData")
summary(mp)
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" &  State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-allprobs-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-allprobs-uniform-regular.pdf",width=6.5,height=4.5)

library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_exps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_exps_nolegend = p_exps + theme(legend.position="none")
p_probs_nolegend = p_probs + theme(legend.position="none")

#pdf("rsa-predictions-uniform.pdf",width=10,height=4)
pdf("rsa-predictions.pdf",width=10,height=4)
grid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()

s = subset(r, quantifier=="Some" & Proportion == "100")
nrow(s)

library(lmerTest)
m=lmer(normresponse ~ AllPriorProbability + (1+AllPriorProbability|workerid) + (1|Item), data=s)
summary(m)



#####################################
# plot model predictions: wonkiness
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(wr, QUD == "how-many" & Alternatives == "0_basic" & WonkyWorldPrior == .5 & Wonky == "true"))
nrow(toplot)

toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_color_manual(values=c("#F8766D","#00BF7D","#00B0F6")) +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior expected number of objects") +
  scale_y_continuous(breaks=seq(0,1,by=.25),name="Model predicted wonkiness probability")

ggsave("model-wonkiness-uniform.pdf",width=5.5,height=4)#,width=30,height=10)
ggsave("model-wonkiness-binomial.pdf",width=5.5,height=4)#,width=30,height=10)


###############
## EMPIRICAL PLOTS
###############

# expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")

agr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh

min(agr[agr$quantifier == "Some",]$ProportionResponse)
max(agr[agr$quantifier == "Some",]$ProportionResponse)

p_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=quantifier)) +
  geom_point() +
  #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(breaks=seq(1,15,by=2),name="Posterior mean number of objects") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior mean number of objects")  
ggsave(file="meanresponses.pdf",width=5,height=3.7)


# allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData")

# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)
tmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)
ub = subset(agrr, Proportion == "100")
ub = droplevels(ub)

p_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=quantifier)) +
  geom_point() +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(limits=c(0,1),name="Posterior probability of all-state ") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(limits=c(0,1),name="Prior probability of all-state")  
ggsave(file="empirical-allprobs.pdf",width=5,height=3.7)


library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_eexps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_eexps_nolegend = p_eexps + theme(legend.position="none")
p_eprobs_nolegend = p_eprobs + theme(legend.position="none")

pdf("empirical-results.pdf",width=10,height=4)
grid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()


# plot subejct variability for exclusion
ggplot(r[r$Proportion == "0",], aes(x=normresponse,fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)  
ggsave("subject-variability.pdf",width=5.5,height=4)




############
# empirical wonkiness posteriors
############
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData")
head(r)
nrow(r)

ggplot(r, aes(x=response, fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)
ggsave("subject-variability-wonkiness.pdf",width=7,height=25)

toplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN="mean", data=r)
toplot = droplevels(subset(toplot, quantifier %in% c("All","Some","None")))
toplot$Quantifier = factor(tolower(toplot$quantifier), levels=c("all", "none","some"))

ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier)) +
  geom_point() +
  geom_smooth() +
  scale_color_manual(values=c("#F8766D","#00BF7D","#00B0F6")) +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior expected number of objects") +
  scale_y_continuous(breaks=seq(0,1,by=.25),name="Mean empirical wonkiness probability")  
ggsave(file="empirical-wonkiness.pdf",width=5.5,height=4)


######################
### NOAH'S MODEL PREDICTIONS
rsa_allstate = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-allstate.csv",header=F)
head(rsa_allstate)
colnames(rsa_allstate) = c("BinomialCW","PosteriorAllProbability")
ggplot(rsa_allstate, aes(x=BinomialCW,y=PosteriorAllProbability)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Binomial coin weight") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions.pdf",width=4.5,height=3.5)  

rsa_expectation = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectation.csv",header=F)
head(rsa_expectation)
colnames(rsa_expectation) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expectation, aes(x=PriorExpectation/15,y=PosteriorExpectation/15)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior expectation")  
ggsave("noahs-expectation-predictions.pdf",width=4.5,height=3.5)  

rsa_expall = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectedVsallstate.csv",header=F)
head(rsa_expall)
colnames(rsa_expall) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expall, aes(x=PriorExpectation/15,y=PosteriorExpectation)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions-bypriorexp.pdf",width=4.5,height=3.5)  


#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and 
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/", 
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#' 
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    if (is.element('output', names(object))) {
      if (is.element("data", names(object$output$options))) {
        data_restore_on_exit <- object$output$options$data
        on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
        object$output$options$data <- NULL
      }
      if (is.element("label", names(object$output$options))) {
        label_restore_on_exit <- object$output$options$label
        on.exit(object$output$options$label <- label_restore_on_exit, add = TRUE)
        object$output$options$label <- NULL
      }
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

 # TODO: (RK) Read default_options in from config, so a user can
 # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- list(data = switch(1 + is.element("data", names(object$output$options)), 
                              NULL, object$output$options$data), 
                label = switch(1 + is.element("label", names(object$output$options)), 
                               NULL, object$output$options$label))

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list()
IMMA.parameters  <- list()
IMMA.definitions <- list()

# Core section
IMMA.attachments[[100]] <- 'core'

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH')

# For each parameter, provide an array specifying:
#    Its length in characters, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)
#ICOADS attachment
IMMA.attachments[[1]] = 'icoads';
IMMA.parameters[[1]]  = c('BSI','B10','B1','DCK','SID','PT',
                          'DUPS','DUPC','TC','PB','WX','SX',
			  'C2','SQZ','SQA','AQZ','AQA','UQZ',
			  'UQA','VQZ','VQA','PQZ','PQA','DQZ',
			  'DQA','ND','SF','AF','UF','VF','PF',
			  'RF','ZNC','WNC','BNC','XNC','YNC',
			  'PNC','ANC','GNC','DNC','SNC','CNC',
			  'ENC','FNC','TNC','QCE','LZ','QCZ')
IMMA.definitions[[1]] = list(
    'BSI'  = list( 1, NULL,  NULL,  NULL, NULL, 1., 1 ),
    'B10'  = list( 3, 1.,    648.,  NULL, NULL, 1., 1 ),
    'B1'   = list( 2, 0.,    99.,   NULL, NULL, 1., 1 ),
    'DCK'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'SID'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'PT'   = list( 2, 0.,    15.,   NULL, NULL, 1., 1 ),
    'DUPS' = list( 2, 0.,    14.,   NULL, NULL, 1., 1 ),
    'DUPC' = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'TC'   = list( 1, 0.,    1.,    NULL, NULL, 1., 1 ),
    'PB'   = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'WX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'SX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'C2'   = list( 2, 0.,    40.,   NULL, NULL, 1., 1 ),
    'SQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'SQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'AQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'AQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'UQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'UQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'VQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'VQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'PQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'PQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'DQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'DQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'ND'   = list( 1, 1.,    2.,    NULL, NULL, 1., 1 ),
    'SF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'AF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'UF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'VF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'PF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'RF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'ZNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'WNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'BNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'XNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'YNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'PNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ANC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'GNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'DNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'SNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'CNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ENC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'FNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'TNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'QCE'  = list( 2, 0.,    63.,   NULL, NULL, 1., 1 ),
    'LZ'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'QCZ'  = list( 2, 0.,    31.,   NULL, NULL, 1., 1 )
)
# IMMT2 attachment
IMMA.attachments[[2]] = 'immt2'
IMMA.parameters[[2]]  = c('OS','OP','FM','IX','W2','SGN',
                          'SGT','SGH','WMI','SD2','SP2',
			  'SH2','IS','ES','RS','IC1','IC2',
			  'IC3','IC4','IC5','IR','RRR','TR',
			  'QCI','QI1','QI2','QI3','QI4',
			  'QI5','QI6','QI7','QI8','QI9',
			  'QI10','QI11','QI12','QI13','QI14',
			  'QI15','QI16','QI17','QI18','QI19',
			  'QI20','QI21','HDG','COG','SOG',
			  'SLL','SLHH','RWD','RWS')
IMMA.definitions[[2]] = list(
    'OS'   = list( 1, 0.,   6.,   NULL,  NULL,  1.,  1 ),
    'OP'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'FM'   = list( 2, 0.,   8.,   NULL,  NULL,  1.,  1 ),
    'IX'   = list( 1, 1.,   7.,   NULL,  NULL,  1.,  1 ),
    'W2'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGN'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGT'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'SGH'  = list( 2, 0.,   50.,  56.,   99.,   1.,  1 ),
    'WMI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SD2'  = list( 2, 0.,   38.,  NULL,  NULL,  1.,  1 ),
    'SP2'  = list( 2, 0.,   30.,  99.,   99.,   1.,  1 ),
    'SH2'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'IS'   = list( 1, 1.,   5.,   NULL,  NULL,  1.,  1 ),
    'ES'   = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'RS'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'IC1'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC2'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC3'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC4'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC5'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IR'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'RRR'  = list( 3, 0.,   999., NULL,  NULL,  1.,  1 ),
    'TR'   = list( 1, 1.,   9.,   NULL,  NULL,  1.,  1 ),
    'QCI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI1'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI2'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI3'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI4'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI5'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI6'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI7'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI8'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI9'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI10' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI11' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI12' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI13' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI14' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI15' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI16' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI17' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI18' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI19' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI20' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI21' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'HDG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'COG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'SOG'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLL'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLHH' = list( 3, -99., 99.,  NULL,  NULL,  1.,  1 ),
    'RWD'  = list( 3, 1.,   362., NULL,  NULL,  1.,  1 ),
    'RWS'  = list( 3, 0.0,  99.9, NULL,  NULL,  0.1, 1 )
)
# Model quality control attachment
IMMA.attachments[[3]] = 'mqc';
IMMA.parameters[[3]]  = c('CCCC','BUID','BMP','BSWU','SWU',
                          'BSWV','SWV','BSAT','BSRH','SRH',
			  'SIX','BSST','MST','MSH','BY',
			  'BM','BD','BH','BFL')
IMMA.definitions[[3]] = list(
    'CCCC' = list( 4, 65.,   90.,    NULL,  NULL,  NULL,  3 ),
    'BUID' = list( 6, 48.,   57.,    65.,   90.,   NULL,  3 ),
    'BMP'  = list( 5, 870.0, 1074.6, NULL,  NULL,  0.1,   1 ),
    'BSWU' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWU'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSWV' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWV'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSAT' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSRH' = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SRH'  = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SIX'  = list( 1, 2.,    3.,     NULL,  NULL,  1.,    1 ),
    'BSST' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'MST'  = list( 1, 0.,    9.,     NULL,  NULL,  1.,    1 ),
    'MSH'  = list( 3, 0.,    999.,   NULL,  NULL,  1.,    1 ),
    'BY'   = list( 4, 0.,    9999.,  NULL,  NULL,  1.,    1 ),
    'BM'   = list( 2, 1.,    12.,    NULL,  NULL,  1.,    1 ),
    'BD'   = list( 2, 1.,    31.,    NULL,  NULL,  1.,    1 ),
    'BH'   = list( 2, 0.,    23.,    NULL,  NULL,  1.,    1 ),
    'BFL'  = list( 2, 0.,    99.,    NULL,  NULL,  1.,    1 )
)
# Metadata attachment
IMMA.attachments[[4]] = 'metadata'
IMMA.parameters[[4]]  = c('C1M','OPM','KOV','COR','TOB','TOT',
                          'EOT','LOT','TOH','EOH','SIM','LOV',
			  'DOS','HOP','HOT','HOB','HOA','SMF',
			  'SME','SMV')
IMMA.definitions[[4]] = list(
    'C1M' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'OPM' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'KOV' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'COR' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'TOB' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOT' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOH' = list( 1, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOH' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'SIM' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOV' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'DOS' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'HOP' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOT' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOB' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOA' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'SMF' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SME' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SMV' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 )
)
# Historical attachment
IMMA.attachments[[5]] = 'historical'
IMMA.parameters[[5]]  = c('WFI','WF','XWI','XW','XDI','XD',
                       'SLPI','TAI','TA','XNI','XN')
IMMA.definitions[[5]] = list(
    'WFI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'WF'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XWI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XW'   = list( 3, NULL,  NULL,  NULL,  NULL,  0.1,   1 ),
    'XDI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XD'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SLPI' = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TAI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TA'   = list( 4, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XNI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XN'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 )
)
# Supplemental attachment
IMMA.attachments[[99]] = 'supplemental'
IMMA.parameters[[99]]  = c('ATTE','SUPD')
IMMA.definitions[[99]] = list(
    'ATTE' = list( 1,     NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SUPD' = list( NULL,  NULL,  NULL,  NULL,  NULL,  NULL,  3 )
)

# Find out which attachment a parameter is in
IMMA.whichAttachment <- function(parameter) {
    for(i in c(100,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

# Check the value for a parameter is inside its acceptable range(s)
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[7] == 3 ) {
        return(result); 
    }
  
    w<-which(!is.null(ob[[parameter]]) & !is.na(ob[[parameter]]) &
             ((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] )) |
             ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= ob[[parameter]] )))
    if(length(w<length(ob[[parameter]]) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        definitions<-IMMA.definitionsFor(parameter)

        # Treat differently according to type
        if(definitions[7]==3) { # Character, just print
          w<-which(!is.null(ob[[parameter]]))
          if(length(w)>0) {
              if(!is.null(definitions[1])) {
                 Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],ob[[parameter]][w])
              } else {  # Unspecified length, supplementary only - use length of data
                 Result[w]<-sprintf("%s%s",Result[w],ob[[parameter]][w])
              }
          }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
              if(!is.null(definitions[1])) {
                 Result[!w]<-sprintf(sprintf("%%s%%.%ss",definitions[1]),Result[!w],' ')
              } else {  # Unspecified length, supplementary only - use length of data
                 Result<-sprintf("%s%s",Result[!w],' ')
              }
          }
        }
        if(definitions[7]==1) { # Integer - check, scale, round and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             Result[w]<-sprintf(sprintf("%%s%%.%dd",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
        if(definitions[7]==3) { # Base36 - check, scale, convert and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             enc<-IMMA.encode_base36(round)
             Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
      }
    # Done all the parameters, add the ID and length to the start
    # (except for core)
    if ( attachment != 100 ) {
        if ( attachment == 99 ) {
            Result = sprintf(" 0%s",Result)
        } else {
            Result = sprintf("%2d%s",nchar(Result)+4,Result)
        }
        Result = sprintf("%2d%s",attachment,Result)
    }

    return(Result)
  }

# Make a string version of the whole record
IMMA.packString <- function(ob) {
  
}




#' Read in all the IMMA records from a connection
#'
#' Currently only reads the core element - discards attachments
#'
#' I'm not sure how to read variable-format records in an efficient fashion
#'  so at the moment this only looks at the fixed-format component.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	result.df$gene <- factor(result.df$gene, levels=unique(as.character(result.df$gene)))
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "Combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  df = NULL
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  resultsSub <- resultsSub[resultsSub$score.type == "Combined",]
  ## if input dataframe is not null then update the target dataframe with the inputdf genes
  if (!(is.null(inputdf)))
  {
    temp <- as.data.frame(inputdf[,1])
    colnames(temp) <- c("gene")
    resultsSub <- plyr::join(temp,resultsSub,type="inner")          
  }
  ## sort the dataframe to match with results table
  if (cutoff > 0)
  {
    resultsSub <- resultsSub[order(-resultsSub$"score"),]
  }else{
    resultsSub <- resultsSub[order(resultsSub$"score"),]
  }
  temp <- resultsSub[resultsSub$cancer == cancer,]
  resultsSub <- resultsSub[resultsSub$cancer != cancer,]
  resultsSub <- rbind(temp,resultsSub)
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(updateProgress = NULL,cancer,inputdf,sample)
{
  if (sample == 'tumors'){
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }else{
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }
  
}

##' view 2
comp1view2Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined") 
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
    }
  }
}
## for user file input
comp1view2FilePlot = function(updateProgress = NULL,cancer,inputdf,sample){

  if (sample == 'tumors'){    
    og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }else{
    og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsog <- plyr::join(temp,rgsog,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste("<a href=\"http://www.genecards.org/cgi-bin/carddisp.pl?gene=",rgs[,1],"\">","Gene Card","</a>",sep="")
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsts <- plyr::join(temp,rgsts,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")

        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsog <- plyr::join(temp,rgsog,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsts <- plyr::join(temp,rgsts,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(updateProgress= NULL,cancer,score,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs) 
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}

## shinyFiles
## lubridate, dplyr
## R-blogger
## http://www.r-bloggers.com/read-excel-files-from-r/
## Plotly or animit

## conditional calculated field: mutate and ddply; see documentation for ddply
## groups: use selectInput with multiple=TRUE and selectize = FALSE
## DONE: add sample data mtcars
## http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information

## optimize what's to save for project
## GitHub Hosting example: https://gist.github.com/mattbrehmer/5645155
## Alternative to ggplot2: https://github.com/ramnathv/rCharts

#options(error = browser)
options(shiny.error=NULL) # NULL
options(shiny.trace = FALSE)  # change to TRUE for trace
#options(shiny.reactlog=TRUE)

require(shiny); require(reshape); require(ggplot2); require(Hmisc); require(uuid); #require(plotly);
require(tables); require(tools); require(png); require(plyr); require(shinysky); require(Cairo)
require(knitr); require(rmarkdown); require(shinyAce)

options(shiny.usecairo=TRUE)



InitialTextValue <- 'Xabcde-f9'

MoltenMeasuresName <- 'value'
YFunChoices <- c('Sum'='sum','Mean'='mean','Median'='median','Min'='min','Max'='max',
                 'Standard Deviation'='sd','Variance'='var')
InternalY <- '..y..'


GeomChoices <- c('Text'='text', 'Bar'='bar','Line'='line',
                 'Area'='area',  'Point'='point',
                 'Path'='path','Polygon'='polygon',
                 'Boxplot'='boxplot')
StatChoices <- c('Identity'='identity','Count'='bin','Summary'='summary','Boxplot'='boxplot')


getAesChoices <- function(geom, stat='identity'){
  switch(geom,
         'text'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                           'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                'Color'=c('Alpha'='aesAlpha'),
                                'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                                'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                     'Color'=c('Alpha'='aesAlpha'),
                                     'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                     'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     )
        ),

        'bar'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType','Weight'='aesWeight'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType','Weight'='aesWeight'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'line'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType',
                                           'Grouping'='aesGroup'),
                                'Color'=c('Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType',
                                                'Grouping'='aesGroup'),
                                     'Color'=c('Alpha'='aesAlpha')
                     )
        ),

        'area'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'point'=switch(stat,
                      'bin'=list('Coordinates'=c('X'='aesX'),
                                 'Common'=c('Color'='aesColor','Size'='aesSize',
                                            'Shape'='aesShape'),
                                 'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      ),
                      'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                      'Common'=c('Color'='aesColor','Size'='aesSize',
                                                 'Shape'='aesShape'),
                                      'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      )
        ),

        'boxplot'=switch(stat,
                         'boxplot'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                        'Common'=c('Color'='aesColor','Size'='aesSize',
                                                   'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                        'Color'=c('Border Color'='aesBorderColor',
                                                  'Alpha'='aesAlpha')
                         ),
                         'identity'=list('Coordinates'=c('X'='aesX','Y Middle'='aesMiddle',
                                                         'Y Lower'='aesLower','Y Upper'='aesUpper',
                                                         'Y Min'='aesYmin','Y Max'='aesYmax'),
                                         'Common'=c('Color'='aesColor','Size'='aesSize',
                                                    'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                         'Color'=c('Border Color'='aesBorderColor',
                                                   'Alpha'='aesAlpha')
                         )
        )

  )
}

AesChoicesSimpleList <- unique(unlist(lapply(GeomChoices, getAesChoices), use.names=FALSE))

fonttable <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE,
                        text='
Short,Canonical
mono,Courier
sans,Helvetica
serif,Times
,AvantGarde
,Bookman
,Helvetica-Narrow
,NewCenturySchoolbook
,Palatino
,URWGothic
,URWBookman
,NimbusMon
URWHelvetica,NimbusSan
,NimbusSanCond
,CenturySch
,URWPalladio
URWTimes,NimbusRom
')
FontFamilyChoices <- as.vector(t(as.matrix(fonttable)))
FontFamilyChoices <- FontFamilyChoices[FontFamilyChoices!='']

FontFaceChoices <- c("plain","bold","italic","bold.italic")


load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=subset(result.df, score.type=="Combined"), yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "Combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  df = NULL
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  ## if input dataframe is not null then update the target dataframe with the inputdf genes
  if (!(is.null(inputdf)))
  {
    temp <- as.data.frame(inputdf[,1])
    colnames(temp) <- c("gene")
    resultsSub <- plyr::join(temp,resultsSub,type="inner")          
  }
  ## sort the dataframe to match with results table
  if (cutoff > 0)
  {
    resultsSub <- resultsSub[order(-resultsSub$"score"),] 
  }else{
    resultsSub <- resultsSub[order(resultsSub$"score"),]     
  }
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(updateProgress = NULL,cancer,inputdf,sample)
{
  if (sample == 'tumors'){
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }else{
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }
  
}

##' view 2
comp1view2Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined") 
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
    }
  }
}
## for user file input
comp1view2FilePlot = function(updateProgress = NULL,cancer,inputdf,sample){

  if (sample == 'tumors'){    
    og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }else{
    og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsog <- plyr::join(temp,rgsog,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste("<a href=\"http://www.genecards.org/cgi-bin/carddisp.pl?gene=",rgs[,1],"\">","Gene Card","</a>",sep="")
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsts <- plyr::join(temp,rgsts,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")

        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsog <- plyr::join(temp,rgsog,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsts <- plyr::join(temp,rgsts,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(updateProgress= NULL,cancer,score,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs) 
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param margin The margin to sample (1 to sample rows, 2 to sample columns)
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42)
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, margin=1)
{
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      el <- subset(reshape2::melt(D$HP), value>0)
      try_again = TRUE
      while(try_again)
      {
        el[,margin] <- sample(el[,margin])
        try_again <- (length(unique(paste(el$Var1, el$Var2))) != Nlinks)
      }
      permuted_HP <- reshape2::acast(rbind(subset(reshape2::melt(D$HP), value==0),el), Var1~Var2, length)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}
#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 26, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/cogsci_2015/paper/pics/")
source("rscripts/helpers.r")

# get prior expectations, laplace smoothed
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations_laplace.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = priorexpectations$Item

# histogram of expectations
ggplot(priorexpectations, aes(x=expectation/15)) +
  geom_histogram() +
  scale_x_continuous(name="Expected value of prior distribution") +
  scale_y_continuous(name="Number of cases")
ggsave("priorexpectations-histogram-laplace.pdf")


# plot model predictions
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

toplot = droplevels(subset(some, SpeakerOptimality == 1))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform.pdf",width=5.5,height=4.5)
save(toplot, file="data/toplot-expectations.RData")

toplot_w = toplot
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted, shape=RSA)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform-regular.pdf",width=6.5,height=4.5)


######### CLEAN UP REST OF THIS ##########



#' get model predictions
load("data/mp-uniform.RData")
#d = read.table("data/parsed_uniform_results.tsv", quote="", sep="\t", header=T)
table(d$Item)
nrow(d)
head(d)
d[d$Item == "ate the seeds birds" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 1,]
d[d$Item == "stuck to the wall baseballs" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 2 & d$Wonky == "true",]
mp = ddply(d, .(Item, QUD, State, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
head(mp)
#mp[mp$Item == "ate the seeds birds" & mp$QUD=="how-many" & mp$Alternatives=="0_basic" & mp$SpeakerOptimality == 1,]
wr = ddply(d, .(Item, QUD, Wonky, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
wr[wr$Item == "ate the seeds birds" & wr$QUD=="how-many" & wr$Alternatives=="0_basic" & wr$SpeakerOptimality == 1,]



# get smoothed prior probabilities
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
head(priorprobs)
row.names(priorprobs) = paste(priorprobs$effect,priorprobs$object)
mpriorprobs = melt(priorprobs, id.vars=c("effect", "object"))
head(mpriorprobs)
row.names(mpriorprobs) = paste(mpriorprobs$effect,mpriorprobs$object,mpriorprobs$variable)
mp$PriorProbability = mpriorprobs[paste(as.character(mp$Item)," X",mp$State,sep=""),]$value
mp$AllPriorProbability = priorprobs[paste(as.character(mp$Item)),]$X15
head(mp)

# get empirical state posteriors:
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/3_sinking-marbles-nullutterance/results/data/r.RData")
head(r)
r$Item = as.factor(paste(r$effect,r$object))
# because posteriors come in 4 bins, make Bin variable for model prediction dataset:
mp$Proportion = as.factor(ifelse(mp$State == 0, "0", ifelse(mp$State == 15, "100", ifelse(mp$State < 8, "1-50", "51-99"))))

agr = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=mean)
#agr$CILow = aggregate(normresponse ~ Item + quantifier + Proportion,data=r, FUN=ci.low)$normresponse
#agr$CIHigh = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=ci.high)$normresponse
#agr$YMin = agr$normresponse - agr$CILow
#agr$YMax = agr$normresponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Proportion, agr$Quantifier)
mp$PosteriorProbability_empirical = agr[paste(mp$Item,mp$Proportion,mp$Quantifier),]$normresponse

#plot empirical against predicted distributions for "some"
some = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality, PriorExpectation, Proportion, WonkyWorldPrior, PosteriorProbability_empirical), summarise, PosteriorProbability_predicted=sum(PosteriorProbability), PriorProbability_smoothed=sum(PriorProbability))
some= subset(some, Quantifier == "some")
nrow(some)
head(some)
msome = melt(some, measure.vars=c("PosteriorProbability_empirical","PosteriorProbability_predicted","PriorProbability_smoothed"))
msome$ptype = as.factor(ifelse(msome$variable == "PosteriorProbability_empirical", "posterior (empirical)",ifelse(msome$variable == "PosteriorProbability_predicted","posterior (model)", "prior")))
head(msome)
nrow(msome)
summary(msome)

toplot = droplevels(subset(msome, QUD == "how-many" & SpeakerOptimality == 2 & Alternatives == "0_basic"))#"0_basic1_lownum2_extra4_twowords5_threewords"))
nrow(toplot)
toplot$Probability = as.factor(ifelse(toplot$ptype == "prior","prior","posterior"))
toplot$Prop = factor(toplot$Proportion, levels=c("1-50","51-99","100"))
ggplot(toplot, aes(x=Prop, y=value,color=ptype, group=ptype, size=Probability)) +
  geom_point() +
  geom_line() +
  scale_size_discrete(range=c(1,2)) +
  scale_color_manual(values=c("red","blue","black")) +
  facet_wrap(WonkyWorldPrior~Item)
ggsave("graphs/model-empirical-uniform-howmany-2-basic.pdf",width=35,height=30)

#plot empirical against predicted expectations for "some"
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")
summary(r)
r$Item = as.factor(paste(r$effect, r$object))
agr = aggregate(ProportionResponse ~ Item + quantifier, data=r, FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ Item + quantifier,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ Item + quantifier,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Quantifier)
mp$PosteriorExpectation_empirical = agr[paste(mp$Item,mp$Quantifier),]$ProportionResponse
mp$PriorExpectation_smoothed = mp$PriorExpectation/15

pexpectations = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality,PriorExpectation_smoothed, WonkyWorldPrior, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = droplevels(subset(pexpectations, Quantifier == "some"))

cors = ddply(some, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorExpectation_predicted, PosteriorExpectation_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)

ggplot(some, aes(x=PosteriorExpectation_predicted, y=PosteriorExpectation_empirical,color=as.factor(SpeakerOptimality), shape=as.factor(WonkyWorldPrior))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
#  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-expectations.pdf",width=30,height=10)

  
#plot empirical against predicted allstate-prbabilities for "some"
allstate = droplevels(subset(mp, State == 15 & Quantifier == "some"))
cors = ddply(allstate, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)
# .59 correlation despite being shitty model

ggplot(allstate, aes(x=PosteriorProbability, y=PosteriorProbability_empirical,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-allstateprobs.pdf",width=30,height=10)

#maybe COGSCI plot basis? plot  predicted allstate-prbabilities for "some" as a function of prior allstate-probabilities

ggplot(allstate, aes(x=PriorProbability, y=PosteriorProbability,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-uniform-allstateprobs.pdf",width=30,height=10)

# get empirical wonkiness posteriors
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/11_sinking-marbles-normal/results/data/r.RData")
head(r)
nrow(r)
r$Item = as.factor(paste(r$effect,r$object))

t = as.data.frame(prop.table(table(r$Item, r$quantifier, r$response), mar=c(1,2)))
head(t)
colnames(t) = c("Item","Quantifier","NormalMarbles","Proportion")
t[t$Var1=="ate the seeds birds",]
t$Quantifier = tolower(t$Quantifier)
tail(t)
t$Wonky = as.factor(ifelse(t$NormalMarbles == "yes","false","true"))
row.names(t) = paste(t$Item, t$Quantifier, t$Wonky)

wr$PosteriorProbability_empirical = t[paste(wr$Item, wr$Quantifier, wr$Wonky),]$Proportion
head(wr)
wonky = droplevels(subset(wr, Wonky == "true"))

head(wonky)
toplot = droplevels(subset(wonky, Alternatives == "0_basic" & WonkyWorldPrior == .4 & SpeakerOptimality == 2))

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability, color=Quantifier)) +
  geom_point() +
  geom_smooth() 
ggsave(file="graphs/wonkinessplot.pdf",width=6)

cors = ddply(wonky, .(Alternatives, QUD, SpeakerOptimality, Quantifier, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors,15)

wonky_all = subset(wonky, Quantifier == "all")
wonky_none = subset(wonky, Quantifier == "none")
wonky_some = subset(wonky, Quantifier == "some")

ggplot(wonky_all, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_all.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_none.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_some.pdf", width=30,height=10)



ggplot(wonky_all, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-all-wonkiness.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-none-wonkiness.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-some-wonkiness.pdf", width=30,height=10)

save(mp, file="data/mp-uniform.RData")
save(wr, file="data/wr-uniform.RData")

wonky[wonky$Quantifier == "all" & wonky$PriorExpectation < 4 & wonky$Alternatives == "0_basic" & wonky$QUD == "how-many" & wonky$SpeakerOptimality == 2,]

# get model predictions for all-state with basic alts, spopt==2, and qud==how-many
mp_some_allstate = subset(mp, Alternatives=="0_basic" & SpeakerOptimality == 2 & QUD == "how-many" & State == 15)
head(mp_some_allstate)
nrow(mp_some_allstate)



#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 26, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/cogsci_2015/paper/pics/")
source("rscripts/helpers.r")

# get prior expectations, laplace smoothed
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations_laplace.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = priorexpectations$Item

# histogram of expectations
ggplot(priorexpectations, aes(x=expectation/15)) +
  geom_histogram() +
  scale_x_continuous(name="Expected value of prior distribution") +
  scale_y_continuous(name="Number of cases")
ggsave("priorexpectations-histogram-laplace.pdf")


# plot model predictions
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

toplot = droplevels(subset(some, SpeakerOptimality == 1))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform.pdf",width=5.5,height=4.5)
save(toplot, file="data/toplot-expectations.RData")

toplot_w = toplot
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted, shape=RSA)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform-regular.pdf",width=6.5,height=4.5)


######### CLEAN UP REST OF THIS ##########



#' get model predictions
load("data/mp-uniform.RData")
#d = read.table("data/parsed_uniform_results.tsv", quote="", sep="\t", header=T)
table(d$Item)
nrow(d)
head(d)
d[d$Item == "ate the seeds birds" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 1,]
d[d$Item == "stuck to the wall baseballs" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 2 & d$Wonky == "true",]
mp = ddply(d, .(Item, QUD, State, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
head(mp)
#mp[mp$Item == "ate the seeds birds" & mp$QUD=="how-many" & mp$Alternatives=="0_basic" & mp$SpeakerOptimality == 1,]
wr = ddply(d, .(Item, QUD, Wonky, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
wr[wr$Item == "ate the seeds birds" & wr$QUD=="how-many" & wr$Alternatives=="0_basic" & wr$SpeakerOptimality == 1,]



# get smoothed prior probabilities
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
head(priorprobs)
row.names(priorprobs) = paste(priorprobs$effect,priorprobs$object)
mpriorprobs = melt(priorprobs, id.vars=c("effect", "object"))
head(mpriorprobs)
row.names(mpriorprobs) = paste(mpriorprobs$effect,mpriorprobs$object,mpriorprobs$variable)
mp$PriorProbability = mpriorprobs[paste(as.character(mp$Item)," X",mp$State,sep=""),]$value
mp$AllPriorProbability = priorprobs[paste(as.character(mp$Item)),]$X15
head(mp)

# get empirical state posteriors:
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/3_sinking-marbles-nullutterance/results/data/r.RData")
head(r)
r$Item = as.factor(paste(r$effect,r$object))
# because posteriors come in 4 bins, make Bin variable for model prediction dataset:
mp$Proportion = as.factor(ifelse(mp$State == 0, "0", ifelse(mp$State == 15, "100", ifelse(mp$State < 8, "1-50", "51-99"))))

agr = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=mean)
#agr$CILow = aggregate(normresponse ~ Item + quantifier + Proportion,data=r, FUN=ci.low)$normresponse
#agr$CIHigh = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=ci.high)$normresponse
#agr$YMin = agr$normresponse - agr$CILow
#agr$YMax = agr$normresponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Proportion, agr$Quantifier)
mp$PosteriorProbability_empirical = agr[paste(mp$Item,mp$Proportion,mp$Quantifier),]$normresponse

#plot empirical against predicted distributions for "some"
some = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality, PriorExpectation, Proportion, WonkyWorldPrior, PosteriorProbability_empirical), summarise, PosteriorProbability_predicted=sum(PosteriorProbability), PriorProbability_smoothed=sum(PriorProbability))
some= subset(some, Quantifier == "some")
nrow(some)
head(some)
msome = melt(some, measure.vars=c("PosteriorProbability_empirical","PosteriorProbability_predicted","PriorProbability_smoothed"))
msome$ptype = as.factor(ifelse(msome$variable == "PosteriorProbability_empirical", "posterior (empirical)",ifelse(msome$variable == "PosteriorProbability_predicted","posterior (model)", "prior")))
head(msome)
nrow(msome)
summary(msome)

toplot = droplevels(subset(msome, QUD == "how-many" & SpeakerOptimality == 2 & Alternatives == "0_basic"))#"0_basic1_lownum2_extra4_twowords5_threewords"))
nrow(toplot)
toplot$Probability = as.factor(ifelse(toplot$ptype == "prior","prior","posterior"))
toplot$Prop = factor(toplot$Proportion, levels=c("1-50","51-99","100"))
ggplot(toplot, aes(x=Prop, y=value,color=ptype, group=ptype, size=Probability)) +
  geom_point() +
  geom_line() +
  scale_size_discrete(range=c(1,2)) +
  scale_color_manual(values=c("red","blue","black")) +
  facet_wrap(WonkyWorldPrior~Item)
ggsave("graphs/model-empirical-uniform-howmany-2-basic.pdf",width=35,height=30)

#plot empirical against predicted expectations for "some"
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")
summary(r)
r$Item = as.factor(paste(r$effect, r$object))
agr = aggregate(ProportionResponse ~ Item + quantifier, data=r, FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ Item + quantifier,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ Item + quantifier,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Quantifier)
mp$PosteriorExpectation_empirical = agr[paste(mp$Item,mp$Quantifier),]$ProportionResponse
mp$PriorExpectation_smoothed = mp$PriorExpectation/15

pexpectations = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality,PriorExpectation_smoothed, WonkyWorldPrior, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = droplevels(subset(pexpectations, Quantifier == "some"))

cors = ddply(some, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorExpectation_predicted, PosteriorExpectation_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)

ggplot(some, aes(x=PosteriorExpectation_predicted, y=PosteriorExpectation_empirical,color=as.factor(SpeakerOptimality), shape=as.factor(WonkyWorldPrior))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
#  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-expectations.pdf",width=30,height=10)

  
#plot empirical against predicted allstate-prbabilities for "some"
allstate = droplevels(subset(mp, State == 15 & Quantifier == "some"))
cors = ddply(allstate, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)
# .59 correlation despite being shitty model

ggplot(allstate, aes(x=PosteriorProbability, y=PosteriorProbability_empirical,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-allstateprobs.pdf",width=30,height=10)

#maybe COGSCI plot basis? plot  predicted allstate-prbabilities for "some" as a function of prior allstate-probabilities

ggplot(allstate, aes(x=PriorProbability, y=PosteriorProbability,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-uniform-allstateprobs.pdf",width=30,height=10)

# get empirical wonkiness posteriors
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/11_sinking-marbles-normal/results/data/r.RData")
head(r)
nrow(r)
r$Item = as.factor(paste(r$effect,r$object))

t = as.data.frame(prop.table(table(r$Item, r$quantifier, r$response), mar=c(1,2)))
head(t)
colnames(t) = c("Item","Quantifier","NormalMarbles","Proportion")
t[t$Var1=="ate the seeds birds",]
t$Quantifier = tolower(t$Quantifier)
tail(t)
t$Wonky = as.factor(ifelse(t$NormalMarbles == "yes","false","true"))
row.names(t) = paste(t$Item, t$Quantifier, t$Wonky)

wr$PosteriorProbability_empirical = t[paste(wr$Item, wr$Quantifier, wr$Wonky),]$Proportion
head(wr)
wonky = droplevels(subset(wr, Wonky == "true"))

head(wonky)
toplot = droplevels(subset(wonky, Alternatives == "0_basic" & WonkyWorldPrior == .4 & SpeakerOptimality == 2))

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability, color=Quantifier)) +
  geom_point() +
  geom_smooth() 
ggsave(file="graphs/wonkinessplot.pdf",width=6)

cors = ddply(wonky, .(Alternatives, QUD, SpeakerOptimality, Quantifier, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors,15)

wonky_all = subset(wonky, Quantifier == "all")
wonky_none = subset(wonky, Quantifier == "none")
wonky_some = subset(wonky, Quantifier == "some")

ggplot(wonky_all, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_all.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_none.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_some.pdf", width=30,height=10)



ggplot(wonky_all, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-all-wonkiness.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-none-wonkiness.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-some-wonkiness.pdf", width=30,height=10)

save(mp, file="data/mp-uniform.RData")
save(wr, file="data/wr-uniform.RData")

wonky[wonky$Quantifier == "all" & wonky$PriorExpectation < 4 & wonky$Alternatives == "0_basic" & wonky$QUD == "how-many" & wonky$SpeakerOptimality == 2,]

# get model predictions for all-state with basic alts, spopt==2, and qud==how-many
mp_some_allstate = subset(mp, Alternatives=="0_basic" & SpeakerOptimality == 2 & QUD == "how-many" & State == 15)
head(mp_some_allstate)
nrow(mp_some_allstate)



# server.R
library(shiny)
library(rworldmap)
library(countrycode)

# We put here all load for performance reasons.
#Nevertheless the load blocks the app a few seconds
moocs <- read.csv("./data/HMXPC13_DI_v2_5-14-14.csv" ,header=TRUE, sep=",");

data <- moocs[moocs$registered == "1",]

# Adding courses list.
course_id <- unique(data$course_id)

shinyServer(function(input, output) {

  output$leftEd <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  output$leftAge <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  output$leftGender <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  output$leftCountry <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  # Visualization by Level of Education
  output$LoEPlot <- renderPlot({
    if(input$radioEd == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectEd,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
    
    # Variable for range of studies
    studies <- data$LoE_DI
    
    colors = c("red", "yellow", "green", "violet","orange", "blue")
    barplot(table(studies),main="Nº de certificados atendiendo al nivel de estudios", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("Missing","Bachelor's","Doctorate","< Secondary", "Master's", "Secondary"))
  })
  
  # Visualization by age
  output$AgePlot <- renderPlot({
    if(input$radioAge == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectAge,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
    
    # Years of students (we traduce year of birth to age)
    years <- 2014 - data$YoB
    # By Age
    categories <- c(10,18,25,30,35,45,55,65,80,90)
    agecat <- cut(years, categories)
    
    colors = c("red", "yellow", "green", "violet","orange", "blue","cyan","grey","pink")
    barplot(table(agecat),main="Nº de certificados atendiendo a la edad", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("10-18","18-25","25-30","30-35", "35-45", "45-55","55-65","65-80","80-90"))
  })
  
  # Visualization by genre
  output$GenderPlot <- renderPlot({
    if(input$radioGender == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectGender,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
    
    #By gender
    gender <- table(data$gender)
    genderpercent <- gender/sum(gender)*100
    labels <- c("Missing","Female","Male","Other")
    genderpercent <- round(genderpercent, digits=0)
    labels <- paste(labels, genderpercent)
    labels <- paste(labels,"%",sep="") # ad % to labels
    
    pie(table(data$gender), labels = labels, 
        main="Nº de certificados atendiendo al género", 
        col=rainbow(length(labels)) # We set some colors
        )
  })
  
  # Visualization by country
  output$CountryPlot <- renderPlot({
    if(input$radioCountry == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectCountry,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
  
    #By Country
    dataf <- table(data$final_cc_cname_DI)
    Countries <- as.data.frame(dataf)
    Countries[1] <- countrycode(Countries$Var1,"country.name", "iso3c")
    sPDF <- joinCountryData2Map(Countries, joinCode = "NAME", nameJoinColumn = "Var1")
    
    par(mai=c(0,0,0.3,0),xaxs="i",yaxs="i")
    
    # creating a user defined palette
    op <- palette(c('green','yellow','orange','red'))
    
    # find quartile breaks
    cutVector <- quantile(sPDF@data[["Freq"]], na.rm=TRUE)
    
    # classify the data to a factor
    sPDF@data[["FreqCategories"]] <- cut(sPDF@data[["Freq"]], cutVector, include.lowest=TRUE)
    
    # rename the categories
    levels(sPDF@data[["FreqCategories"]]) <- c('low', 'medium', 'high', 'very_high')
    
    #mapping
    mapCountryData(sPDF, nameColumnToPlot="FreqCategories",
                                mapTitle="Nº de alumnos certificados atendiendo al País",
                                colourPalette="palette", addLegend=TRUE,
                                oceanCol='lightblue',
                                missingCountryCol='white'
                                )
  })
  
  

})#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list();
IMMA.parameters  <- list();
IMMA.definitions <- list();

# Core section
IMMA.attachments[[100]] <- 'core';

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH');

# For each parameter, provide an array specifying:
#    Its length in bytes, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)

# Find out which attachment a parameter is in
IMMA.whichAttachment <- function(parameter) {
    for(i in c(100)) {# ,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

# Check the value for a parameter is inside its acceptable range(s)
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[6] == 3 ) {
        return(result); 
    }
  
    w<-which(((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] )) |
             ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= this[[parameter]] )))
    if(length(w<length(ob[[parameter]]) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        if ( this[parameters[i]]!=null 
            && this.checkParameter( parameters[i], definitions ) )
        {
            var Tmp = this[parameters[i]];

            // Scale to integer units for output
            if ( definitions[parameters[i]][5] != null ) {
                Tmp /= definitions[parameters[i]][5];
                Tmp = parseInt(Tmp);
            }

            // Encode as base36 if required
            if ( definitions[parameters[i]][5] == 2 ) {
                Tmp = IMMA.encode_base36(Tmp);
            }

            // Convert to a string of the correct length
            if ( definitions[parameters[i]][6] == 1 ) {

                // Integer
                if ( definitions[parameters[i]][0] != null ) {
                    Tmp=Tmp.toString();
                    while(Tmp.length<definitions[parameters[i]][0]) {
                        Tmp=" "+Tmp;
                    }
                }
                else {

                    // Undefined length - should never happen
                    Tmp=Tmp.toString();
                }
            }
            else {

                // String
                if ( definitions[parameters[i]][0] != null ) {
                    Tmp=Tmp.toString();
                    while(Tmp.length<definitions[parameters[i]][0]) {
                        Tmp=Tmp+" ";
                    }
                }
                else {
                
                   // Undefined length - only for supplementary data
                   Tmp=Tmp.toString(); 
                }
            }
            Result += Tmp;

        }
        else {
            // Undefined data - make a blank string of the corect length
            if ( definitions[parameters[i]][0] != null ) {
                for(var j=0;j<definitions[parameters[i]][0];j++) {
                    Result += " ";
                }
            }
            else {

                // Undefined data with unknown length - treat as blank string
                Result += " ";
            }
        }
    }
    
    // Done all the parameters, add the ID and length to the start
    // (except for core)
    if ( attachment != 0 ) {
        if ( attachment == 99 ) {
            Result = " 0"+Result;
        }
        else {
            var Tmp = (Result.length+4).toString();
            if(Tmp.length<2) { Tmp = " "+Tmp; }
            Result = Tmp+Result;
        }
        Tmp = attachment.toString();
        if(Tmp.length<2) { Tmp= " "+Tmp; }
        Result = Tmp+Result;
    }

    return Result;
}




#' Read in all the IMMA records from a connection
#'
#' Currently only reads the core element - discards attachments
#'
#' I'm not sure how to read variable-format records in an efficient fashion
#'  so at the moment this only looks at the fixed-format component.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(updateProgress = NULL,cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(updateProgress = NULL,cancer,inputdf,sample)
{
  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{
    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
  
}

##' view 2
comp1view2Plot = function(updateProgress = NULL,cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"Combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }
}
## for user file input
comp1view2FilePlot = function(updateProgress = NULL,cancer,inputdf,sample){

  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{

      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(updateProgress = NULL,cutoff,cancer,score,sample){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")

        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(updateProgress= NULL,cancer,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
#!/usr/bin/env Rscript

# Parse the --file= argument out of command line args and
# determine where base directory is so that we can source
# our common sub-routines
arg0 <- sub("--file=(.*)", "\\1", grep("--file=", commandArgs(), value = TRUE))
dir0 <- dirname(arg0)
source(file.path(dir0, "common.r"))

theme_set(theme_grey(base_size = 17))

# Setup parameters for the script
params = matrix(c(
  'help',    'h', 0, "logical",
  'width',   'x', 2, "integer",
  'height',  'y', 2, "integer",
  'outfile', 'o', 2, "character",
  'indir',   'i', 2, "character",
  'tstart',  '1',  2, "integer",
  'tend',    '2',  2, "integer",
  'ylabel1stgraph', 'Y',  2, "character"
  ), ncol=4, byrow=TRUE)

# Parse the parameters
opt = getopt(params)

if (!is.null(opt$help))
  {
    cat(paste(getopt(params, command = basename(arg0), usage = TRUE)))
    q(status=1)
  }

# Initialize defaults for opt
if (is.null(opt$width))   { opt$width   = 1280 }
if (is.null(opt$height))  { opt$height  = 1500 }
if (is.null(opt$indir))   { opt$indir  = "current"}
if (is.null(opt$outfile)) { opt$outfile = file.path(opt$indir, "summary.png") }
if (is.null(opt$ylabel1stgraph)) { opt$ylabel1stgraph = "Op/sec" }

# Load the benchmark data, passing the time-index range we're interested in
b = load_benchmark(opt$indir, opt$tstart, opt$tend)

# If there is no actual data available, bail
if (nrow(b$latencies) == 0)
{
  stop("No latency information available to analyze in ", opt$indir)
}

png(file = opt$outfile, width = opt$width, height = opt$height)

# First plot req/sec from summary
plot_throughput <- qplot(elapsed, successful / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = "Throughput") +

                geom_smooth(aes(y = successful / window, colour = "ok"), size=0.5) +
                geom_point(aes(y = successful / window, colour = "ok"), size=2.0) +

                scale_colour_manual("Response", values = c("#188125"))

plot_error <- qplot(elapsed, failed / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = "Errors") +

                geom_smooth(aes(y = failed / window, colour = "error"), size=0.5) +
                geom_point(aes(y = failed / window, colour = "error"), size=2.0) +

                scale_colour_manual("Response", values = c("#FF665F"))

plot_sessions_running <- qplot(elapsed, running, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = "# sessions",
                 main = "Sessions Running") +

                 geom_point(aes(y = running, colour = "running"), size=2.0) +
                 geom_line( aes(y = running, colour = "running"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#000000"))

plot_sessions_started <- qplot(elapsed, starts / window, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                 main = "Sessions Started") +

                 geom_point(aes(y = starts / window, colour = "starts"), size=2.0) +
                 geom_line( aes(y = starts / window, colour = "starts"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#188125"))

# Setup common elements of the latency plots
latency_plot <- ggplot(b$latencies, aes(x = elapsed)) +
                   facet_grid(. ~ op) +
                   labs(x = "Elapsed Secs", y = "Latency (ms)")

# Plot median, mean and 95th percentiles
plot_median_mean <- latency_plot + labs(title = "Mean and Median Latency") +
            geom_smooth(aes(y = mean, color = "mean"), size=0.5) +
            geom_point(aes(y = mean, color = "mean"), size=2.0) +

            geom_smooth(aes(y = median, color = "median"), size=0.5) +
            geom_point(aes(y = median, color = "median"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FFA700", "#188125"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot median, mean and 95th percentiles
plot_95 <- latency_plot + labs(title = "95th Percentile Latency") +
            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot 99th percentile
plot_99 <- latency_plot + labs(title = "99th Percentile Latency") +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X99_9th","X99th" ),
            #                 labels = c("99.9th", "99th"))

# Plot 99.9th percentile
plot_999 <- latency_plot + labs(title = "99.9th Percentile Latency") +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

# Plot 100th percentile
plot_max <- latency_plot + labs(title = "Maximum Latency") +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

plot_upper_percentiles <- latency_plot + labs(title = "95th, 99th, 99.9th and 100th Percentile") +
            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FFFE00", "#FFA900", "#FF5600", "#FF0000"))

grid.newpage()

pushViewport(viewport(layout = grid.layout(6, 1)))

vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

print(plot_throughput, vp = vplayout(1,1))
print(plot_error, vp = vplayout(2,1))
print(plot_sessions_running, vp = vplayout(3,1))
print(plot_sessions_started, vp = vplayout(4,1))
print(plot_median_mean, vp = vplayout(5,1))
print(plot_upper_percentiles, vp = vplayout(6,1))

dev.off()
REBOL [
	Title:   "Red/System linker"
	Author:  "Nenad Rakocevic"
	File: 	 %linker.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

linker: context [
	version: 		1.0.0							;-- emitted linker version
	cpu-class: 		'IA-32							;-- default target
	file-emitter:	none							;-- file emitter object
	verbose: 		0								;-- logs verbosity level
	
	line-record!: make-struct [
		ptr		[integer!]							;-- code pointer
		line	[integer!]							;-- line number
		file	[integer!]							;-- filename string offset
	] none
	
	job-class: context [
		format: 									;-- 'PE | 'ELF | 'Mach-o
		type: 										;-- 'exe | 'obj | 'lib | 'dll | 'drv
		target:										;-- CPU identifier
		sections:									;-- code/data sections
		flags:										;-- global flags
		sub-system:									;-- target environment (GUI | console)
		symbols:									;-- symbols table
		output:										;-- output file name (without extension)
		debug-info:									;-- debugging informations
		base-address:								;-- base address
		buffer: none								;-- output buffer
	]
	
	throw-error: func [err [word! string! block!]][
		print [
			"*** Linker Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
		]
		system-dialect/compiler/quit-on-error
	]
	
	resolve-symbol-refs: func [
		job 	 [object!] 
		cbuf 	 [binary!]							;-- code buffer
		dbuf 	 [binary!]							;-- data buffer
		code-ptr [integer!]							;-- code memory address
		data-ptr [integer!]							;-- data memory address
		pointer	 [object!]
		/local 
			data-offset
	][
		data-offset: either job/PIC? [data-ptr - code-ptr][data-ptr]
		
		foreach [name spec] job/symbols [
			unless empty? spec/3 [
				all [
					any [
						all [
							spec/1 = 'global		;-- code to data references
							pointer/value: data-offset + spec/2
						]
						all [
							spec/1 = 'native-ref	;-- code to code references
							pointer/value: either job/PIC? [spec/2][code-ptr + spec/2]
						]
					]
					foreach ref spec/3 [
						if integer? ref [change at cbuf ref form-struct pointer]
					]
				]
			]
			if all [	
				spec/1 = 'global
				block? spec/4
			][										;-- data to data references
				pointer/value: data-ptr + spec/2			
				foreach ref spec/4 [change at dbuf ref form-struct pointer]
			]
		]
	]
	
	get-debug-lines-size: func [job [object!] /local size][
		size: 12 * (length? job/debug-info/lines/records) / 3
		foreach file job/debug-info/lines/files [
			size: size + 1 + length? file			;-- file is supposed to be FORMed not MOLDed
		]
		size
	]
	
	build-debug-lines: func [
		job [object!]
		code-ptr [integer!]							;-- code memory address
		pointer [object!]
		/local	records files rec-size buffer table strings record data-buf spec
	][
		records: job/debug-info/lines/records
		files: job/debug-info/lines/files
		
		rec-size: 12 * (length? records) / 3 		;-- 12 = pointer! + integer! + integer!
											 		;--  3 = nb of elements in records (flat structure)
		buffer:  make binary! rec-size		 		;-- main buffer
		table:   make block! length? files	 		;-- intermediary file strings offsets table
		strings: make binary! 32 * length? files	;-- file strings buffer
		
		foreach file files [
			append table length? strings			;-- save file string offsets
			append strings form file
			append strings null
		]
		
		record: make-struct line-record! none
		forskip records 3 [
			record/ptr:  code-ptr + records/1 - 1
			record/line: records/2
			record/file: rec-size + pick table records/3	;-- store file offsets
			append buffer form-struct record
		]
		
		data-buf: job/sections/data/2		
		spec: find job/symbols '__debug-lines
		spec/<data>/2: length? data-buf				;-- patch __debug-lines symbol to point to 1st record
		
		repend data-buf [buffer strings]			;-- append records and strings to data segment
	]
		
	clean-imports: func [imports [block!]][			;-- remove unused imports
		foreach [lib list] imports/3 [
			remove-each [name refs] list [empty? refs]
		]
	]

	make-filename: func [job [object!] /local base provided suffix][
		provided: suffix? base: job/build-basename
		suffix: any [
			job/build-suffix
			select file-emitter/defs/extensions job/type
		]
		if any [none? suffix suffix <> provided][
			base: join base suffix
		]
		join any [job/build-prefix %""] base
	]
	
	build: func [job [object!] /local file fun][
		unless job/target [job/target: cpu-class]
		job/buffer: make binary! 512 * 1024
	
		clean-imports job/sections/import
	
		file-emitter: either encap? [
			do-cache rejoin [%system/formats/ job/format %.r]
		][
			do rejoin [%formats/ job/format %.r]
		]
		file-emitter/build job

		file: make-filename job
		if verbose >= 1 [print ["output file:" file]]
		
		if error? try [write/binary/direct file job/buffer][
			throw-error ["locked or unreachable file:" file]
		]
		
		if fun: in file-emitter 'on-file-written [
			do reduce [get fun job file]
		]
		
		if find get-modes file 'file-modes 'owner-execute [
			set-modes file [owner-execute: true]
		]
		file
	]

]
# server.R
library(shiny)
# We put here all load for performance reasons.
#Nevertheless the load blocks the app a few seconds

shinyServer(function(input, output) {

  output$leftEd <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos."
  })
  
  output$leftAge <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos."
  })
  
  output$leftGender <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos."
  })
  
  # Visualization by Level of Education
  output$LoEPlot <- renderPlot({
    colors = c("red", "yellow", "green", "violet","orange", "blue")
    barplot(table(studies),main="Nº de certificados atendiendo al nivel de estudios", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("Missing","Bachelor's","Doctorate","< Secondary", "Master's", "Secondary"))
  })
  
  # Visualization by age
  output$AgePlot <- renderPlot({
    colors = c("red", "yellow", "green", "violet","orange", "blue","cyan","grey","pink")
    barplot(table(agecat),main="Nº de certificados atendiendo a la edad", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("10-18","18-25","25-30","30-35", "35-45", "45-55","55-65","65-80","80-90"))
  })
  
  # Visualization by genre
  output$GenderPlot <- renderPlot({
    pie(table(data$gender), labels = labels, 
        main="Nº de certificados atendiendo al género", 
        col=rainbow(length(labels)) # We set some colors
        )
  })
  
  # Visualization by country
  # http://www.londonr.org/Presentations/Andy%20South%20-%20Beautiful%20world%20maps%20in%20R.pdf
  output$CountryPlot <- renderPlot({
    pie(table(data$gender), labels = labels, 
        main="Nº de certificados atendiendo al género", 
        col=rainbow(length(labels)) # We set some colors
    )
  })
  
  

})REBOL [
    Title:   "Red run time error test script"
	Author:  "Peter W A Wood"
	File: 	 %run-time-error-test.r
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/origin/BSD-3-License.txt"
]

~~~start-file~~~ "Red run time errors"

	--test-- "rte-1"
		--compile-and-run-this/error {Red[] i: 1 j: 0 k: i / j}
    	--assert-red-printed? "*** Math error: attempt to divide by zero"
    	
    --test-- "rte-2"
    	--compile-and-run-this/error {Red[] absolute -2147483648}
    	--assert-red-printed? "*** Math error: math or number overflow"
    	
     --test-- "rte-3"
    	--compile-and-run-this/error {Red[] #"^^(01)" + #"^^(10FFFF)"}
    	--assert-red-printed? "*** Math Error: math or number overflow"
    	
    --test-- "rte-4"
    	--compile-and-run-this/error {Red[] do [#"^^(01)" + #"^^(10FFFF)"]}
    	--assert-red-printed? "*** Math Error: math or number overflow"
    	
    --test-- "rte-5"
    	--compile-and-run-this/error {Red[] #"^^(00)" - #"^^(01)"}
    	--assert-red-printed? "*** Math Error: math or number overflow"
    	
    --test-- "rte-6"
    	--compile-and-run-this/error {Red[] do [#"^^(00)" - #"^^(01)"]}
    	--assert-red-printed? "*** Math Error: math or number overflow"
    	
    --test-- "rte-7"
    	--compile-and-run-this/error {Red[] #"^^(010FFF)" * #"^^(11)"}
    	--assert-red-printed? "*** Math Error: math or number overflow"
    	
    --test-- "rte-8"
    	--compile-and-run-this/error {Red[] do [#"^^(010FFF)" * #"^^(11)" ]}
    	--assert-red-printed? "*** Math Error: math or number overflow"
  
~~~end-file~~~ 
REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		forever foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct try
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall forever]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| #get pos: (process-get-directive pos/1 pos)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit [[stack/adjust]]
			][
				mark: tail output
				unless head? path [
					emit [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-change*
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-change*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-change* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-try: does [
		unless block? pc/1 [
			pc: back pc
			comp-word									;-- fallback to interpreter
			exit
		]
		emit [catch RED_ERROR]
		insert-lf -2
		body: comp-sub-block 'try
		if body/1 = 'stack/reset [remove body]
		mark: tail output
		emit-open-frame 'try
		insert body mark
		clear mark
		append body [
			stack/unwind
		]
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
	
	comp-forever: does [
		pc: back pc
		change/part pc [while [true]] 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native words/_body
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec select objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			redirect-to literals [
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			]
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame op
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-get-directive: func [
		path code [block!] /local obj ctx blk
	][
		unless path? path [
			throw-error ["invalid #get argument:" spec]
		]
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 2
		blk: [red/word/get-in (decorate-exec-ctx ctx) (get-word-index/with last path ctx)]
		insert code compose blk
	]
	
	process-in-directive: func [
		path word code [block!] /local obj ctx blk
	][
		if any [not path? path not any-word? :word][
			throw-error ["invalid #in argument:" mold path mold :word]
		]
		append path word
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 3
		blk: [red/object/get-word (decorate-exec-ctx ctx) (get-word-index/with word ctx)]
		insert code compose blk
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc form load-cache %version.r
				comp-expression
				true
			]
			#build-date [
				change pc mold now
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
batch-mode: all [system/options/args find system/options/args "--batch"]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

;; set the default script header
qt/script-header: "Red []"

;; make auto files if needed
do %source/units/make-red-auto-tests.r
do %source/units/make-interpreter-auto-tests.r 

;; run the tests
print rejoin ["Quick-Test v" qt/version]
print rejoin ["REBOL " system/version]

start-time: now/precise

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

===start-group=== "Red compiler unit tests"
	--run-unit-test-quiet %source/compiler/lexer-test.r
===end-group===

===start-group=== "Red/System runtime tests"
  	--run-test-file-quiet %source/runtime/tools-test.reds
  	--run-test-file-quiet %source/runtime/unicode-test.red
===end-group===

===start-group=== "Red Compiler tests"
  	--run-script-quiet %source/compiler/print-test.r
  	--run-script-quiet %source/compiler/regression-tests.r
  	--run-script-quiet %source/compiler/run-time-error-test.r
  	--run-script-quiet %source/compiler/compile-error-test.r
===end-group===

===start-group=== "Red Units tests"
    --run-test-file-quiet %source/units/object-test.red
  	--run-test-file-quiet %source/units/logic-test.red
  	--run-test-file-quiet %source/units/conditional-test.red
  	--run-test-file-quiet %source/units/series-test.red
  	--run-test-file-quiet %source/units/path-test.red
  	--run-test-file-quiet %source/units/serialization-test.red
  	--run-test-file-quiet %source/units/function-test.red
  	--run-test-file-quiet %source/units/loop-test.red
  	--run-test-file-quiet %source/units/type-test.red
  	--run-test-file-quiet %source/units/find-test.red
  	--run-test-file-quiet %source/units/select-test.red
  	--run-test-file-quiet %source/units/binding-test.red
  	--run-test-file-quiet %source/units/evaluation-test.red
  	--run-test-file-quiet %source/units/load-test.red
  	--run-test-file-quiet %source/units/switch-test.red
  	--run-test-file-quiet %source/units/case-test.red
  	--run-test-file-quiet %source/units/routine-test.red
  	--run-test-file-quiet %source/units/append-test.red
  	--run-test-file-quiet %source/units/insert-test.red
  	--run-test-file-quiet %source/units/make-test.red
  	--run-test-file-quiet %source/units/system-test.red
  	--run-test-file-quiet %source/units/parse-test.red
  	--run-test-file-quiet %source/units/bitset-test.red
  	--run-test-file-quiet %source/units/same-test.red
  	--run-test-file-quiet %source/units/strict-equal-test.red
  	--run-test-file-quiet %source/units/integer-test.red
  	--run-test-file-quiet %source/units/char-test.red
  	--run-test-file-quiet %source/units/float-test.red
===end-group===

===start-group=== "Red Library tests"
	
===end-group===

===start-group=== "Auto-tests"
  	--run-test-file-quiet %source/units/auto-tests/integer-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-not-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/not-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-greater-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/greater-equal-auto-test.red
===end-group===

===start-group=== "Interpreter Auto-tests"
  	--run-test-file-quiet %source/units/auto-tests/interp-binding-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-case-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-conditional-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-evaluation-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-find-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-function-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-load-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-logic-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-loop-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-select-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-serialization-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-series-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-type-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-switch-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-append-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-insert-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-system-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-parse-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-bitset-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-integer-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-float-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-char-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-object-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-same-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-strict-equal-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-not-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-integer-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-float-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-not-equal-auto-test.red
  	
===end-group===

***end-run-quiet***

--delete-temp-files

end-time: now/precise
print ["       in" difference end-time start-time newline]
system/options/quiet: store-quiet-mode
either batch-mode [
	quit/return either qt/test-run/failures > 0 [1] [0]
][
	print ["The test output was logged to" qt/log-file]
	ask "hit enter to finish"
	print ""
	qt/test-run/failures
]
#!/usr/bin/env Rscript

# Josep Ll. Berral-García
# ALOJA-BSC-MSR hadoop.bsc.es
# 2014-12-11
# Launcher of ALOJA-ML
 
# usage: ./aloja_cli.r -m method [-d dataset] [-l learned model] [-p param1=aaaa:param2=bbbb:param3=cccc:...] [-a] [-n dims] [-v]
#	 ./aloja_cli.r --method method [--dataset dataset] [--learned learned model] [--params param1=aaaa:param2=bbbb:param3=cccc:...] [--allvars] [--numvars dims] [--verbose]
#
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1-small:vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size"
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p1 -d m5p1-tt.csv -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":sorted=asc -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":sorted=asc -v
#	 ./aloja_cli.r -m aloja_outlier_dataset -d m5p1-tt.csv -l m5p1 -p sigma=3:hdistance=3:saveall=m5p1test
#
#	 ./aloja_cli.r -m aloja_pca -d aloja-dataset.csv -p saveall=pca1
#	 ./aloja_cli.r -m aloja_regtree -d pca1-transformed.csv -p prange=1e-4,1e+4:saveall=m5p-simple-redim -n 20
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p-simple-redim -p inst_predict="1922.904354752,70.1570440421649,2.9694955079494,-3.64259027685954,-0.748746678239734,0.161321484374316,0.617610510007444,-0.459044093400257,0.251211132013151,0.251937462205716,-0.142007748147355,-0.0324862729758309,0.406308900544488,0.13593705166432,0.397452596451088,-0.731635384355167,-0.318297127484775,-0.0876192175148721,-0.0504762335523307,-0.0146283091875174" -v
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p-simple-redim -d m5p-simple-redim-tt.csv -v
#	 ./aloja_cli.r -m aloja_transform_data -d newdataset.csv -p pca_name=pca1:saveall=newdataset
#	 ./aloja_cli.r -m aloja_transform_instance -p pca_name=pca1:inst_transform="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1
#	 ./aloja_cli.r -m aloja_dataset_collapse_expand -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1:inst_general="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L"
#	 ./aloja_cli.r -m aloja_best_configurations -p bvec_name=dsc1 -v

library(devtools);
source_url("https://raw.githubusercontent.com/Aloja/aloja-ml/master/functions.r");

###############################################################################
# Read arguments from CLI

	suppressPackageStartupMessages(require(optparse));

	option_list = list(
		make_option(c("-m", "--method"), action="store", default=NULL, type='character', help="Method to be executed"),
		make_option(c("-p", "--params"), action="store", default=NULL, type='character', help="Generic list of parameters, separated by two points and no spaces"),
		make_option(c("-v", "--verbose"), action="store_true", default=FALSE, help="Outputs the result of the method"),
		make_option(c("-d", "--dataset"), action="store", default=NULL, type='character', help="For training methods: Dataset source of data"),
		make_option(c("-a", "--allvars"), action="store_true", default=FALSE, help="All vars are input but first one (for reduced dimensions)"),
		make_option(c("-n", "--numvars"), action="store", default=NULL, type='integer', help="All n vars after first one are input (for reduced dimensions)"),
		make_option(c("-l", "--learned"), action="store", default=NULL, type='character', help="For prediction methods: Learned model for prediction")
	);

	opt = parse_args(OptionParser(option_list=option_list));

###############################################################################
# Error and Warning messages on arguments

	if (is.null(opt$method))
	{
		cat("[ERROR] No method selected. Aborting mission.\n");
		quit(save="no", status=-1);
	}

###############################################################################
# Read datasets

	dataset <- NULL;

	if (!is.null(opt$dataset))
	{
		# Call for aloja_get_data
		params_1 <- list();
		params_1[["fread"]] = opt$dataset;

		dataset <- do.call(aloja_get_data,params_1);
	}

###############################################################################
# Parse parameters

	params <- list();
	params[["ds"]] <- dataset;

	if (opt$method %in% c("aloja_regtree","aloja_nneighbors","aloja_linreg","aloja_nnet","aloja_pca","aloja_dataset_collapse","aloja_dataset_collapse_expand","aloja_outlier_dataset"))
	{
		if (is.null(opt$vout)) params[["vout"]] <- "Exe.Time";

		if (is.null(opt$vin))
		{
			if (opt$allvars)
			{
				params[["vin"]] = colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))];
			} else if (!is.null(opt$numvars)) {
				params[["vin"]] = (colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))])[1:opt$numvars];
			} else {
				params[["vin"]] = c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster");
			}
		}
	}
	if (opt$method  == "aloja_print_individual_summaries" || opt$method  == "aloja_print_summaries")
	{
		params[["vin"]] = c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Exe.Time"); 
	}

	if (opt$method  == "aloja_predict_instance" || opt$method  == "aloja_predict_dataset" || opt$method == "aloja_outlier_dataset")
	{
		params_2 <- list();
		params_2[["tagname"]] <- opt$learned;
		params[["learned_model"]] <- do.call(aloja_load_object,params_2);
	}

	if (opt$method == "aloja_dataset_clustering")
	{
		params_3 <- list();
		params_3[["tagname"]] <- opt$learned;
		params[["na.predict"]] <- do.call(aloja_load_object,params_3);
	}

	if (!is.null(opt$params))
	{
		saux_1 <- strsplit(opt$params, ":");
		saux_2 <- strsplit(saux_1[[1]],"=");

		for (i in 1:length(saux_2))
		{
			params[[saux_2[[i]][1]]] <- strsplit(saux_2[[i]][2],",")[[1]];
		}
		rm(saux_1,saux_2);
	}

	if (is.null(params$vin) && opt$method  == "aloja_predict_instance")
	{
		if (length(params$inst_predict) == length(params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster");
		}
	}
	if (is.null(params$vin) && opt$method  == "aloja_predict_dataset")
	{
		if (all(colnames(params$ds) %in% params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster");
		}
	}

###############################################################################
# Execute call

	result <- do.call(opt$method,params);

	if (opt$verbose) result;

###############################################################################
# C'est fini

	quit(save="no", status=0);


require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_gbp)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gbp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 
human_num   <- function(x){human_numbers(x, smbl = "")} 
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(cancer,inputdf,sample)
{
  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{
    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
  
}

##' view 2
comp1view2Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }
}
## for user file input
comp1view2FilePlot = function(cancer,inputdf,sample){

  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{

      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(cutoff,cancer,score,sample){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(cancer,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
  geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(cancer,inputdf,sample)
{
  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{
    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
  
}

##' view 2
comp1view2Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }
}
## for user file input
comp1view2FilePlot = function(cancer,inputdf,sample){

  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{

      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(cutoff,cancer,score,sample){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(cancer,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
#' @include hcl.r
NULL

#' IWantHue palette generator.
#'
#' @field v8 The V8 context.
#' @export
IWantHue <- setRefClass("IWantHue",
  fields = list(v8 = "ANY"),
  methods = list(
  	initialize = function(context) {
  		v8 <<- context;
		v8$source(system.file("chroma.js", package = "rwantshue"))
		v8$source(system.file("chroma.palette-gen.js", package = "rwantshue"))
		v8$source(system.file("lodash.js", package = "rwantshue"))
		v8$eval("iwanthue = function(n, force_mode, quality, js_color_mapper, color_space) {
			filter_colors = function(color) {
			    var hcl = color.hcl();
			    return hcl[0] >= color_space[0][0] && hcl[0] <= color_space[0][1]
			      && hcl[1] >= color_space[1][0] && hcl[1] <= color_space[1][1]
			      && hcl[2] >= color_space[2][0] && hcl[2] <= color_space[2][1];
			}
			var colors = paletteGenerator.generate(n, filter_colors, force_mode, quality);
			colors = paletteGenerator.diffSort(colors);
			colors = _.map(colors, js_color_mapper);
			return JSON.stringify(colors);
		}")
  	},
  	palette = function(n = 8, force_mode = FALSE, quality = 50, color_space = hcl_presets$fancy_light,
  		js_color_mapper = "function(color) { return color.hex(); }") {
  		"Generate a new iwanthue palette"
  		assert_that(is.numeric(n), length(n) == 1)
  		assert_that(is.logical(force_mode), length(force_mode) == 1)
  		assert_that(is.numeric(quality), length(quality) == 1)
  		assert_that(is.hcl(color_space))
  		assert_that(is.character(js_color_mapper))
  		json <- v8$call("iwanthue", as.integer(n), force_mode, as.integer(quality), I(js_color_mapper), color_space)
  		fromJSON(json)
  	},
    hex = function(...) {
	  	"Generate a vector of colors in hex format"
	  	.self$palette(...)	  	
	},
	rgb = function(...) {
		"Generate a matrix of colors in rgb format"
		.self$palette(..., js_color_mapper = "function(color) { return color.rgb; }")
	}
  )
)

#' Create a new \linkS4class{IWantHue} object.
#' 
#' @export
iwanthue <- function() {
	IWantHue$new(new_context())
}#' @include hcl.r
NULL

#' IWantHue palette generator.
#'
#' @field v8 The V8 context.
#' @export
IWantHue <- setRefClass("IWantHue",
  fields = list(v8 = "ANY"),
  methods = list(
  	initialize = function(context) {
  		v8 <<- context;
		v8$source(system.file("chroma.js", package = "rwantshue"))
		v8$source(system.file("chroma.palette-gen.js", package = "rwantshue"))
		v8$source(system.file("lodash.js", package = "rwantshue"))
		v8$eval("iwanthue = function(n, force_mode, quality, js_color_mapper, color_space) {
			filter_colors = function(color) {
			    var hcl = color.hcl();
			    return hcl[0] >= color_space[0][0] && hcl[0] <= color_space[0][1]
			      && hcl[1] >= color_space[1][0] && hcl[1] <= color_space[1][1]
			      && hcl[2] >= color_space[2][0] && hcl[2] <= color_space[2][1];
			}
			var colors = paletteGenerator.generate(n, filter_colors, force_mode, quality);
			colors = paletteGenerator.diffSort(colors);
			colors = _.map(colors, js_color_mapper);
			return JSON.stringify(colors);
		}")
  	},
  	palette = function(n = 8, force_mode = FALSE, quality = 50, color_space = hcl_presets$fancy_light,
  		js_color_mapper = "function(color) { return color.hex(); }") {
  		"Generate a new iwanthue palette"
  		assert_that(is.numeric(n), length(n) == 1)
  		assert_that(is.logical(force_mode), length(force_mode) == 1)
  		assert_that(is.numeric(quality), length(quality) == 1)
  		assert_that(is.hcl(color_space))
  		assert_that(is.character(js_color_mapper))
  		json <- v8$call("iwanthue", as.integer(n), force_mode, as.integer(quality), I(js_color_mapper), color_space)
  		fromJSON(json)
  	},
    hex = function(...) {
	  	"Generate a vector of colors in hex format"
	  	.self$palette(...)	  	
	},
	rgb = function(...) {
		"Generate a matrix of colors in rgb format"
		.self$palette(..., js_color_mapper = I("function(color) { return color.rgb; }"))
	}
  )
)

#' Create a new \linkS4class{IWantHue} object.
#' 
#' @export
iwanthue <- function() {
	IWantHue$new(new_context())
}
require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_gbp)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gbp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 

require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_gdp)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gdp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 
#' rwantshue is a R adaptor for the "I want hue" color palette generator
#'
#' @docType package
#' @import V8 jsonlite
#' @name rwantshue
NULL
#' Evaluate the bandwidth selection criterion for a given bandwidth
#' 
#' @param formula symbolic representation of the model
#' @param data data frame containing observations of all the terms represented in the formula
#' @param weights vector of prior observation weights (due to, e.g., overdispersion). Not related to the kernel weights.
#' @param family exponential family distribution of the response
#' @param bw bandwidth for the kernel
#' @param kernel kernel function for generating the local observation weights
#' @param coords matrix of locations, with each row giving the location at which the corresponding row of data was observed
#' @param longlat \code{TRUE} indicates that the coordinates are specified in longitude/latitude, \code{FALSE} indicates Cartesian coordinates. Default is \code{FALSE}.
#' @param varselect.method criterion to minimize in the regularization step of fitting local models - options are \code{AIC}, \code{AICc}, \code{BIC}, \code{GCV}
#' @param tol.loc tolerance for the tuning of an adaptive bandwidth (e.g. \code{knn} or \code{nen})
#' @param bw.type type of bandwidth - options are \code{dist} for distance (the default), \code{knn} for nearest neighbors (bandwidth a proportion of \code{n}), and \code{nen} for nearest effective neighbors (bandwidth a proportion of the sum of squared residuals from a global model)
#' @param bwselect.method criterion to minimize when tuning bandwidth - options are \code{AICc}, \code{BICg}, and \code{GCV}
#' @param verbose print detailed information about our progress?
#' 
#' @return value of the \code{bwselect.method} criterion for the given bandwidth
#' 
lagr.tune.bw = function(x, y, weights, coords, dist, family, bw, kernel, env, oracle, varselect.method, tol.loc, bw.type, bwselect.method, min.dist, max.dist, lambda.min.ratio, n.lambda, lagr.convergence.tol, lagr.max.iter, verbose) {    
    #Fit the model with the given bandwidth:
    cat(paste('Bandwidth: ', round(bw, 3), '; ', sep=""))

    # Tell lagr.dispatch whether to select bandwidth via the jacknife
    if (bwselect.method=='jacknife') {
        jacknife = TRUE
    } else {
        jacknife = FALSE
    }


    vcr.model = lagr.dispatch(
        x=x,
        y=y,
        coords=coords,
        fit.loc=NULL,
        D=dist,
        family=family,
        prior.weights=weights,
        tuning=TRUE,
        predict=FALSE,
        simulation=FALSE,
        oracle=oracle,
        varselect.method=varselect.method,
        verbose=verbose,
        bw=bw,
        bw.type=bw.type,
        kernel=kernel,
        min.dist=min.dist,
        max.dist=max.dist,
        tol.loc=tol.loc,,
        lambda.min.ratio=lambda.min.ratio,
        n.lambda=n.lambda, 
        lagr.convergence.tol=lagr.convergence.tol,
        lagr.max.iter=lagr.max.iter
    )
    
    res = mget('trace', env=env, ifnotfound=list(matrix(NA, nrow=0, ncol=3)))
    res$trace = as.data.frame(rbind(res$trace, c(bw, vcr.model[[bwselect.method]], vcr.model$df)))
    colnames(res$trace) = c("bw", "loss", "df")
    res$trace = res$trace[order(res$trace$bw),]
    assign('trace', res$trace, env=env)
    
    cat(paste('df: ', round(vcr.model$df,4), '; Loss: ', signif(vcr.model[[bwselect.method]], 5), '\n', sep=''))
    return(vcr.model[[bwselect.method]])
}
`%||%` <- function(x, y) if (is.null(x)) y else x

#' Merge two lists and overwrite latter entries with former entries
#' if names are the same.
#'
#' For example, \code{list_merge(list(a = 1, b = 2), list(b = 3, c = 4))}
#' will be \code{list(a = 1, b = 3, c = 4)}.
#' @param list1 list
#' @param list2 list
#' @return the merged list.
#' @examples
#' stopifnot(identical(syberiaStages:::list_merge(list(a = 1, b = 2), list(b = 3, c = 4)),
#'                     list(a = 1, b = 3, c = 4)))
#' stopifnot(identical(syberiaStages:::list_merge(NULL, list(a = 1)), list(a = 1)))
# TODO: (RK) This is a duplicate of the function in mungebits -- is there
# any way to pull them out into one place? Maybe Ramd?
list_merge <- function(list1, list2) {
  list1 <- list1 %||% list()
  # Pre-allocate memory to make this slightly faster.
  list1[Filter(function(x) nchar(x) > 0, names(list2) %||% c())] <- NULL
  for (i in seq_along(list2)) {
    name <- names(list2)[i]
    if (!identical(name, NULL) && !identical(name, "")) list1[[name]] <- list2[[i]]
    else list1 <- append(list1, list(list2[[i]]))
  }
  list1
}

#' Parse functions out of a custom resource.
#'
#' @param functions character. The names of functions to parse out.
#' @param provided_env environment. The environment the resource was loaded from.
#' @param type character. The keyword for the resource.
#' @param resource_type character. The type of the resource (e.g., "classifier",
#'   "adapter", etc.). This will be used to generate error messages.
#' @param strict logical. Whether or not to error if the functions are not found.
#' @return a list containing keys same as the \code{functions} argument.
#'    and predict functions.
parse_custom_functions <- function(functions, provided_env, type,
                                   resource_type = 'classifier', strict = TRUE) {
  provided_fns <- setNames(vector('list', length(functions)), functions)
  for (function_type in names(provided_fns)) {
    fn <- Filter(
      function(x) is.function(provided_env[[x]]),
      grep(function_type, ls(provided_env), value = TRUE)
    )
    # TODO: (RK) Refactor this to be more careful about idempotent resources.
    error <- function(snip = 'a') paste0("The custom ", resource_type, " in ",
      "lib/", resource_type, "s/", type, ".R should define ", snip, " '",
      director:::colourise(function_type, 'green'), "' function.")
    if (length(fn) == 0 && identical(strict, TRUE)) stop(error(), call. = FALSE)
    else if (length(fn) > 1)
      stop(error('only one'), " Instead, you defined ", length(fn), ", namely: ",
           paste0(fn, collapse = ', '), call. = FALSE)
    else if (length(fn) == 1)
      provided_fns[[function_type]] <- provided_env[[fn]]
  }
  provided_fns
}

#' Helper function to recursively check the existence of a given name.
#'
#' TODO: (fye) Check if this function can be simplified.
#name_exists <- function(object_name, envir = parent.frame()) {
#  names <- strsplit(object_name, split="\\$")[[1]]
#  if (!names[1] %in% ls(envir, all.names = TRUE)) return(FALSE)
#  if (length(names) == 1) return(TRUE)
#  if (is.list(envir[[names[1]]]))
#    Recall(paste(names[-1], collapse = "$"), envir = list2env(envir[[names[1]]]))
#  else if (is.environment(envir[[names[1]]]))
#    Recall(paste(names[-1], collapse = "$"), envir = envir[[names[1]]])
#  else 
#    FALSE
#}
#'  Package to read from ADIOS, including staging.
#'
#' @name pbdADIOS-package
#'
#' @exportPattern "^adios\\.[[:alpha:]]+"
#' @exportPattern "^custom\\.[[:alpha:]]+"
#'
#' @useDynLib pbdADIOS,
#   ### Reader
#'  R_adios_read_init_method,
#'  R_adios_read_open,
#'  R_adios_read_close,
#'  R_adios_read_finalize_method,
#'  R_adios_inq_var,
#'  R_custom_inq_var_ndim,
#'  R_custom_inq_var_dims,
#'  R_adios_inq_var_blockinfo,
#'  R_adios_selection_bounding_box,
#'  R_adios_schedule_read,
#'  R_custom_data_access,
#'  R_adios_perform_reads,
#'  R_adios_advance_step,
#'  R_adios_errno,
#   ### Writer
#'  R_adios_init_noxml,
#'  R_adios_allocate_buffer,
#'  R_adios_declare_group,
#'  R_adios_select_method,
#'  R_adios_define_var,
#'  R_adios_open,
#'  R_adios_group_size,
#'  R_adios_write,
#'  R_adios_close,
#'  R_adios_finalize
#'
#' @import pbdMPI
#' @docType package
#' @title logisticPCA-package
#' @author Pragneshkumar Patel, George Ostrouchov, Wei-Chen Chen, Drew Schmidt
#' @keywords package
NULL

require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gdp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 
# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  if (length(.stages) == 0) {
    warning("stageRunners with zero stages may cause problems.", .call = FALSE)
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # Functions which intertwine with the objectdiff package
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

 #SNOPSIS

 #runs principal component analysis using prcomp

 #AUTHOR
 # Isaak Y Tecle (iyt2@cornell.edu)


options(echo = FALSE)

library(imputation)

allArgs <- commandArgs()


outFile <- grep("output_files",
                allArgs,
                ignore.case = TRUE,
                perl = TRUE,
                value = TRUE
                )

outFiles <- scan(outFile,
                 what = "character"
                 )

genoDataFile <- grep("genotype_data",
                   allArgs,
                   ignore.case = TRUE,
                   fixed = FALSE,
                   value = TRUE
                   )

scoresFile <- grep("pca_scores",
                        outFiles,
                        ignore.case = TRUE,
                        fixed = FALSE,
                        value = TRUE
                        )

loadingsFile <- grep("pca_loadings",
                        outFiles,
                        ignore.case = TRUE,
                        fixed = FALSE,
                        value = TRUE
                        )

varianceFile <- grep("pca_variance",
                        outFiles,
                        ignore.case = TRUE,
                        fixed = FALSE,
                        value = TRUE
                        )


message("genotype file: ", genoDataFile)
message("pca scores file: ", scoresFile)
message("pca loadings file: ", loadingsFile)
message("pca variance file: ", varianceFile)

if (is.null(genoDataFile))
{
  stop("genotype dataset missing.")
}

if (is.null(scoresFile))
{
  stop("Scores output file is missing.")
}

if (is.null(loadingsFile))
{
  stop("Laodings file is missing.")
}

genoData <- read.table(genoDataFile,
                        header = TRUE,
                        row.names = 1,
                        sep = "\t",
                        na.strings = c("NA", " ", "--", "-", "."),
                        dec = "."
                        )


if (sum(is.na(genoData)) > 0) {
    message("sum of geno missing values, ", sum(is.na(genoData)) )
    genoData <-kNNImpute(genoData, 10)
    genoData <-as.data.frame(genoData)

    #extract columns with imputed values
    genoData <- subset(genoData,
                       select = grep("^x", names(genoData))
                       )

    #remove prefix 'x.' from imputed columns
    names(genoData) <- sub("x.", "", names(genoData))

    genoData <- round(genoData, digits = 0)
    genoData <- data.matrix(genoData)
  }

pca <- prcomp(genoData, retx=TRUE)

scores <- round(pca$x[, 1:10], digits=2)

loadings <- round(pca$rotation[, 1:10], digits=5)

totalVar <- sum((pca$sdev)^2)

variances <- unlist(lapply(pca$sdev, function(x) round((x^2 / totalVar)*100, digits=2)))

variances <- as.data.frame(variances)
colnames(variances)[1] <- "variances"

write.table(scores,
            file = scoresFile,
            sep = "\t",
            col.names = NA,
            quote = FALSE,
            append = FALSE
            )

write.table(loadings,
            file = loadingsFile,
            sep = "\t",
            col.names = NA,
            quote = FALSE,
            append = FALSE
            )


write.table(variances,
            file = varianceFile,
            sep = "\t",
            col.names = NA,
            quote = FALSE,
            append = FALSE
            )

q(save = "no", runLast = FALSE)
# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # Functions which intertwine with the objectdiff package
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  if (a<0) 
    stop("haven't handled the negative case but shouldn't happen for 289 million years when reading a unix time in ms so should be safe")
  c = a*2^32 + b
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
latencySeconds=readInteger()
src = readShort()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(latencySeconds)
print(src)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(12, latencySeconds)
assertEquals(1, src)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  if (a<0) 
    stop("haven't handled the negative case but shouldn't happen for 289 million years when reading a unix time in ms so should be safe")
  c = a*2^32 +b
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
latencySeconds=readInteger()
src = readShort()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(latencySeconds)
print(src)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(12, latencySeconds)
assertEquals(1, src)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  if (a<0) 
    stop("haven't handled the negative case but shouldn't happen for millions of years when reading a unix time in ms so should be safe")
  c = a*2^32 +b
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
latencySeconds=readInteger()
src = readShort()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(latencySeconds)
print(src)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(12, latencySeconds)
assertEquals(1, src)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    # TODO: (RK) Compare actual names rather than indices.
    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    # TODO: (RK) Compare actual names rather than indices.
    compare_head <- function(x, y) { m <- min(length(x), length(y)); x[m] != y[m] }
    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

context("Basic Tests")

test_that("A basic rgithub context can be acquired", {
  create.github.context("https://api.github.com")
  repos <- get.user.repositories("cscheid")
  repos_overview <- do.call("rbind",
                            lapply(repos$content[1:5], function(x) {
                              data.frame(name = x$name,
                                         owner = x$owner$login,
                                         updated_at = x$updated_at)}))
  cat("\n")
  print(repos_overview)
})
library(xlsx)
dataset <- read.xlsx("karina/dataset.xlsx", sheetIndex=1)
options(width=10000) 

get <- function(geneName) {
  a = dataset[dataset$Genes == geneName,];
  return (a) 
}

genes <- function() {
    return (as.character(dataset$David.Input))
} 

fc <- function(genes) {
#    a = dataset[match(genes, dataset$Genes),];
#    b = as.numeric(as.character(a$dm))

  r <- rnorm2(length(genes), 0, 1)
  if(length(genes) == 1) {
    r <- rnorm2(2, 0, 1)
    return (c(r[1]))
  }
  return (c(r))
#   return (b) 
}

pvalues <- function(genes) { 
    a = dataset[match(genes, dataset$Genes),];
    b = as.numeric(as.character(a$BH_adj_pval))
    return(b) 
}

exprs <- function(gene) { 
    r <- rnorm2(100,0,1)
  return 
}
file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  # now need to do some bit manipulations to get the desired 8 byte integer as a double
  0
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                defining_environment = 'environment',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director, defining_environment) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      defining_environment <<- defining_environment
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        scoping_environment <- environment(injects$helper) <- local({
          e <- new.env(parent = defining_environment)
          e$director <- director
          e
        })
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        environment(injects$resource) <- scoping_environment
        injects$resource_name <- resource_key
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(injects$helper) <- scoping_environment
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        fn <- function(source_args) { do.call(base::source, source_args)$value }
        environment(fn) <- defining_environment
        list(value = fn(source_args), preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                defining_environment = 'environment',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director, defining_environment) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      defining_environment <<- defining_environment
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        environment(injects$resource) <- defining_environment
        injects$resource_name <- resource_key
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        environment(injects$helper) <- defining_environment
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        fn <- function(source_args) { do.call(base::source, source_args)$value }
        environment(fn) <- defining_environment
        list(value = fn(source_args), preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
load("starter.RData")
load("gloc.RData")


##' Fetches the chromosomal locations for all genes and sorts them within each chromosome. 
##' @params tcgaResults the list with TCGA results
##' @params ccleResults the list with CCLE results
##' @return a data.frame with locations for all genes
##' @author Andreas Schlicker (a.schlicker@nki.nl)
sortGenesByLocation = function(tcgaResults, ccleResults) {
	# Genes in all cancer types
	genes = rownames(tcgaResults[[1]]$prioritize.combined)
	for (n in 2:length(tcgaResults)) {
		genes = intersect(genes, rownames(tcgaResults[[n]]$prioritize.combined))
	}
	for (n in 1:length(ccleResults)) {
		genes = intersect(genes, rownames(ccleResults[[n]]$prioritize.combined))
	}

	# Find all gene locations
	mart = useMart(host="ensembl.org", path="/biomart/martservice", biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
	geneLoc = getBM(attributes=c("hgnc_symbol", "chromosome_name", "start_position", "end_position", "strand", "band"), filters=c("hgnc_symbol"), values=genes, mart=mart)
	# Remove all non-standard chromosome names and make everything numeric
	geneLoc = geneLoc[which(geneLoc[, "chromosome_name"] %in% c("1", "2", "3", "4", "5", "6", "7", "8", 
																															"9", "10", "11", "12", "13", "14", "15", 
																															"16", "17", "18", "19", "20", "21", "22", 
																															"X", "Y")), ]
	geneLoc[which(geneLoc[, "chromosome_name"] == "X"), "chromosome_name"] = "23"
	geneLoc[which(geneLoc[, "chromosome_name"] == "Y"), "chromosome_name"] = "24"
	geneLoc[, "chromosome_name"] = as.integer(geneLoc[, "chromosome_name"])
	
	geneLoc[which(geneLoc[, "strand"] == 1), "strand"] = "+"
	geneLoc[which(geneLoc[, "strand"] == -1), "strand"] = "-"
	
	# Return the sorted gene information
	geneLoc[order(geneLoc$chromosome_name, geneLoc$start_position), ]
}


##' Generates a chromosome plot for the selected score or the number of affected samples.
##' @params geneLocs the data.frame returned by sortGenesByLocation()
##' @params results either tcgaResults or ccleResults
##' @params cancType the selected four letter cancer code
##' @params chrom the selected chromosome; X is coded as 23 and Y as 24
##' @params scoreType which score was selected; one of "OG", "TS", "CO"
##' @return a list with two plotting objects, "score" the actual score and "affected" the percentage of affected samples
##' @author Andreas Schlicker (a.schlicker@nki.nl) 
getScorePlot = function(geneLocs, results, cancType, chrom, scoreType) {
	scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
	
	# Get the genes for the selected chromosome
	genes = subset(geneLocs, chromosome_name==chrom)
	
	# Get the score vector
	score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.score"]
	# And the percentage of affected samples
	affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"]
	if (scoreType == "TS") {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.score"] * -1
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	} else {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "combined.score"]
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"] - 
							 results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	}
	
	# Plot two tracks, one for scores and the other one for percent affected samples 
	list(score=plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
						ranges=IRanges(start=genes[, "start_position"],
						       	       end=genes[, "end_position"]),
						score,
					        strand="*")), 
			      type=c("h", "g"),
			      ylim=c(min(score), max(score)),
			      col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
			      main=""),
	     affected=plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
		      	      			   ranges=IRanges(start=genes[, "start_position"],
		      	      			   		  end=genes[, "end_position"]),
		      	      			   affected,
						   strand="*")), 
				 type=c("h", "g"),
				 ylim=c(min(affected), max(affected)),
				 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
				 main=""))
}

## function for plotting the score data track across selected chromosome and cancer
getScorePlot2 = function(geneLocs, results, cancType, chrom, scoreType) {
  scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
  
  # Get the genes for the selected chromosome
  genes = subset(geneLocs, chromosome_name==chrom)
  
  # Get the score vector and the percentage of affected samples
  if (scoreType == "OG"){
    score = results[[cancType]][genes[, "hgnc_symbol"], "og.score"]
    #affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"]    
  }else if (scoreType == "TS") {
    score = results[[cancType]][genes[, "hgnc_symbol"], "ts.score"] * -1
    #affected = results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  } else {
    score = results[[cancType]][genes[, "hgnc_symbol"], "combined.score"]
    #affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"] - 
      results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  }
  
  # Plot two tracks, one for scores and the other one for percent affected samples 
  plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
                                          ranges=IRanges(start=genes[, "start_position"],
                                                         end=genes[, "end_position"]),
                                          score,
                                          strand="*")), 
                        type=c("h", "g"),
                        ylim=c(min(score), max(score)),
                        col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
                        main="")
}

## function for plotting the percentage of affected samples data track across selected chromosome and cancer
getAffectedPlot2 = function(geneLocs, results, cancType, chrom, scoreType) {
  scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
  
  # Get the genes for the selected chromosome
  genes = subset(geneLocs, chromosome_name==chrom)
  
  # Get the score vector and the percentage of affected samples
  if (scoreType == "OG"){
    #score = results[[cancType]][genes[, "hgnc_symbol"], "og.score"]
    affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"]    
  }else if (scoreType == "TS") {
    #score = results[[cancType]][genes[, "hgnc_symbol"], "ts.score"] * -1
    affected = results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  } else {
    #score = results[[cancType]][genes[, "hgnc_symbol"], "combined.score"]
    affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"] - 
      results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  }
  
  # Plot two tracks, one for scores and the other one for percent affected samples 
  plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
                                             ranges=IRanges(start=genes[, "start_position"],
                                                            end=genes[, "end_position"]),
                                             affected,
                                             strand="*")), 
                           type=c("h", "g"),
                           ylim=c(min(affected), max(affected)),
                           col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
                           main="")
}


## main call to plot function
## view 1
comp3view1Plot <- function (cancer,scoreType,chr)
{
  if (scoreType == "TS")
  {
    res <- getScorePlot2(gloc, tcgaResultsPlotTrack, cancer, chr, 'TS')
  } else if (scoreType == "OG") {
    res <- getScorePlot2(gloc, ccleResultsPlotTrack, cancer, chr, 'OG')
  } else {
    res <- getScorePlot2(gloc, ccleResultsPlotTrack, cancer, chr, 'CO')
  }  
  res
}

## view 2
comp3view2Plot <- function (cancer,scoreType,chr)
{
  if (scoreType == "TS")
  {
    res <- getAffectedPlot2(gloc, tcgaResultsPlotTrack, cancer, chr, 'TS')
  } else if (scoreType == "OG") {
    res <- getAffectedPlot2(gloc, ccleResultsPlotTrack, cancer, chr, 'OG')
  } else  {
    res <- getAffectedPlot2(gloc, ccleResultsPlotTrack, cancer, chr, 'CO')
  }
  res
}

#' GUI for running LandsatLinkr
#'
#' GUI for running LandsatLinkr
#' @export

run_landsatlinkr = function(){
  
  choices = c("Prepare MSS",
              "Prepare TM/ETM+",
              "Calibrate MSS to TM/ETM+",
              "Composite imagery",
              "Fit neat lines")
  
  selection = select.list(choices, title = "Select a process to run")
  if(selection == "Prepare MSS"){process = seq(1:5)}
  if(selection == "Prepare TM/ETM+"){process = 6}
  if(selection == "Calibrate MSS to TM/ETM+"){process = 7}
  if(selection == "Composite imagery"){process = 8}
  if(selection == "Fit neat lines"){process = 9}
  
  if(sum(process %in% seq(1,8)) > 0){  
    choices = c("No", "Yes")
    selection = select.list(choices, title = "Process in parallel using 2 cores when possible?")
    if(selection == "No"){cores = 1}
    if(selection == "Yes"){cores = 2}
  }
  
  if(sum(process %in% seq(1,6)) > 0){
    scenedir = choose.dir(caption = "Select an MSS or TM/ETM+ scene directory. ex. 'C:/mss/036032'")
    reso = 60 #set default
    proj = "albers" #set default
    if(sum(process %in% c(1,6)) > 0){
      choices = c("30 meter", "60 meter")
      selection = select.list(choices, title = "Select a pixel resolution to use")
      if(selection == "30 meter"){reso = 30}
      if(selection == "60 meter"){reso = 60}
      
      choices = c("Native NAD83 UTM", "USGS North American Albers")
      selection = select.list(choices, title = "Select a map projection to use")
      if(selection == "Native NAD83 UTM"){proj = "default"}
      if(selection == "USGS North American Albers"){proj = "albers"}
    }
    
    demfile=NULL
    if(all(is.na(match(process,5))) == F){
      demfile = choose.files(caption = "Select a scene corresponding DEM file", multi=F)
    }
    #return(list(scenedir, demfile, proj, reso, process,cores))
    prepare_images(scenedir, demfile, proj=proj, reso=reso, process=process,cores=cores)
  }
  
  ################################
  #msscal and mixel
  if(sum(process %in% c(7,8)) > 0){
    if(sum(process %in% 7) > 0){
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      outdir=NULL
      index=NULL
      runname=NULL  
    }
    
    
    if(sum(process %in% 8) > 0){
      choices = c("No", "Yes")
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-1 scene directory to add?")
        if(answer == "Yes"){msswrs1dir = c(msswrs1dir, choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'"))}
      }
      
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-2 scene directory to add?")
        if(answer == "Yes"){msswrs2dir = c(msswrs2dir, choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'"))}
      }
      
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another TM WRS-2 scene directory to add?")
        if(answer == "Yes"){tmwrs2dir = c(tmwrs2dir, choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'"))}
        
        
        outdir = choose.dir(caption = "Select a directory to write the outputs to. ex. 'C:/composites/wrs2_034032'")
        
        #         choices = c("Tasseled cap angle",
        #                     "Tasseled cap brightness",
        #                     "Tasseled cap greenness",
        #                     "Tasseled cap wetness",
        #                     "All")
        #         selection = select.list(choices, title = "Select an index to create composites for")
        #         if(selection == "Tasseled cap angle"){index = "tca"}
        #         if(selection == "Tasseled cap brightness"){index = "tcb"}
        #         if(selection == "Tasseled cap greenness"){index = "tcg"}
        #         if(selection == "Tasseled cap wetness"){index = "tcw"}
        #         if(selection == "All"){index = "all"}
        
        runname = readline("Provide a unique name for the composite series. ex. project1: ")
        
        choices = c("From file",
                    "Provide coordinates")
        selection = select.list(choices, title = "What area do you want to create composites for?")
        if(selection == "From file"){useareafile = choose.files(caption = "Select a 'usearea' file", multi=F)}
        if(selection == "Provide coordinates"){
          check = 0
          while(check != 2){
            print("Please provide min and max xy coordinates (in image set projection units) defining a study area that intersects the image set")
            xmx = as.numeric(readline("max x coordinate: "))
            xmn = as.numeric(readline("min x coordinate: "))
            ymx = as.numeric(readline("max y coordinate: "))
            ymn = as.numeric(readline("min y coordinate: "))
            check = (xmx > xmn) + (ymx > ymn)
            if(check != 2){print("error - coordinates do not create a square - try again")}
          }
          useareafile = file.path(outdir, paste(runname,"_usearea.tif",sep=""))
          make_usearea_file(msswrs1dir[i], useareafile, xmx, xmn, ymx, ymn)
        }
      }
    }
    if(sum((process %in% 7) > 0)){process[1] = 1}
    if(sum((process %in% 8) > 0)){process[process==8] = 2}
    #return(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,cores,process)
    calibrate_and_composite(msswrs1dir,msswrs2dir,tmwrs2dir,index="all",outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=cores, process=process)
  }
  
  if(sum(process %in% 9 > 0)){
    dir = choose.dir(caption = "Select a composites directory from which to find image composite stacks")
    cores = readline("How many cores to use to process in parallel?: ")
    run_neatline(dir, cores)
  }
}
#' Convert DN values to surface reflectance
#'
#' Convert DN values to surface reflectance using the COST model with dark object subtraction
#' @param file The full path name of the *archv file
#' @param drkobjv dark object values from mssdofinder
#' @import raster
#' @export


msscost = function(file, drkobjv){
  
  #link to the equations to convert DN to TOA and TOA to SR
  #http://landsathandbook.gsfc.nasa.gov/data_prod/prog_sect11_3.html
  
  #read in the image metadata  
  info = get_metadata(file)
  
  #define esun values for mss (chander et al 2009 summary of current radiometric calibration coefficients... RSE 113)
  if(info$sensor == "LANDSAT_1"){esun = c(1823,1559,1276,880.1)}
  if(info$sensor == "LANDSAT_2"){esun = c(1829,1539,1268,886.6)}
  if(info$sensor == "LANDSAT_3"){esun = c(1839,1555,1291,887.9)}
  if(info$sensor == "LANDSAT_4"){esun = c(1827,1569,1260,866.4)}
  if(info$sensor == "LANDSAT_5"){esun = c(1824,1570,1249,853.4)}
  
  #define the earth sun distance 
  #d = 1.01497  #Earth-Sun Distance in Astronomical Units at DOY 213
  doy = as.numeric(substr(basename(file),14,16))
  d = eudist(doy)
  
  #read in the DN image data  
  b = brick(file)
  img = as.array(b) 
  
  drkobjv[1] = (info$b1gain*drkobjv[1])+info$b1bias
  drkobjv[2] = (info$b2gain*drkobjv[2])+info$b2bias
  drkobjv[3] = (info$b3gain*drkobjv[3])+info$b3bias
  drkobjv[4] = (info$b4gain*drkobjv[4])+info$b4bias
  
  img[,,1] = ((info$b1gain*img[,,1])+info$b1bias)-drkobjv[1]
  img[,,2] = ((info$b2gain*img[,,2])+info$b2bias)-drkobjv[2]
  img[,,3] = ((info$b3gain*img[,,3])+info$b3bias)-drkobjv[3]
  img[,,4] = ((info$b4gain*img[,,4])+info$b4bias)-drkobjv[4]
  
  img[img<0] = 0
  
  #convert solar zenith angle to radians for cos calculation (r expects radians)
  sunzenith = info$sunzen/57.2958 
  
  #calulate SR from DOS TOA
  img[,,1] = (pi * img[,,1] * (d^2))/(esun[1] * cos(sunzenith))
  img[,,2] = (pi * img[,,2] * (d^2))/(esun[2] * cos(sunzenith))
  img[,,3] = (pi * img[,,3] * (d^2))/(esun[3] * cos(sunzenith))
  img[,,4] = (pi * img[,,4] * (d^2))/(esun[4] * cos(sunzenith))
  
  #scale
  img = round(img * 10000)
  
  img = setValues(b,img)
  dataType(img) = "INT2S"
  projection(img) = set_projection(file)
  img = as(img, "SpatialGridDataFrame")         #convert the raster to SGHF so it can be written using GDAL (faster than writing it with the raster package)
  outfile = sub("archv", "dos_sr", file)
  writeGDAL(img, outfile, drivername = "GTiff", type = "Int16", mvFlag = -32768, options="INTERLEAVE=BAND")
  
}# Command line tools don’t want to clutter their output with unnecessary noise.
library = function (...)
    suppressMessages(base::library(...))

#' The command line arguments
args = commandArgs(trailingOnly = TRUE)

#' Quit the program
#'
#' @param code numeric exit code (default: \code{0})
exit = function (code = 0)
    quit(save = 'no', status = if (is.null(code)) 0 else code)

#' Execute the \code{entry_point} function defined by the caller
#'
#' Execute an entry point function, but only if the calling code is executed as
#' a stand-alone script, not when it is imported as a module.
#'
#' @param entry_point code or function to run (default: \code{main})
#' @return This function is called for its side-effect. If the calling code was
#' imported as a module, then return nothing. Otherwise, this function
#' \emph{does not return}; instead, it quits the script.
#'
#' @details The argument may either be a function (the default is assumed to be
#' a function called \code{main} in the calling code’s scope) or a
#' brace-enclosed expression. It is executed in the calling code’s scope.
#'
#' @examples
#' \dontrun{
#' main = function () { … }
#' # Run function `main`
#' sys$run()
#'
#' # Run the specified function
#' sys$run(function () { … })
#'
#' # Run the specified code
#' sys$run({ … })
#' }
run = function (entry_point = main) {
    caller = parent.frame()
    caller_name = evalq(modules::module_name(), envir = caller)

    if (is.null(caller_name)) {
        if (class(substitute(entry_point)) == '{')
            exit(entry_point)

        exit(eval(substitute(main(), list(main = entry_point)), envir = caller))
    }
}

# Load the Motor Trend data set
data(mtcars)
columns <- c(2,8,10,11) # Columns to convert to factors
mtcars[, columns] <- lapply(mtcars[,columns], as.factor) 
mtcars[, 9] <- factor(mtcars[, 9], labels=c("Auto", "Manual"))
predict_mtcars <- mtcars[1,]
rownames(predict_mtcars) <-NULL
shinyServer(function(input, output, session) {
        output$controls <- renderUI({
                if (is.null(input$tabs)) return()
                list(
                        if(any(input$predictors == "cyl")) 
                                sliderInput("cyl", 
                                            "Number of cylinders:", 
                                            min = 4, 
                                            max = 8,
                                            value = 4,
                                            step = 2),
                        if(any(input$predictors=="disp")) 
                                sliderInput("disp", 
                                            "Displacement:", 
                                            min = min(mtcars$disp), 
                                            max = max(mtcars$disp),
                                            value = min(mtcars$disp)),
                         if(any(input$predictors=="hp"))
                                sliderInput("hp", 
                                    "Gross Horsepower:", 
                                    min = min(mtcars$hp), 
                                    max = max(mtcars$hp),
                                    value = min(mtcars$hp)),
                        if(any(input$predictors=="drat"))
                                sliderInput("drat", 
                                    "Rear axle ratio:", 
                                    min = min(mtcars$drat), 
                                    max = max(mtcars$drat),
                                    value = min(mtcars$drat)),
                        if(any(input$predictors=="wt"))
                                sliderInput("wt", 
                                    "Weight:", 
                                    min = min(mtcars$wt), 
                                    max = max(mtcars$wt),
                                    value = min(mtcars$wt)),
                        if(any(input$predictors=="qsec"))
                                sliderInput("qsec", 
                                    "1/4 mile time:", 
                                    min = min(mtcars$qsec), 
                                    max = max(mtcars$qsec),
                                    value = min(mtcars$qsec)),
                        if(any(input$predictors=="vs"))
                                selectInput("vs", label = "Engine shape:", 
                                    choices = list("V" = 0, "Straight" = 1), 
                                    selected = 0),
                        if(any(input$predictors=="am"))
                                selectInput("am", label = "Transmission:", 
                                    choices = list("Automatic" = "Auto", "Manual" = "Manual"), 
                                    selected = 0),
                        if(any(input$predictors=="gear"))
                                sliderInput("gear", 
                                    "Gears:", 
                                    min = 3, 
                                    max = 5,
                                    value = 3,
                                    step=1),
                        if(any(input$predictors=="carb"))
                                selectInput("carb", label="Carburators:", 
                                    choices = list("1"=1,"2"=2,"3"=3,"4"=4,"6"=6,"8"),
                                    selected=1)
                )
                
        })
        
        model <- reactive({
                input$goButton
                isolate({
                        predictors <- input$predictors
                        sub_mtcars <<- mtcars[,c("mpg", predictors)]
                        lm(mpg ~ ., data=sub_mtcars)
                })
        })
        
        output$plot <- renderPlot({
                par(mfrow=c(2,2))
                plot(model())
        })
        output$summary <- renderPrint({
                summary(model())
        }) 

        observe({
                if (length(input$predictors) == 0)
                        updateCheckboxGroupInput(session, "predictors",
                                                 selected = "cyl")
        })        
        
        observe({
                if(input$tabs == "Model") return()
                if (!all(sort(input$predictors)==sort(names(sub_mtcars)[-1]))) 
                        updateTabsetPanel(session, "tabs", selected = "Model")
                
        })
        
        output$prediction <- renderText({
                if(!is.null(input$cyl)) predict_mtcars$cyl <- as.factor(input$cyl)
                if(!is.null(input$disp)) predict_mtcars$disp <- input$disp
                if(!is.null(input$hp)) predict_mtcars$hp <- input$hp
                if(!is.null(input$drat)) predict_mtcars$drat <-input$drat
                if(!is.null(input$wt)) predict_mtcars$wt <- input$wt
                if(!is.null(input$qsec)) predict_mtcars$qsec <- input$qsec
                if(!is.null(input$vs)) predict_mtcars$vs <- as.factor(input$vs)
                if(!is.null(input$am)) predict_mtcars$am <- as.factor(input$am)
                if(!is.null(input$gear)) predict_mtcars$gear <- as.factor(input$gear)
                if(!is.null(input$carb)) predict_mtcars$carb <- as.factor(input$carb)
                output$values <- renderPrint({
                        predict_mtcars[names(sub_mtcars[-1])]
                })
                paste(round(predict(model(),predict_mtcars),2), "mpg")
                    
        }) 
        
        
 
}
)# Pobrišemo PDF-je in počistimo delovno okolje
silent <- TRUE
source("clearpdf.r", encoding = "UTF-8")

# Če želimo nastaviti pisave v PDF-ju, odkomentiramo
# in sledimo navodilom v programu.
#source("fontconfig.r", encoding = "UTF-8")

# 2. faza: Obdelava, uvoz in čiščenje podatkov
source("uvoz/uvoz.r", encoding = "UTF-8")

# 3. faza: Analiza in vizualizacija podatkov
source("vizualizacija/vizualizacija.r", encoding = "UTF-8")

# 4. faza: Napredna analiza podatkov
source("analiza/analiza.r", encoding = "UTF-8")

cat("Končano.\n")
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Canonical words"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Purpose: {
		These words are used internally by REBOL and must have specific canon
		word values in order to be correctly identified.
	}
]

any-type!
any-word!
any-path!
any-function!
number!
scalar!
series!
any-string!
any-object!
any-block!

datatypes

native
self
none
true
false
on
off
yes
no
pi

rebol

system

;boot levels
base
sys
mods

;reflectors:
spec
body
words
values
types
title

x
y
+
-
*
unsigned
-unnamed- 	; lambda (unnamed) functions
-apply-		; apply func
code		; error field
delect

; Secure:  (add to system/state/policies object too)
secure
protect
net
call
envr
eval
memory
debug
browse
extension
;dir - below
;file - below

; Time:
hour
minute
second

; Date:
year
month
day
time
date
weekday
julian
yearday
zone
utc

; Parse: - These words must not reserved above!!
parse
|	 ; must be first
; prep words:
set  
copy
some
any
opt
not
and
then
remove
insert
change
if
fail
reject
while
return
limit
??
accept
break
; match words:
skip
to
thru
quote
do
into
only
end  ; must be last

; Event:
type
key
port
mode
window
double
control
shift

; Checksum
sha1
md4
md5
crc32
adler32

; Codec actions
identify
decode
encode

; Schemes
console
file
dir
event
callback
dns
tcp
udp
clipboard
serial
signal

; Serial parameters
; Parity
odd
even
; Control flow
hardware
software

; Struct
uint8
int8
uint16
int16
uint32
int32
uint64
int64
float
;double ;reuse earlier definition
pointer
addr
raw-memory
raw-size
rebval

;routine
void
library
name
abi
stdcall
fastcall
sysv
thiscall
unix64
ms-cdecl
win64
default
vfp ;arm
o32; mips abi
n32; mips abi
n64; mips abi
o32-soft-float; mips abi
n32-soft-float; mips abi
n64-soft-float; mips abi
...
varargs

; Gobs:
gob
offset
size
pane
parent
image
draw
text
effect
color
flags
rgb
alpha
data
resize
rotate
no-title
no-border
dropable
transparent
popup
modal
on-top
hidden
owner
active
minimize
maximize
restore 
fullscreen

*port-modes*

; posix signal names
all
sigalrm
sigabrt
sigbus
sigchld
sigcont
sigfpe
sighup
sigill
sigint
sigkill
sigpipe
sigquit
sigsegv
sigstop
sigterm
sigtstp
sigttin
sigttou
sigusr1
sigusr2
sigpoll
sigprof
sigsys
sigtrap
sigurg
sigvtalrm
sigxcpu
sigxfsz

bits
crash
crash-dump
watch-recycle
watch-obj-copy
stack-size

uid
euid
gid
egid
pid

;call/info
id
exit-code
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Canonical words"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Purpose: {
		These words are used internally by REBOL and must have specific canon
		word values in order to be correctly identified.
	}
]

any-type!
any-word!
any-path!
any-function!
number!
scalar!
series!
any-string!
any-object!
any-block!

datatypes

native
self
none
true
false
on
off
yes
no
pi

rebol

system

;boot levels
base
sys
mods

;reflectors:
spec
body
words
values
types
title

x
y
+
-
*
unsigned
-unnamed- 	; lambda (unnamed) functions
-apply-		; apply func
code		; error field
delect

; Secure:  (add to system/state/policies object too)
secure
protect
net
call
envr
eval
memory
debug
browse
extension
;dir - below
;file - below

; Time:
hour
minute
second

; Date:
year
month
day
time
date
weekday
julian
yearday
zone
utc

; Parse: - These words must not reserved above!!
parse
|	 ; must be first
; prep words:
set  
copy
some
any
opt
not
and
then
remove
insert
change
if
fail
reject
while
return
limit
??
accept
break
; match words:
skip
to
thru
quote
do
into
only
end  ; must be last

; Event:
type
key
port
mode
window
double
control
shift

; Checksum
sha1
md4
md5
crc32
adler32

; Codec actions
identify
decode
encode

; Schemes
console
file
dir
event
callback
dns
tcp
udp
clipboard
serial
signal

; Serial parameters
; Parity
odd
even
; Control flow
hardware
software

; Struct
uint8
int8
uint16
int16
uint32
int32
uint64
int64
float
;double ;reuse earlier definition
pointer
addr
raw-memory
raw-size
rebval

;routine
void
library
name
abi
stdcall
fastcall
sysv
thiscall
unix64
ms-cdecl
win64
default
vfp ;arm
o32; mips abi
n32; mips abi
n64; mips abi
o32-soft-float; mips abi
n32-soft-float; mips abi
n64-soft-float; mips abi
...
varargs

; Gobs:
gob
offset
size
pane
parent
image
draw
text
effect
color
flags
rgb
alpha
data
resize
rotate
no-title
no-border
dropable
transparent
popup
modal
on-top
hidden
owner
active
minimize
maximize
restore 
fullscreen

*port-modes*

; posix signal names
all
sigalrm
sigabrt
sigbus
sigchld
sigcont
sigfpe
sighup
sigill
sigint
sigkill
sigpipe
sigquit
sigsegv
sigstop
sigterm
sigtstp
sigttin
sigttou
sigusr1
sigusr2
sigpoll
sigprof
sigsys
sigtrap
sigurg
sigvtalrm
sigxcpu
sigxfsz

bits
crash
crash-dump
watch-recycle
watch-obj-copy
stack-size

uid
euid
gid
egid
pid

;call/info
id
exit-code
##' Generates pathview plots for all given results. This function can be used to plot 
##' different scores for one cancer type or one score across different cancer types.
##' If cancers == "all", only the first score in scores is plotted. In all other cases,
##' all scores are plotted for the first cancer only. 
##' @param tcgaResults the result list from a TCGA prioritization run
##' @param ccleResults the result list from a CCLE prioritization run
##' @param pathways vector with KEGG pathway IDs to plot; default: NULL (all pathways)
##' @param cancers vector of names of cancer types to plot; default: all
##' @param scores vector of names of the scores to plot; default: combined.score
##' @param out.dir directory for output files; default: "."
##' @param out.suffix suffix to be added to output plots; default: ""
##' @param kegg.dir directory with predownloaded KEGG files; all new downloaded files will be stored there;
##' default: "."
##' @author Andreas Schlicker
generatePathview = function(tcgaResults, ccleResults, pathway, cancers="all",
			    what=c("tcga", "ccle", "both"),
			    out.dir=".", out.suffix="", kegg.dir=".", 
	                    scores="combined.score") {
	# Get the score matrix and combine them if necessary
	if (what == "tcga") {
		if (cancers == "all") {
			cancers = names(tcgaResults)
		}
		scoreMat = pathviewMat(tcgaResults[intersect(cancers, names(tcgaResults))], scores[1])
	} else if (what == "ccle") {
		f (cancers == "all") {
			cancers = names(ccleResults)
=		}
		scoreMat = pathviewMat(ccleResults[intersect(cancers, names(ccleResults))], scores[1])
	} else {
		scoreMat = cbind(tcgaResults[[cancers[1]]]$prioritize.combined[, scores],
				 ccleResults[[cancers[1]]]$prioritize.combined[, scores])
	}
	
	if (scores == "combined.score") {
		low = list(gene="#034b87", cpd="blue")
		mid = list(gene="gray98", cpd="gray")
		high = list(gene="#880000", cpd="yellow")
		both.dirs = list(gene=TRUE, cpd=TRUE)
	} else if (scores == "og.score") {
		low = list(gene="gray98", cpd="blue")
		mid = list(gene="gray98", cpd="gray")
		high = list(gene="#880000", cpd="yellow")
		both.dirs = list(gene=FALSE, cpd=FALSE)
	} else (scores == "ts.score") {
		low = list(gene="gray98", cpd="blue")
		mid = list(gene="gray98", cpd="gray")
		high = list(gene="#034b87", cpd="yellow")
		both.dirs = list(gene=FALSE, cpd=FALSE)
	}
	
	limit = ifelse(is.null(limit), max(abs(scoreMat), na.rm=TRUE), limit)
	
	# Save working directory and switch to new one
	oldwd = getwd()
	setwd(out.dir)
	
	# Generate plots
	invisible(pathview(gene.data=scoreMat, pathway.id=pathway,
		           kegg.native=TRUE, gene.idtype="SYMBOL",
		           out.suffix=out.suffix, kegg.dir=kegg.dir,
		           limit=list(gene=limit, cpd=1), node.sum="max.abs",
		           multi.state=TRUE, low=low, mid=mid, high=high),
			   both.dirs=both.dirs)
	# Set old working directory
	setwd(oldwd)
}
#!/usr/bin/env Rscript

# Parse the --file= argument out of command line args and
# determine where base directory is so that we can source
# our common sub-routines
arg0 <- sub("--file=(.*)", "\\1", grep("--file=", commandArgs(), value = TRUE))
dir0 <- dirname(arg0)
source(file.path(dir0, "common.r"))

theme_set(theme_grey(base_size = 17))

# Setup parameters for the script
params = matrix(c(
  'help',    'h', 0, "logical",
  'width',   'x', 2, "integer",
  'height',  'y', 2, "integer",
  'outfile', 'o', 2, "character",
  'indir',   'i', 2, "character",
  'tstart',  '1',  2, "integer",
  'tend',    '2',  2, "integer",
  'ylabel1stgraph', 'Y',  2, "character"
  ), ncol=4, byrow=TRUE)

# Parse the parameters
opt = getopt(params)

if (!is.null(opt$help))
  {
    cat(paste(getopt(params, command = basename(arg0), usage = TRUE)))
    q(status=1)
  }

# Initialize defaults for opt
if (is.null(opt$width))   { opt$width   = 1280 }
if (is.null(opt$height))  { opt$height  = 1280 }
if (is.null(opt$indir))   { opt$indir  = "current"}
if (is.null(opt$outfile)) { opt$outfile = file.path(opt$indir, "summary.png") }
if (is.null(opt$ylabel1stgraph)) { opt$ylabel1stgraph = "Op/sec" }

# Load the benchmark data, passing the time-index range we're interested in
b = load_benchmark(opt$indir, opt$tstart, opt$tend)

# If there is no actual data available, bail
if (nrow(b$latencies) == 0)
{
  stop("No latency information available to analyze in ", opt$indir)
}

png(file = opt$outfile, width = opt$width, height = opt$height)

# First plot req/sec from summary
plot_throughput <- qplot(elapsed, successful / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = "Throughput") +

                geom_smooth(aes(y = successful / window, colour = "ok"), size=0.5) +
                geom_point(aes(y = successful / window, colour = "ok"), size=2.0) +

                geom_smooth(aes(y = failed / window, colour = "error"), size=0.5) +
                geom_point(aes(y = failed / window, colour = "error"), size=2.0) +

                scale_colour_manual("Response", values = c("#FF665F", "#188125"))

plot_sessions_running <- qplot(elapsed, running, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = "# sessions",
                 main = "Sessions Running") +

                 geom_point(aes(y = running, colour = "running"), size=2.0) +
                 geom_line( aes(y = running, colour = "running"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#000000"))

plot_sessions_started <- qplot(elapsed, starts / window, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                 main = "Sessions Started") +

                 geom_point(aes(y = starts / window, colour = "starts"), size=2.0) +
                 geom_line( aes(y = starts / window, colour = "starts"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#188125"))

# Setup common elements of the latency plots
latency_plot <- ggplot(b$latencies, aes(x = elapsed)) +
                   facet_grid(. ~ op) +
                   labs(x = "Elapsed Secs", y = "Latency (ms)")

# Plot median, mean and 95th percentiles
plot_median_mean <- latency_plot + labs(title = "Mean and Median Latency") +
            geom_smooth(aes(y = mean, color = "mean"), size=0.5) +
            geom_point(aes(y = mean, color = "mean"), size=2.0) +

            geom_smooth(aes(y = median, color = "median"), size=0.5) +
            geom_point(aes(y = median, color = "median"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FFA700", "#188125"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot median, mean and 95th percentiles
plot_95 <- latency_plot + labs(title = "95th Percentile Latency") +
            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot 99th percentile
plot_99 <- latency_plot + labs(title = "99th Percentile Latency") +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X99_9th","X99th" ),
            #                 labels = c("99.9th", "99th"))

# Plot 99.9th percentile
plot_999 <- latency_plot + labs(title = "99.9th Percentile Latency") +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

# Plot 100th percentile
plot_max <- latency_plot + labs(title = "Maximum Latency") +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

plot_upper_percentiles <- latency_plot + labs(title = "95th, 99th, 99.9th and 100th Percentile") +
            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FFFE00", "#FFA900", "#FF5600", "#FF0000"))

grid.newpage()

pushViewport(viewport(layout = grid.layout(5, 1)))

vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

print(plot_throughput, vp = vplayout(1,1))
print(plot_sessions_running, vp = vplayout(2,1))
print(plot_sessions_started, vp = vplayout(3,1))
print(plot_median_mean, vp = vplayout(4,1))
print(plot_upper_percentiles, vp = vplayout(5,1))

dev.off()
#' General-purpose data munging
#'
#' One can use \code{munge} to take a \code{data.frame}, apply a given set
#' of transformations, and persistently store the operations on
#' the \code{data.frame}, ready to run on a future \code{data.frame}.
#'
#' @param dataframe a data set to operate on.
#' @param ... usually a list specifying the necessary operations (see
#'    examples).
#' @param stagerunner logical or list. Whether to run the munge procedure or
#'    return the parametrizing stageRunner object (see package stagerunner).
#'    If a list, one can specify \code{remember = TRUE} to pass to the
#'    stageRunner initializer.
#' @param train_only logical. Whether or not to leave the \code{trained}
#'    parameter on each mungebit to \code{TRUE} or \code{FALSE} accordingly.
#'    For example, if \code{stagerunner = TRUE} and we are planning to re-use
#'    the stagerunner for prediction, it makes sense to leave the mungebits
#'    untrained. (Note that this will prevent one from being able to run the
#'    predict functions!)
#' @return data.frame that has had the specified operations applied to it,
#'    along with an additional property \code{mungepieces} that records
#'    the history of applied functions. These can be used to reproduce
#'    the transformations on e.g., a dataset that needs to have a
#'    prediction run.
#' @export
#' @examples
#' \dontrun{
#' iris2 <- munge(iris,
#'   list(column_transformation(function(x) 2 * x), 'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#'
#' iris2 <- munge(iris,
#'    # train function & predict function
#'    list(c(column_transformation(function(x) 2 * x),
#'         column_transformation(function(x) 3 * x)),
#'    # arguments to pass to transformation, i.e. column names in this case
#'    'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#' iris3 <- munge(iris, attr(iris2, 'mungepieces'))
#' # used transformations ("mungepieces") stored on iris2 and apply to iris3.
#' # They will remember that they've been trained already and run the
#' # prediction routine instead of the training routine. Note the above is
#' # also equivalent to the shortcut: munge(iris, iris2)
#' stopifnot(iris3[['Sepal.Length']] == iris[['Sepal.Length']] * 3)
#' }
munge <- function(dataframe, ..., stagerunner = FALSE, train_only = FALSE) {
  mungepieces <- list(...)
  if (length(mungepieces) == 0) return(dataframe)

  plane <- if (is.environment(dataframe)) dataframe else mungeplane(dataframe)

  if (is.data.frame(mungepieces[[1]]))
    mungepieces[[1]] <- attr(mungepieces[[1]], 'mungepieces')
  else if (is(mungepieces[[1]], 'tundraContainer'))
    mungepieces[[1]] <- mungepieces[[1]]$munge_procedure

  # If mungepieces[[1]] is of the form
  # list(list|mungepiece|function, list|mungepiece|function, ...)
  # just put it into mungepieces. This is so munge can be called as either
  # munge(dataframe, list(...)) or munge(dataframe, ...)
  if (length(mungepieces) == 1 && is.list(mungepieces[[1]]) &&
      all(unlist(lapply(mungepieces[[1]],
        function(x) is.mungepiece(x) || is.mungebit(x) || is.list(x) || is.function(x))))) {
      mungepieces <- mungepieces[[1]]
  }

  mungepieces <- lapply(mungepieces, parse_mungepiece,
                        train_only = !identical(train_only, FALSE))

  # order matters, do not parallelize!
  stages <- lapply(mungepieces, function(piece) {
    force(piece); function(env) piece$run(env)
  })
  stages <- append(stages, list(function(env) {
    # For now, store the mungepieces on the dataframe
    if (length(mungepieces) > 0)
      attr(env$data, 'mungepieces') <- append(attr(env$data, 'mungepieces'), mungepieces)
  }))
  names(stages)[length(stages)] <- "(Internal) Store munge procedure on dataframe"

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) require(stagerunner)
  remember <- if ('remember' %in% names(stagerunner)) stagerunner$remember else FALSE
  runner <- stageRunner$new(as.environment(plane), stages, remember = remember)

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) runner
  else {
    runner$run()
    plane$data
  }
}

context("Basic Tests")

test_that("A basic rgithub context can be acquired", {
  create.github.context("https://api.github.com")
  repos <- get.user.repositories("cscheid")
  repos_overview <- do.call("rbind",
                            lapply(repos$content[1:5], function(x) {
                              data.frame(name = x$name,
                                         owner = x$owner$login,
                                         updated_at = x$updated_at)}))
  cat("\n")
  print(repos_overview)
})
context("Basic Tests")

test_that("A basic rgithub context can be acquired", {
	create.github.context("https://api.github.com")
	repos <- get.user.repositories("cscheid")
	repos_overview <- do.call("rbind",
														lapply(repos$content[1:5], function(x) {
															data.frame(name = x$name,
																				 owner = x$owner$login,
																				 updated_at = x$updated_at)}))
	cat("\n")
	print(repos_overview)
})
#' GUI for running LandsatLinkr
#'
#' GUI for running LandsatLinkr
#' @export

run_landsatlinkr = function(){
  
  choices = c("Prepare MSS",
              "Prepare TM/ETM+",
              "Calibrate MSS to TM/ETM+",
              "Composite imagery")
  
  selection = select.list(choices, title = "Select a process to run")
  if(selection == "Prepare MSS"){process = seq(1:5)}
  if(selection == "Prepare TM/ETM+"){process = 6}
  if(selection == "Calibrate MSS to TM/ETM+"){process = 7}
  if(selection == "Composite imagery"){process = 8}
  
  
  choices = c("No", "Yes")
  selection = select.list(choices, title = "Process in parallel using 2 cores when possible?")
  if(selection == "No"){cores = 1}
  if(selection == "Yes"){cores = 2}
  
  if(sum(process %in% seq(1,6)) > 0){
    scenedir = choose.dir(caption = "Select an MSS or TM/ETM+ scene directory. ex. 'C:/mss/036032'")
    reso = 60 #set default
    proj = "albers" #set default
    if(sum(process %in% c(1,6)) > 0){
      choices = c("30 meter", "60 meter")
      selection = select.list(choices, title = "Select a pixel resolution to use")
      if(selection == "30 meter"){reso = 30}
      if(selection == "60 meter"){reso = 60}
      
      choices = c("Native NAD83 UTM", "USGS North American Albers")
      selection = select.list(choices, title = "Select a map projection to use")
      if(selection == "Native NAD83 UTM"){proj = "default"}
      if(selection == "USGS North American Albers"){proj = "albers"}
    }
    
    demfile=NULL
    if(all(is.na(match(process,5))) == F){
      demfile = choose.files(caption = "Select a scene corresponding DEM file", multi=F)
    }
    #return(list(scenedir, demfile, proj, reso, process,cores))
    prepare_images(scenedir, demfile, proj=proj, reso=reso, process=process,cores=cores)
  }
  
  ################################
  #msscal and mixel
  if(sum(process %in% c(7,8)) > 0){
    if(sum(process %in% 7) > 0){
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      outdir=NULL
      index=NULL
      runname=NULL  
    }
    
    
    if(sum(process %in% 8) > 0){
      choices = c("Yes", "No")
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-1 scene directory to add?")
        if(answer == "Yes"){msswrs1dir = c(msswrs1dir, choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'"))}
      }
      
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-2 scene directory to add?")
        if(answer == "Yes"){msswrs2dir = c(msswrs2dir, choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'"))}
      }
      
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another TM WRS-2 scene directory to add?")
        if(answer == "Yes"){tmwrs2dir = c(tmwrs2dir, choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'"))}
        
        
        outdir = choose.dir(caption = "Select a directory to write the outputs to. ex. 'C:/composites/wrs2_034032'")
        
        choices = c("Tasseled cap angle",
                    "Tasseled cap brightness",
                    "Tasseled cap greenness",
                    "Tasseled cap wetness",
                    "All")
        selection = select.list(choices, title = "Select an index to create composites for")
        if(selection == "Tasseled cap angle"){index = "tca"}
        if(selection == "Tasseled cap brightness"){index = "tcb"}
        if(selection == "Tasseled cap greenness"){index = "tcg"}
        if(selection == "Tasseled cap wetness"){index = "tcw"}
        if(selection == "All"){index = "all"}
        
        runname = readline("Provide a unique name for the composite series. ex. project1: ")
        
        choices = c("From file",
                    "Provide coordinates")
        selection = select.list(choices, title = "What area do you want to create composites for?")
        if(selection == "From file"){useareafile = choose.files(caption = "Select a 'usearea' file", multi=F)}
        if(Selection == "Provide coordinates"){
          check = 0
          while(check != 2){
            print("Please provide min and max xy coordinates (in image set projection units) defining a study area that intersects the image set")
            xmx = readline("max x coordinate: ")
            xmn = readline("min x coordinate: ")
            ymx = readline("max y coordinate: ")
            ymn = readline("min y coordinate: ")
            check = (xmx > xmn) + (ymx > ymn)
            if(check != 2){print("error - coordinates do not create a square - try again")}
          }
          useareafile = file.path(outdir, paste(runname,"_usearea.tif",sep=""))
          make_usearea_file(msswrs1dir[i], useareafile, xmx, xmn, ymx, ymn)
        }
      }
    }
    if(sum((process %in% 7) > 0)){process[1] = 1}
    if(sum((process %in% 8) > 0)){process[process==8] = 2}
    #return(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,cores,process)
    calibrate_and_composite(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=cores, process=process)
  } 
}
#' Calibrate MSS imagery to TM and make cloud-free composites 
#'
#' Calibrate MSS imagery to TM and make cloud-free composites   
#' @param msswrs1dir character. mss wrs1 directory path
#' @param msswrs2dir character. mss wrs2 directory path
#' @param tmwrs2dir character. tm wrs2 directory path
#' @param index character. spectral index to make composites for. options: "tca", "tcb", "tcg", "tcw"
#' @param outdir character. path to output directory
#' @param runname character. unique name for the composite set
#' @param useareafile character. path to usearea file
#' @param doyears ??? what years to composite
#' @param order character. how to order the images options "sensor_and_doy" and "doy"
#' @param overlap character. how to deal with overlapping images. options: "mean"
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @param process numeric. integer or vector specifying which processes to run: 1=msscal, 2=mixel
#' @import foreach
#' @import doParallel
#' @export


calibrate_and_composite = function(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=2, process=c(1,2)){
  
  #msscal
  if(all(is.na(match(process,1))) == F){
    print("Running msscal")
    t=proc.time()
    msscal(msswrs1dir, msswrs2dir, tmwrs2dir, cores=cores)
    print(proc.time()-t)
  }
  
  #mixel
  if(all(is.na(match(process,2))) == F){
    print("Running mixel")
    t=proc.time()
    if(index == "all"){
      index = c("tca", "tcb", "tcg", "tcw")
      outdir = c(file.path(outdir,"tca"),file.path(outdir,"tcb"),file.path(outdir,"tcg"),file.path(outdir,"tcw"))
      for(i in 1:length(index)){mixel2(msswrs1dir,msswrs2dir,tmwrs2dir,index[i],outdir[i],runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean")}
    } else {
      outdir = file.path(outdir,index)
      mixel2(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean")
    }
    print(proc.time()-t)
  }
}#!/usr/bin/env Rscript

library(DNAcopy)

options(warn=-1)
args <-commandArgs(trailingOnly = TRUE)

setwd(args[1])

c1 <- read.table("ChrI")
c2 <- read.table("ChrII")
c3 <- read.table("ChrIII")
c4 <- read.table("ChrIV")
c5 <- read.table("ChrV")
c6 <- read.table("ChrVI")
c7 <- read.table("ChrVII")
c8 <- read.table("ChrVIII")
c9 <- read.table("ChrIX")
c10 <- read.table("ChrX")
c11 <- read.table("ChrXI")
c12 <- read.table("ChrXII")
c13 <- read.table("ChrXIII")
c14 <- read.table("ChrXIV")
c15 <- read.table("ChrXV")
c16 <- read.table("ChrXVI")

c1$chr <- 1
c2$chr <- 2
c3$chr <- 3
c4$chr <- 4
c5$chr <- 5
c6$chr <- 6
c7$chr <- 7
c8$chr <- 8
c9$chr <- 9
c10$chr <- 10
c11$chr <- 11
c12$chr <- 12
c13$chr <- 13
c14$chr <- 14
c15$chr <- 15
c16$chr <- 16


merged <- rbind(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16)

pdf("cnv_report.pdf")
CNA.object <- CNA(merged$V1, merged$chr, merged$V2, data.type=("logratio"), presorted=TRUE)
CNA.smooth <- smooth.CNA(CNA.object)
CNA.segm <- segment(CNA.smooth)

plot(CNA.segm, plot.type="w")
plot(CNA.segm, plot.type="s")
plot(CNA.segm, plot.type="p")

c1.object <- CNA(c1$V1, c1$chr, c1$V2, data.type=("logratio"), presorted=TRUE)
c1.smooth <- smooth.CNA(c1.object)
c1.segm <- segment(c1.smooth)

plot(c1.segm, plot.type="s")

c2.object <- CNA(c2$V1, c2$chr, c2$V2, data.type=("logratio"), presorted=TRUE)
c2.smooth <- smooth.CNA(c2.object)
c2.segm <- segment(c2.smooth)

plot(c2.segm, plot.type="s")

c3.object <- CNA(c3$V1, c3$chr, c3$V2, data.type=("logratio"), presorted=TRUE)
c3.smooth <- smooth.CNA(c3.object)
c3.segm <- segment(c3.smooth)

plot(c3.segm, plot.type="s")

c4.object <- CNA(c4$V1, c4$chr, c4$V2, data.type=("logratio"), presorted=TRUE)
c4.smooth <- smooth.CNA(c4.object)
c4.segm <- segment(c4.smooth)

plot(c4.segm, plot.type="s")

c5.object <- CNA(c5$V1, c5$chr, c5$V2, data.type=("logratio"), presorted=TRUE)
c5.smooth <- smooth.CNA(c5.object)
c5.segm <- segment(c5.smooth)

plot(c5.segm, plot.type="s")

c6.object <- CNA(c6$V1, c6$chr, c6$V2, data.type=("logratio"), presorted=TRUE)
c6.smooth <- smooth.CNA(c6.object)
c6.segm <- segment(c6.smooth)

plot(c6.segm, plot.type="s")

c7.object <- CNA(c7$V1, c7$chr, c7$V2, data.type=("logratio"), presorted=TRUE)
c7.smooth <- smooth.CNA(c7.object)
c7.segm <- segment(c7.smooth)

plot(c7.segm, plot.type="s")

c8.object <- CNA(c8$V1, c8$chr, c8$V2, data.type=("logratio"), presorted=TRUE)
c8.smooth <- smooth.CNA(c8.object)
c8.segm <- segment(c8.smooth)

plot(c8.segm, plot.type="s")

c9.object <- CNA(c9$V1, c9$chr, c9$V2, data.type=("logratio"), presorted=TRUE)
c9.smooth <- smooth.CNA(c9.object)
c9.segm <- segment(c9.smooth)

plot(c9.segm, plot.type="s")

c10.object <- CNA(c10$V1, c10$chr, c10$V2, data.type=("logratio"), presorted=TRUE)
c10.smooth <- smooth.CNA(c10.object)
c10.segm <- segment(c10.smooth)

plot(c10.segm, plot.type="s")

c11.object <- CNA(c11$V1, c11$chr, c11$V2, data.type=("logratio"), presorted=TRUE)
c11.smooth <- smooth.CNA(c11.object)
c11.segm <- segment(c11.smooth)

plot(c11.segm, plot.type="s")

c12.object <- CNA(c12$V1, c12$chr, c12$V2, data.type=("logratio"), presorted=TRUE)
c12.smooth <- smooth.CNA(c12.object)
c12.segm <- segment(c12.smooth)

plot(c12.segm, plot.type="s")

c13.object <- CNA(c13$V1, c13$chr, c13$V2, data.type=("logratio"), presorted=TRUE)
c13.smooth <- smooth.CNA(c13.object)
c13.segm <- segment(c13.smooth)

plot(c13.segm, plot.type="s")

c14.object <- CNA(c14$V1, c14$chr, c14$V2, data.type=("logratio"), presorted=TRUE)
c14.smooth <- smooth.CNA(c14.object)
c14.segm <- segment(c14.smooth)

plot(c14.segm, plot.type="s")

c15.object <- CNA(c15$V1, c15$chr, c15$V2, data.type=("logratio"), presorted=TRUE)
c15.smooth <- smooth.CNA(c15.object)
c15.segm <- segment(c15.smooth)

plot(c15.segm, plot.type="s")

c16.object <- CNA(c16$V1, c16$chr, c16$V2, data.type=("logratio"), presorted=TRUE)
c16.smooth <- smooth.CNA(c16.object)
c16.segm <- segment(c16.smooth)

plot(c16.segm, plot.type="s")

dev.off()








########################################
#
# Program to run DESeq2 on the count data
#
########################################

setwd("~/jen/Files/")
require(DESeq2)
require(plyr)
require(biomaRt)

##### Part 1: Read in the data

alldirectories = c("run60msrnaseqwtsplnlungbbreg","run61msrnaseqdkospbbregwtlnbreg","run68mousernaseqtregsplnlung","run69mousernaseqtregs")
countdirectory="/home/trevor/jen/counts/"
summarytabledirectory="/home/trevor/jen/summarytables/"

# Count data
curfilesc = NULL
filenamesc = NULL
curtablefilec = vector("list",length(alldirectories))
removesummaryinfo <- function(data) {
	newdata = data[-which(substr(data$V1,1,2)=="__"),]
return(newdata)
}
for(i in 1:length(alldirectories)) {
	curdirectory = alldirectories[i]
	filenames = list.files(paste(countdirectory,curdirectory,"/",sep=""), pattern="*.txt", full.names=FALSE)
	curfiles = lapply(paste(countdirectory,curdirectory,"/",filenames,sep=""), read.table)
	curfilesc = c(curfilesc,lapply(curfiles,removesummaryinfo))
	filenamesc = c(filenamesc,paste(substr(curdirectory,1,5),filenames,sep=""))
	# Meta data
	curtablefilec[[i]] = read.table(paste(summarytabledirectory,curdirectory,"table.txt",sep=""), skip=3, sep="\t", header=TRUE)
	curtablefilec[[i]]$Sample.IDmod = paste(substr(curdirectory,1,5),curtablefilec[[i]][,3],sep="")
}
# Comparisons data
fc = file(paste(summarytabledirectory,"mousecomparisonswreps.txt",sep=""))
comparisonsfile = strsplit(readLines(fc), "\t")
close(fc)

##### Part 2: Format for DESeq analysis

countData = join_all(curfilesc,by="V1")
names(curtablefilec[[3]]) = names(curtablefilec[[1]])
allcolData = do.call(rbind,curtablefilec)
colnames(countData) = c("genes",sapply(strsplit(filenamesc,split="\\."),"[",1))
rownames(countData) = countData[,1]; countData2 = countData[,-1]
# Remove samples that were 0 in all runs
countData3 = countData2[-which(apply(countData2,1,sum)==0),]

##### Part 3: Run differential expression analysis on each comparison

allresults = vector("list",length(comparisonsfile))
for(i in 1:length(comparisonsfile)) {
	print(i)
	curcompsi = comparisonsfile[[i]]
	curcomps = NULL
	cursets = NULL
	for(j in 1:length(curcompsi)) {
		pullcomps = unlist(strsplit(curcompsi[[j]],split=" "))
		curcomps = c(curcomps,pullcomps)
		cursets = c(cursets,rep(j,length(pullcomps)))
	}
	pullcounts = which(colnames(countData3)%in%curcomps)
	pullcols = which(allcolData$Sample.IDmod%in%curcomps)
	curcolData = data.frame(condition=allcolData$Sample.Description[pullcols],group=as.factor(cursets))
	rownames(curcolData) = allcolData$Sample.IDmod[pullcols]
	curcountdata = countData3[,pullcounts]
	curcountdataorder = curcountdata[,match(colnames(curcountdata),rownames(curcolData))]
	if(length(unique(curcolData$group))>1) {
	dds = DESeqDataSetFromMatrix(countData = curcountdataorder, colData = curcolData, design = ~ group)
	}
	if(length(unique(curcolData$group))==1) { # Fall back on no replicates method if there are no replicates
	dds = DESeqDataSetFromMatrix(countData = curcountdataorder, colData = curcolData, design = ~ condition)
	}
	dds = DESeq(dds)
	res = results(dds)
	ressort = res[order(res$padj,decreasing=FALSE),]
	allresults[[i]] = ressort
}

##### Part 4: Annotate the results

for(i in 1:length(allresults)) {
ensembl = useMart("ensembl")
ensembl = useDataset("mmusculus_gene_ensembl",mart=ensembl)
annodata = getBM(attributes=c("ensembl_gene_id","external_gene_name","description"),filters="ensembl_gene_id",values=allresults[[i]]@rownames,mart=ensembl)
allresults[[i]]@listData = cbind(DataFrame(allresults[[i]]),annodata[match(allresults[[i]]@rownames,annodata$ensembl_gene_id),-1])
}

##### Part 5: Save the data

save(allresults,file="mouseanalysisresuls.rdata")
########################################
#
# Program to run DESeq2 on the count data
#
########################################

setwd("~/jen/Files/")
require(DESeq2)
require(plyr)
require(biomaRt)

##### Part 1: Read in the data

alldirectories = c("run60msrnaseqwtsplnlungbbreg","run61msrnaseqdkospbbregwtlnbreg","run68mousernaseqtregsplnlung","run69mousernaseqtregs")
countdirectory="/home/trevor/jen/counts/"
summarytabledirectory="/home/trevor/jen/summarytables/"

# Count data
curfilesc = NULL
filenamesc = NULL
curtablefilec = vector("list",length(alldirectories))
removesummaryinfo <- function(data) {
	newdata = data[-which(substr(data$V1,1,2)=="__"),]
return(newdata)
}
for(i in 1:length(alldirectories)) {
	curdirectory = alldirectories[i]
	filenames = list.files(paste(countdirectory,curdirectory,"/",sep=""), pattern="*.txt", full.names=FALSE)
	curfiles = lapply(paste(countdirectory,curdirectory,"/",filenames,sep=""), read.table)
	curfilesc = c(curfilesc,lapply(curfiles,removesummaryinfo))
	filenamesc = c(filenamesc,paste(substr(curdirectory,1,5),filenames,sep=""))
	# Meta data
	curtablefilec[[i]] = read.table(paste(summarytabledirectory,curdirectory,"table.txt",sep=""), skip=3, sep="\t", header=TRUE)
	curtablefilec[[i]]$Sample.IDmod = paste(substr(curdirectory,1,5),curtablefilec[[i]][,3],sep="")
}
# Comparisons data
fc = file(paste(summarytabledirectory,"mousecomparisonswreps.txt",sep=""))
comparisonsfile = strsplit(readLines(fc), "\t")
close(fc)

##### Part 2: Format for DESeq analysis

countData = join_all(curfilesc,by="V1")
names(curtablefilec[[3]]) = names(curtablefilec[[1]])
allcolData = do.call(rbind,curtablefilec)
colnames(countData) = c("genes",sapply(strsplit(filenamesc,split="\\."),"[",1))
rownames(countData) = countData[,1]; countData2 = countData[,-1]
# Remove samples that were 0 in all runs
countData3 = countData2[-which(apply(countData2,1,sum)==0),]

##### Part 3: Run differential expression analysis on each comparison

allresults = vector("list",length(comparisonsfile))
for(i in 1:length(comparisonsfile)) {
	print(i)
	curcompsi = comparisonsfile[[i]]
	curcomps = NULL
	cursets = NULL
	for(j in 1:length(curcompsi)) {
		pullcomps = unlist(strsplit(curcompsi[[j]],split=" "))
		curcomps = c(curcomps,pullcomps)
		cursets = c(cursets,rep(j,length(pullcomps)))
	}
	pullcounts = which(colnames(countData3)%in%curcomps)
	pullcols = which(allcolData$Sample.IDmod%in%curcomps)
	curcolData = data.frame(condition=allcolData$Sample.Description[pullcols],group=as.factor(cursets))
	rownames(curcolData) = allcolData$Sample.IDmod[pullcols]
	curcountdata = countData3[,pullcounts]
	curcountdataorder = curcountdata[,match(colnames(curcountdata),rownames(curcolData))]
	dds = DESeqDataSetFromMatrix(countData = curcountdataorder, colData = curcolData, design = ~ group)
	dds = DESeq(dds)
	res = results(dds)
	ressort = res[order(res$padj,decreasing=FALSE),]
	allresults[[i]] = ressort
}

##### Part 4: Annotate the results

for(i in 1:length(allresults)) {
ensembl = useMart("ensembl")
ensembl = useDataset("mmusculus_gene_ensembl",mart=ensembl)
annodata = getBM(attributes=c("ensembl_gene_id","external_gene_name","description"),filters="ensembl_gene_id",values=allresults[[i]]@rownames,mart=ensembl)
allresults[[i]]@listData = cbind(DataFrame(allresults[[i]]),annodata[match(allresults[[i]]@rownames,annodata$ensembl_gene_id),-1])
}

##### Part 5: Save the data

save(allresults,file="mouseanalysisresuls.rdata")
##' Fetches the chromosomal locations for all genes and sorts them within each chromosome. 
##' @params tcgaResults the list with TCGA results
##' @params ccleResults the list with CCLE results
##' @return a data.frame with locations for all genes
##' @author Andreas Schlicker (a.schlicker@nki.nl)
sortGenesByLocation = function(tcgaResults, ccleResults) {
	# Genes in all cancer types
	genes = rownames(tcgaResults[[1]]$prioritize.combined)
	for (n in 2:length(tcgaResults)) {
		genes = intersect(genes, rownames(tcgaResults[[n]]$prioritize.combined))
	}
	for (n in 1:length(ccleResults)) {
		genes = intersect(genes, rownames(ccleResults[[n]]$prioritize.combined))
	}

	# Find all gene locations
	mart = useMart(host="ensembl.org", path="/biomart/martservice", biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
	geneLoc = getBM(attributes=c("hgnc_symbol", "chromosome_name", "start_position", "end_position", "strand", "band"), filters=c("hgnc_symbol"), values=genes, mart=mart)
	# Remove all non-standard chromosome names and make everything numeric
	geneLoc = geneLoc[which(geneLoc[, "chromosome_name"] %in% c("1", "2", "3", "4", "5", "6", "7", "8", 
																															"9", "10", "11", "12", "13", "14", "15", 
																															"16", "17", "18", "19", "20", "21", "22", 
																															"X", "Y")), ]
	geneLoc[which(geneLoc[, "chromosome_name"] == "X"), "chromosome_name"] = "23"
	geneLoc[which(geneLoc[, "chromosome_name"] == "Y"), "chromosome_name"] = "24"
	geneLoc[, "chromosome_name"] = as.integer(geneLoc[, "chromosome_name"])
	
	geneLoc[which(geneLoc[, "strand"] == 1), "strand"] = "+"
	geneLoc[which(geneLoc[, "strand"] == -1), "strand"] = "-"
	
	# Return the sorted gene information
	geneLoc[order(geneLoc$chromosome_name, geneLoc$start_position), ]
}


##' Generates a chromosome plot for the selected score or the number of affected samples.
##' @params geneLocs the data.frame returned by sortGenesByLocation()
##' @params results either tcgaResults or ccleResults
##' @params cancType the selected four letter cancer code
##' @params chrom the selected chromosome; X is coded as 23 and Y as 24
##' @params scoreType which score was selected; one of "OG", "TS", "CO"
##' @return a list with two plotting objects, "score" the actual score and "affected" the percentage of affected samples
##' @author Andreas Schlicker (a.schlicker@nki.nl) 
getScorePlot = function(geneLocs, results, cancType, chrom, scoreType) {
	scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
	
	# Get the genes for the selected chromosome
	genes = subset(geneLocs, chromosome_name==chrom)
	
	# Get the score vector
	score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.score"]
	# And the percentage of affected samples
	affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"]
	if (scoreType == "TS") {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.score"] * -1
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	} else {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "combined.score"]
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"] - 
							 results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	}
	
	# Plot two tracks, one for scores and the other one for percent affected samples 
	list(score=plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
						ranges=IRanges(start=genes[, "start_position"],
						       	       end=genes[, "end_position"]),
						score,
					        strand="*")), 
			      type=c("h", "g"),
			      ylim=c(min(score), max(score)),
			      col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
			      main=""),
	     affected=plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
		      	      			   ranges=IRanges(start=genes[, "start_position"],
		      	      			   		  end=genes[, "end_position"]),
		      	      			   affected,
						   strand="*")), 
				 type=c("h", "g"),
				 ylim=c(min(affected), max(affected)),
				 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
				 main=""))
}

# TODO: silently install packages if not installed!!!

library('jsonlite')

connectToServer = function(port) {
  while(TRUE) {
    socket = try(suppressWarnings(socketConnection('localhost', port, open="w+", blocking=TRUE)), TRUE)
    if(inherits(socket, 'try-error')) {
      Sys.sleep(0.1)
    } else {
      break
    }
  }
  return(socket)
}

listenToMessages = function() {
  while(TRUE) {
    message = readLines(SOCKET, n=1)
    # debug('received', message)
    message = try(fromJSON(message), TRUE)

    if(is.list(message)) {
      if(message$type == 'query') {
        processQuery(message$query)
      }
    }
  }
}

processQuery = function(query) {
  # test if it parses
  parsed_query = try(parse(text=query), TRUE)
  if(inherits(parsed_query, 'try-error')) {
    sendError("Parse error")
    return(FALSE)
  } else {
    # run code in an isolated scope
    new_environment = new.env()
    results = eval(parsed_query, env=new_environment)

    sendResults(results)

    return(TRUE)
  }
}

# send message functions

sendResults = function(results) {
  message = list(type = 'results', results = processResults(results))
  sendMessage(message)
}

sendError = function(error) {
  message = list(type = 'error', error = error)
  sendMessage(message)
}

sendMessage = function(message) {
  encoded_message = toJSON(message, auto_unbox=TRUE)
  writeLines(encoded_message, SOCKET)
  flush(SOCKET)
  # debug('sent', encoded_message)
}

# process results

processResults = function(results) {
  serializeJSON(results)
}

# nasty debug function (will be removed soon...)

debug = function(title, message) {
  message(paste0("!! ", toupper(title), ": ", message))
}

#' Dispatch the fitting of local models to parallel cores, if registered
#' 
#' Loops through estimation locations with foreach, sending each local model to a core for fitting. If zero or one cores are registered, then foreach computes the local models sequentially.
#' 
#' @param x matrix of observed covariates
#' @param y vector of observed responses
#' @param family exponential family distribution of the response
#' @param coords matrix of locations, with each row giving the location at which the corresponding row of data was observed
#' @param fit.loc matrix of locations where the local models should be fitted
#' @param kernel kernel function for generating the local observation weights
#' @param bw bandwidth parameter
#' @param bw.type type of bandwidth - options are \code{dist} for distance (the default), \code{knn} for nearest neighbors (bandwidth a proportion of \code{n}), and \code{nen} for nearest effective neighbors (bandwidth a proportion of the sum of squared residuals from a global model)
#' @param tol.loc tolerance for the tuning of an adaptive bandwidth (e.g. \code{knn} or \code{nen})
#' @param varselect.method criterion to minimize in the regularization step of fitting local models - options are \code{AIC}, \code{AICc}, \code{BIC}, \code{GCV}
#' @param tuning logical indicating whether this model will be used to tune the bandwidth, in which case only the tuning criteria are returned
#' @param D pre-specified matrix of distances between locations
#' @param verbose print detailed information about our progress?
#' 
lagr.dispatch = function(x, y, family, coords, fit.loc, oracle, D, bw, bw.type, verbose, varselect.method, prior.weights, tuning, predict, simulation, kernel, min.bw, max.bw, min.dist, max.dist, tol.loc, lambda.min.ratio, n.lambda, lagr.convergence.tol, lagr.max.iter, jacknife=FALSE, bootstrap.index=NULL) {
    if (!is.null(fit.loc)) { coords.fit = fit.loc }
    else { coords.fit = coords }
    n = nrow(coords.fit)

    vcr.model = list()

    #For the adaptive bandwith methods, use a default tolerance if none is specified:
    if (is.null(tol.loc)) {tol.loc = bw / 1000}

    #The knn bandwidth is a proportion of the total prior weight, so compute the total prior weight:
    if (bw.type == 'knn') {
        prior.weights = drop(prior.weights)
        total.weight = sum(prior.weights)
    }
    
    group.id = attr(x, 'assign')
    
#models = list()
    models = foreach(i=1:n, .errorhandling='stop') %dopar% {
#for (i in 1:n) {
        if (!is.null(fit.loc)) {
            dist = drop(D[nrow(coords)+i,1:nrow(coords)])
        } else { dist = drop(D[i,]) }
        loc = coords.fit[i,]

        #If we are seeking the bandwidth via the jacknife, then remove any observations with zero distance.
        if (jacknife==TRUE || jacknife=='anti') {
            indx = which(dist!=0)
        } else {
            indx = 1:nrow(x)
        }

        if (!is.null(bootstrap.index)) {
            indx = indx[bootstrap.index]
        }

        if (jacknife=='anti') {
            indx = c(indx, which(indx==0))
        }
        
        #Use a prespecified distance as the bandwidth?
        if (bw.type == 'dist') {
            bandwidth = bw
            kernel.weights = drop(kernel(dist, bandwidth))

        #Compute the bandwidth that sets the sum of weights around location i equal to bw?
        } else if (bw.type == 'knn') {
            opt = optimize(
                lagr.knn,
                lower=min.dist,
                upper=max.dist,
                maximum=FALSE,
                tol=tol.loc,
                loc=loc,
                coords=coords[indx,],
                kernel=kernel,
                verbose=verbose,
                dist=dist[indx],
                total.weight=total.weight,
                prior.weights=prior.weights[indx],
                target=bw
            )
            bandwidth = opt$minimum
            kernel.weights = drop(kernel(dist, bandwidth))
            
        #Compute the bandwidth so that the sum of the local weighted squared error equals the bw?
        } else if (bw.type == 'nen') {
            opt = optimize(
                lagr.ssr,
                lower=min.dist,
                upper=max.dist, 
                maximum=FALSE,
                tol=tol.loc,
                x=x[indx,],
                y=y[indx],
                group.id=group.id,
                family=family,
                loc=loc,
                coords=coords[indx,],
                dist=dist[indx],
                kernel=kernel,
                target=bw,
                varselect.method=varselect.method,
                oracle=oracle,
                prior.weights=prior.weights[indx],
                verbose=verbose,
                lambda.min.ratio=lambda.min.ratio,
                n.lambda=n.lambda, 
                lagr.convergence.tol=lagr.convergence.tol,
                lagr.max.iter=lagr.max.iter
            )
            bandwidth = opt$minimum
            kernel.weights = drop(kernel(dist, bandwidth))
        }
        
        #If we have specified covariates via an oracle, then use those
        if (!is.null(oracle)) {oracle.loc = oracle[[i]]}
        else {oracle.loc = NULL}

        #Fit the local model
        m = list(tunelist=list('ssr-loc'=list('pearson'=Inf, 'deviance'=Inf), 'df-local'=1), 'sigma2'=0, 'nonzero'=vector(), 'weightsum'=sum(kernel.weights))
        try(m <- lagr.fit.inner(
            x=x[indx,],
            y=y[indx],
            group.id=group.id,
            family=family,
            coords=as.matrix(coords[indx,]),
            loc=loc,
            varselect.method=varselect.method,
            tuning=tuning,
            predict=predict,
            simulation=simulation,
            lambda.min.ratio=lambda.min.ratio,
            n.lambda=n.lambda, 
            lagr.convergence.tol=lagr.convergence.tol,
            lagr.max.iter=lagr.max.iter,
            verbose=verbose,
            kernel.weights=kernel.weights[indx],
            prior.weights=prior.weights[indx],
            oracle=oracle.loc)
        )
        if (verbose) {
            cat(paste("For i=", i, "; location=(", paste(round(loc,3), collapse=","), "); bw=", round(bandwidth,3), "; s=", m[['s']], "; dispersion=", round(tail(m[['dispersion']],1),3), "; nonzero=", paste(m[['nonzero']], collapse=","), "; weightsum=", round(m[['weightsum']],3), ".\n", sep=''))
        }        
        m[['bw']] = bandwidth
        return(m)
#models[[i]] = m
    }
    
    vcr.model[['fits']] = models
    
    #Calculate information criteria:
    fitted = vector()
    df = 0
    n = nrow(x)
    
    #Compute model-average fitted values and degrees of freedom:
    for (x in models) {
        #Compute the model-averaging weights:
        crit = x[['tunelist']][['criterion']]        
        if (varselect.method %in% c("AIC", "AICc", "BIC")) {
            crit.weights = as.numeric(crit==min(crit))
        } else if (varselect.method %in% c("wAIC", "wAICc")) {
            crit.weights = -crit
        }
        
        fitted = c(fitted, sum(x[['tunelist']][['localfit']] * crit.weights) / sum(crit.weights))
        df = df + sum((1+x[['model']][['results']][['df']]) * crit.weights / x[['weightsum']] ) / sum(crit.weights)
    }

    dev.resids = family$dev.resids(y, fitted, prior.weights)
    ll = family$aic(y, n, fitted, prior.weights, sum(dev.resids))

    #Compute the information criteria:
    vcr.model[['AICc']] = ll + 2*df + 2*df*(df+1)/(n-df-1)
    vcr.model[['AIC']] = ll + 2*df
    vcr.model[['GCV']] = ll
    vcr.model[['BIC']] = ll + log(n)*df

    vcr.model[['df']] = df
    
    return(vcr.model)
}
#' Calibrate MSS images to TM images
#'
#' Calibrate MSS images to TM images using linear regression
#' @param msswrs2dir character. MSS WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import ggplot2
#' @import gridExtra
#' @export


msscal_single = function(mss_file, tm_file){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  write_coef = function(mss_file, ref_file, index, coef,r){
    info = data.frame(mss_file = basename(mss_file),
                      ref_file = basename(ref_file),
                      index = index,
                      yint = as.numeric(coef[1]),
                      b1c = as.numeric(coef[2]),
                      b2c = as.numeric(coef[3]),
                      b3c = as.numeric(coef[4]),
                      b4c = as.numeric(coef[5]),
                      r=r)
    
    coefoutfile = file.path(outdir,paste(mssimgid,"_",index,"_cal_coef.csv",sep=""))
    write.csv(info, coefoutfile, row.names=F)
  }
  
  sample_it = function(img, bins, n){
    
    mi = min(img, na.rm=T)
    ma = max(img, na.rm=T)
    
    step = (ma - mi)/bins
    breaks = seq(mi,ma,step)
    
    min_samp = array(n, bins)
    for(i in 1:(length(breaks)-1)){
      these = which(img > breaks[i] & img <= breaks[i+1])
      if(i == 1){samp = sample(these, size=min(min_samp[i],length(these)))} else {
        samp = c(samp, sample(these, size=min(min_samp[i],length(these))))
      } 
    }
    return(samp)
  }
  
  #define the filenames
  mss_sr_file = mss_file
  mss_mask_file = sub("dos_sr.tif", "cloudmask.tif", mss_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #load files as raster
  mss_sr_img = brick(mss_sr_file)
  mss_mask_img = raster(mss_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(mss_sr_img)  = alignExtent(mss_sr_img, ref_tc_img, snap="near")
  extent(mss_mask_img) = alignExtent(mss_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(mss_sr_file,mss_mask_file,ref_tc_file,ref_tca_file,ref_mask_file))
  mss_sr_img = crop(mss_sr_img,int)
  mss_mask_img = crop(mss_mask_img,int)
  ref_tc_img = crop(ref_tc_img,int)
  ref_tca_img = crop(ref_tca_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask
  mss_mask_img = as.matrix(mss_mask_img)
  ref_mask_img = as.matrix(ref_mask_img)
  mask = mss_mask_img*ref_mask_img
  goods = which(mask == 1)
  refpix = as.matrix(ref_tca_img)[goods]
  
  #samp = sample_it(refpix, bins=20, n=1000)
  samp = sample(1:length(goods), 15000)
  samp = goods[samp]
  
  mss_mask_img = ref_mask_img = mask = refpix =  0
  
  b1samp = as.matrix(subset(mss_sr_img, 1))[samp]
  b2samp = as.matrix(subset(mss_sr_img, 2))[samp]
  b3samp = as.matrix(subset(mss_sr_img, 3))[samp]
  b4samp = as.matrix(subset(mss_sr_img, 4))[samp]
  samplen = length(samp)
  
  
  #predict the indices
  dname = dirname(mss_sr_file)
  mssimgid = substr(basename(mss_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", mssimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #TCB
  refsamp = as.matrix(subset(ref_tc_img, 1))[samp]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcb", sampoutfile, samplen)
  bcoef = model[[1]]
  bsamp = model[[2]]
  bplot = model[[3]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  #TCG
  refsamp = as.matrix(subset(ref_tc_img, 2))[samp]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcg", sampoutfile, samplen)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gplot = model[[3]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  refsamp = as.matrix(subset(ref_tc_img, 3))[samp]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcw", sampoutfile, samplen)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wplot = model[[3]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  singlepred = atan(gsamp$singlepred/bsamp$singlepred) * (180/pi) * 100
  refsamp = atan(gsamp$refsamp/bsamp$refsamp) * (180/pi) * 100
  tbl = data.frame(mss_img = rep(basename(mss_sr_file),length(singlepred)),
                   ref_img = rep(basename(ref_tc_file),length(singlepred)),
                   index = rep("tca",length(singlepred)),
                   refsamp,singlepred)
  final = tbl[complete.cases(tbl),]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  write.csv(final, sampoutfile, row.names=F)
  
  
  r = cor(final$refsamp, final$singlepred)
  coef = rlm(final$refsamp ~ final$singlepred)
  g = ggplot(final, aes(singlepred, refsamp)) +
    stat_binhex(bins = 100)+
    scale_fill_gradientn(name = "Count", colours = rainbow(7))+
    xlab(paste(basename(mss_sr_file),"tca")) +
    ylab(paste(basename(ref_tc_file),"tca")) +
    ggtitle(paste("tca linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))) +
    theme(plot.title = element_text(size = 12)) +
    geom_smooth(method="rlm", colour = "black", se = FALSE) + 
    coord_fixed(ratio = 1)+
    theme_bw()  
  pngout = sub("samp.csv", "plot.png",sampoutfile)
  png(pngout,width=700, height=700)
  print(g)
  dev.off()
  
  info = data.frame(mss_file = basename(mss_sr_file), ref_file = basename(ref_tc_file),
                    index = "tca", yint = as.numeric(coef$coefficients[1]),
                    b1c = as.numeric(coef$coefficients[2]), r=r)
  
  coefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  write.csv(info, coefoutfile, row.names=F)
  

  write_coef(mss_sr_file, ref_tc_file, "tcb", bcoef, br)
  write_coef(mss_sr_file, ref_tc_file, "tcg", gcoef, gr)
  write_coef(mss_sr_file, ref_tc_file, "tcw", wcoef, wr)

  
  outfile = file.path(outdir,paste(mssimgid,"_tc_cal_planes.png",sep=""))
  make_tc_planes_comparison(bsamp, gsamp, wsamp, outfile)
  
}
#' GUI for running LandsatLinkr
#'
#' GUI for running LandsatLinkr
#' @export

run_landsatlinkr = function(){
  
  choices = c("Prepare MSS",
              "Prepare TM/ETM+",
              "Calibrate MSS to TM/ETM+",
              "Composite")
  
  selection = select.list(choices, title = "Select a process to run")
  if(selection == "Prepare MSS"){process = seq(1:5)}
  if(selection == "Prepare TM/ETM+"){process = 6}
  if(selection == "Calibrate MSS to TM/ETM+"){process = 7}
  if(selection == "Composite imagery"){process = 8}
  
  
  choices = c("No", "Yes")
  selection = select.list(choices, title = "Process in parallel using 2 cores when possible?")
  if(selection == "No"){cores = 1}
  if(selection == "Yes"){cores = 2}
  
  if(sum(process %in% seq(1,6)) > 0){
    scenedir = choose.dir(caption = "Select an MSS or TM/ETM+ scene directory. ex. 'C:/mss/036032'")
    reso = 60 #set default
    proj = "albers" #set default
    if(sum(process %in% c(1,6)) > 0){
      choices = c("30 meter", "60 meter")
      selection = select.list(choices, title = "Select a pixel resolution to use")
      if(selection == "30 meter"){reso = 30}
      if(selection == "60 meter"){reso = 60}
      
      choices = c("Native NAD83 UTM", "USGS North American Albers")
      selection = select.list(choices, title = "Select a map projection to use")
      if(selection == "Native NAD83 UTM"){proj = "default"}
      if(selection == "USGS North American Albers"){proj = "albers"}
    }
    
    demfile=NULL
    if(all(is.na(match(process,5))) == F){
      demfile = choose.files(caption = "Select a scene corresponding DEM file", multi=F)
    }
    #return(list(scenedir, demfile, proj, reso, process,cores))
    prepare_images(scenedir, demfile, proj=proj, reso=reso, process=process,cores=cores)
  }
  
  ################################
  #msscal and mixel
  if(sum(process %in% c(7,8)) > 0){
    if(sum(process %in% 7) > 0){
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      outdir=NULL
      index=NULL
      runname=NULL  
    }
    
    
    if(sum(process %in% 8) > 0){
      choices = c("Yes", "No")
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-1 scene directory to add?")
        if(answer == "Yes"){msswrs1dir = c(msswrs1dir, choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'"))}
      }
      
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-2 scene directory to add?")
        if(answer == "Yes"){msswrs2dir = c(msswrs2dir, choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'"))}
      }
      
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another TM WRS-2 scene directory to add?")
        if(answer == "Yes"){tmwrs2dir = c(tmwrs2dir, choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'"))}
        
        
        outdir = choose.dir(caption = "Select a directory to write the outputs to. ex. 'C:/composites/wrs2_034032'")
        
        choices = c("Tasseled cap angle",
                    "Tasseled cap brightness",
                    "Tasseled cap greenness",
                    "Tasseled cap wetness")
        selection = select.list(choices, title = "Select an index to create composites for")
        if(selection == "Tasseled cap angle"){index = "tca"}
        if(selection == "Tasseled cap brightness"){index = "tcb"}
        if(selection == "Tasseled cap greenness"){index = "tcg"}
        if(selection == "Tasseled cap wetness"){index = "tcw"}
        
        runname = readline("Provide a unique name for the composite series. ex. project1: ")
        
        choices = c("From file")
        selection = select.list(choices, title = "What area do you want to create composites for?")
        if(selection == "From file"){useareafile = choose.files(caption = "Select a 'usearea' file", multi=F)}
      }
    }
    if(sum((process %in% 7) > 0)){process[1] = 1}
    if(sum((process %in% 8) > 0)){process[process==8] = 2}
    #return(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,cores,process)
    calibrate_and_composite(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=cores, process=process)
  } 
}
#' Decompress, stack, and reproject LPSG MSS images
#'
#' Decompresses, stacks, and optionally reprojects LPGS MSS images recieved from USGS EROS as .tar.gz files
#' @param file character. full path name of the surface reflectance file
#' @param outtype coded integer designating what units are desired in the output image: 1=DN, 2=radiance, 3=surface reflectance
#' @import raster
#' @import gdalUtils
#' @export

# http://earthexplorer.usgs.gov/ Landsat CDR TM and ETM+ images
tmunpackr = function(file, proj="default", reso=60){
  #tcset = "all", "tc", "tca"
  
  #set new directories
  randomstring = paste(sample(c(0:9, letters, LETTERS), 6, replace=TRUE),collapse="")
  tempdir = file.path(dirname(file),randomstring) #temp
  year = substr(basename(file),10,13)
  
  pieces = unlist(strsplit(dirname(file), "/")) #break up the directory and unlist so the pieces can be called by index
  len = length(pieces)-1 #get the ending index for "scene"
  newpieces = paste(pieces[1:len], collapse = "/") #subset the directory pieces so the last piece is the scene
  outdir = file.path(newpieces, "images", year)
  dir.create(tempdir, recursive=T, showWarnings=F)
  dir.create(outdir, recursive=T, showWarnings=F)
  
  #decompress the image and get/set files names
  untar(file, exdir=tempdir) #decompress the file
  files = list.files(tempdir, full.names=T)
  bands = grep("band", files, value=T)
  shadow = grep("cloud_shadow_qa.tif", files, value=T) #0 okay, 255 bad
  cloud = grep("sr_cloud_qa.tif", files, value=T) #0 okay, 255 bad
  snow = grep("sr_snow_qa.tif", files, value=T) #0 okay, 255 bad
  fmask = grep("cfmask.tif", files, value=T) # <= 1 okay background 255
  outbase = substr(basename(file),1,16) 
  tempstack = file.path(tempdir,paste(outbase,"_tempstack.tif",sep=""))
  tempvrt = sub("tempstack.tif", "tempmask.vrt", tempstack)
  tempmask = sub("tempstack", "tempmask", tempstack)
  projstack = sub("tempstack", "projstack", tempstack)
  projmask = sub("tempstack", "projmask", tempstack)
  finalstack = file.path(outdir,paste(outbase,"_ledaps.tif", sep=""))
  finalmask = file.path(outdir,paste(outbase,"_cloudmask.tif", sep=""))
  tcfile = file.path(outdir,paste(outbase,"_tc.tif", sep=""))
  tcafile = file.path(outdir,paste(outbase,"_tca.tif", sep=""))
  outprojfile = file.path(outdir,paste(outbase,"_proj.txt", sep=""))
  
  ref = raster(bands[1]) #set a reference raster for setting values and getting projection
  origproj = projection(ref)
  
  #stack the image bands and write out
  gdalbuildvrt(gdalfile=bands, output.vrt = tempvrt, separate=T) #, tr=c(reso,reso)
  gdal_translate(src_dataset=tempvrt, dst_dataset=tempstack, of = "GTiff", co="INTERLEAVE=BAND")
  
   #s = stack(bands)
   #origproj = projection(s)
   #s = as(s, "SpatialGridDataFrame")       
   #writeGDAL(s, tempstack, drivername = "ENVI", type = "Int16", mvFlag = -9999)
  
  #make a composite cloudmask
  s = as.matrix(raster(shadow))
  c = as.matrix(raster(cloud))
  sn = as.matrix(raster(snow))
  f = as.matrix(raster(fmask))
  
  check = s[1,1] # if is.na(check) == T new else old
  if(is.na(check) == T){s = is.na(s)} else {s = !is.na(s)}
  check = c[1,1] # if is.na(check) == T new else old
  if(is.na(check) == T){c = is.na(c)} else {c = !is.na(c)}
  check = sn[1,1] # if is.na(check) == T new else old
  if(is.na(check) == T){sn = is.na(sn)} else {sn = !is.na(sn)}
  f = f <= 1
  mask = s*c*f*sn
  mask = setValues(ref,mask)
  mask = as(mask, "SpatialGridDataFrame")        #convert the raster to SGHF so it can be written using GDAL (faster than writing it with the raster package)
  writeGDAL(mask, tempmask, drivername = "GTiff", type = "Byte", mvFlag = 255, options="INTERLEAVE=BAND")
  
  s=c=sn=f=mask=0 #clear the memory
  
  #reproject the image #need to add in writing proj file for default
  if(proj == "default"){proj = origproj}
  if(proj == "albers"){proj = "+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs"}
    write(proj, outprojfile)
    gdalwarp(srcfile=tempstack, dstfile=projstack, 
               s_srs=origproj, t_srs=proj, of="GTiff", 
               r="bilinear", srcnodata=-9999, dstnodata=-32768, multi=T, #"near"
               tr=c(reso,reso), co="INTERLEAVE=BAND")
    
    #project the mask
    gdalwarp(srcfile=tempmask, dstfile=projmask, 
             s_srs=origproj, t_srs=proj, of="GTiff", 
             r="mode", srcnodata=255, dstnodata=255, multi=T,
             tr=c(reso,reso), co="INTERLEAVE=BAND")

  

  #trim the na rows and cols
  if(proj != "default"){
    infile = projstack
    inmask = projmask
  } else {
    infile = tempstack
    inmask = tempmask
  } 
  trim_na_rowcol(infile, finalstack, inmask, finalmask)
  
  #tasseled cap
  ref = raster(finalstack, 1)
  b1 = as.matrix(raster(finalstack, 1))
  b2 = as.matrix(raster(finalstack, 2))
  b3 = as.matrix(raster(finalstack, 3))
  b4 = as.matrix(raster(finalstack, 4))
  b5 = as.matrix(raster(finalstack, 5))
  b6 = as.matrix(raster(finalstack, 6))
  
  bcoef = c(0.2043, 0.4158, 0.5524, 0.5741, 0.3124, 0.2303)
  gcoef = c(-0.1603, -0.2819, -0.4934, 0.7940, -0.0002, -0.1446)
  wcoef = c(0.0315, 0.2021, 0.3102, 0.1594,-0.6806, -0.6109)
  
  tcset="all" #hardwire

  bright = (b1*bcoef[1])+(b2*bcoef[2])+(b3*bcoef[3])+(b4*bcoef[4])+(b5*bcoef[5])+(b6*bcoef[6])
  green = (b1*gcoef[1])+(b2*gcoef[2])+(b3*gcoef[3])+(b4*gcoef[4])+(b5*gcoef[5])+(b6*gcoef[6])
  if(tcset == "all" | tcset == "tc"){wet = (b1*wcoef[1])+(b2*wcoef[2])+(b3*wcoef[3])+(b4*wcoef[4])+(b5*wcoef[5])+(b6*wcoef[6])}
  
  b1=b2=b3=b4=b5=b6=0
  
  #calc tc and convert to a raster
  if(tcset == "all" | tcset == "tc"){
    tcb = setValues(ref,bright)
    tcg = setValues(ref,green)
    tcw = setValues(ref,wet)
    tc = stack(tcb,tcg,tcw)
    projection(tc) = set_projection(tcfile)
    tc = as(tc, "SpatialGridDataFrame")
    writeGDAL(tc, tcfile, drivername = "GTiff", type = "Int16", mvFlag = -32768, options="INTERLEAVE=BAND")
  }
  
  if(tcset == "all" | tcset == "tca"){
    #calc tc angle and convert to a raster
    tca = atan(green/bright) * (180/pi) * 100
    tca = setValues(ref,tca)
    projection(tca) = set_projection(tcafile)
    tca = as(tca, "SpatialGridDataFrame")
    writeGDAL(tca, tcafile, drivername = "GTiff", type = "Int16", mvFlag = -32768, options="INTERLEAVE=BAND")
  }
  
  #delete temporary files
  unlink(tempdir, recursive=T, force=T)
}

# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Enkrat prvak", "Dvakrat prvak", "Večkrat prvak")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
veckrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) > 2))
dvakrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) == 2))
enkrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) < 2))
stevilo.naslovov.dirkaca[veckrat.prvak] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[dvakrat.prvak] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[enkrat.prvak] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)



source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Funkcija, ki uvozi podatke iz datoteke dirkalisca2014.csv
uvoziDirkalisca <- function() {
  return(read.table("podatki/dirkalisca2014.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))
  
}

# Zapišimo podatke v razpredelnico dirkališča.
cat("Uvažam podatke o dirkališčih...\n")
dirkalisca <- uvoziDirkalisca()

# 3. faza: Izdelava zemljevida

# Uvozimo funkcijo za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r")

# Uvozimo zemljevid.
cat("Uvažam zemljevid...\n")
svet <- uvozi.zemljevid("http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip",
                          "Svet", "ne_110m_admin_0_countries.shp", mapa = "zemljevid",
                          encoding = "Windows-1250")


t <- table(Stevilo.naslovov.dirkaca$Država)

najvec.zmag <- max(t)
najmanj.zmag <- min(t)

u <- unique(t)
u <- u[order(u)]
barve <- rgb(0, 0, 1, match(t, u)/length(u))
names(barve) <- names(t)

# Narišimo zemljevide v PDF.
cat("Rišem 1. zemljevid...\n")
pdf("slike/Zmage_po_drzavah.pdf", width=10, height=8)

plot(svet, col = barve[as.character(svet$name_long)], border = "grey")
title("Število svetovnih prvakov po državah")
legend("left", legend = u, fill = rgb(0, 0, 1, (1:length(u))/length(u)), bg="white")


# pripravimo koordinate držav
koord.orig <- coordinates(svet[match(names(t), svet$name_long),])
rownames(koord.orig) <- names(t)
# spreminjali bomo koordinate imen
koord.ime <- koord.orig
imena <- names(t)
# pripravimo vektor imen
names(imena) <- names(t)
# pripravimo vektor pozicij
pos <- rep(1, length(t))
names(pos) <- names(t)
# pripravimo vektor odmikov
offset <- rep(0, length(t))
names(offset) <- names(t)
# povemo, katere države bomo pokazali s črto
zamaknjene <- c("Austria", "France", "Italy", "United Kingdom")
offset[zamaknjene] <- 0.5

# priredimo pozicije imen držav
koord.ime["Austria",1] <- koord.ime["Austria",1] + 10 # premik po osi x
koord.ime["France",1] <- koord.ime["France",1] - 7 # premik po osi x
koord.ime["United Kingdom",2] <- koord.ime["United Kingdom",2] + 8 # premik po osi y
koord.ime["Italy",] <- koord.ime["Italy",] + c(6, -8) # premik po obeh oseh

# povemo, kje glede na točko naj bo prikazano ime
pos["Austria"] <- 4 # desno
pos["France"] <- 2 # levo
pos["Italy"] <- 1 # spodaj
pos["United Kingdom"] <- 3 # zgoraj

# priredimo imena
imena["United Kingdom"] <- "UK"

# izpišemo imena
text(koord.ime, labels = imena, col = "black", cex = 0.6, pos = pos, offset = offset)

# narišemo črte
for (drzava in zamaknjene) {
  lines(c(koord.ime[drzava,1], koord.orig[drzava,1]),
        c(koord.ime[drzava,2], koord.orig[drzava,2]))
}

dev.off()
Kernel <- setRefClass("Kernel",
                fields = c("connection_info", "zmqctx", "sockets", "executor"),
                methods= list(

hb_reply = function() {
    data <- receive.socket(sockets$hb, unserialize = FALSE)
    send.socket(sockets$hb, data, serialize = FALSE)
},

#'<brief desc>
#'
#'<full description>
#' @param msg_lst <what param does>
#' @export
sign_msg = function(msg_lst) {
    concat <- unlist(msg_lst)
    return(hmac(connection_info$key, concat, "sha256"))
},
#'<brief desc>
#'
#'<full description>
#' @param parts <what param does>
#' @import rjson
#' @export
wire_to_msg = function(parts) {
    i <- 1
    #print(parts)
    while (any(parts[[i]] != charToRaw("<IDS|MSG>"))) {
        i <- i + 1
    }
    signature <- rawToChar(parts[[i + 1]])
    expected_signature <- sign_msg(parts[(i + 2):(i + 5)])
    stopifnot(identical(signature, expected_signature))
    header <- fromJSON(rawToChar(parts[[i + 2]]))
    parent_header <- fromJSON(rawToChar(parts[[i + 3]]))
    metadata <- fromJSON(rawToChar(parts[[i + 4]]))
    content <- fromJSON(rawToChar(parts[[i + 5]]))
    if (i > 1) {
        identities <- parts[1:(i - 1)]
    } else {
        identities <- NULL
    }
    return(list(header = header, parent_header = parent_header, metadata = metadata, 
        content = content, identities = identities))
},
#'<brief desc>
#'
#'<full description>
#' @param msg <what param does>
#' @export
msg_to_wire = function(msg) {
    #print(msg)
    bodyparts <- list(charToRaw(toJSON(msg$header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$parent_header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$metadata, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$content, auto_unbox=TRUE))
                     )
    signature <- sign_msg(bodyparts)
    return(c(msg$identities, list(charToRaw("<IDS|MSG>")), list(charToRaw(signature)), bodyparts))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @export
new_reply = function(msg_type, parent_msg) {
    header <- list(msg_id = UUIDgenerate(), username = parent_msg$header$username, 
        session = parent_msg$header$session, msg_type = msg_type)
    return(list(header = header, parent_header = parent_msg$header, identities = parent_msg$identities, 
        metadata = namedlist()  # Ensure this is {} in JSON, not []
        ))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @param  socket <what param does>
#' @param  content <what param does>
#' @export
send_response = function(msg_type, parent_msg, socket_name, content) {
    msg <- new_reply(msg_type, parent_msg)
    msg$content <- content
    socket <- sockets[socket_name][[1]]
    send.multipart(socket, msg_to_wire(msg))
},
#'<brief desc>
#'
#'<full description>
#' @param  <what param does>
#' @export
handle_shell = function() {
    parts <- receive.multipart(sockets$shell)
    msg <- wire_to_msg(parts)
    if (msg$header$msg_type == "execute_request") {
        executor$execute(msg)
    } else if (msg$header$msg_type == "kernel_info_request") {
        kernel_info(msg)
    } else if (msg$header$msg_type == "history_request") {
        history(msg)
    } else {
        print(c("Got unhandled msg_type:", msg$header$msg_type))
    }
},

history = function(request) {
  send_response("history_reply", request, 'shell', list(history=list()))
},

kernel_info = function(request) {
  send_response("kernel_info_reply", request, 'shell',
                list(protocol_version=c(4, 0), language="R",
                     language_info=list(name="R", codemirror_mode="r",
                                pygments_lexer="r", mimetype="text/x-r-source",
                                file_extension=".r"
                                )
                    )
                )
},

handle_control = function() {
  parts = receive.multipart(sockets$control)
  msg = wire_to_msg(parts)
  if (msg$header$msg_type == "shutdown_request") {
    shutdown(msg)
  } else {
    print(c("Unhandled control message, msg_type:", msg$header$msg_type))
  }
},

shutdown = function(request) {
  send_response('shutdown_reply', request, 'control',
                list(restart=request$content$restart))
  stop("Shut down by frontend.")
},

initialize = function(connection_file) {
    connection_info <<- fromJSON(connection_file)
    print(connection_info)
    url <- paste(connection_info$transport, "://", connection_info$ip, sep = "")
    url_with_port <- function(port_name) {
        return(paste(url, ":", connection_info[port_name], sep = ""))
    }

    # ZMQ Socket setup
    zmqctx <<- init.context()
    sockets <<- list(
        hb = init.socket(zmqctx, "ZMQ_REP"),
        iopub = init.socket(zmqctx, "ZMQ_PUB"),
        control = init.socket(zmqctx, "ZMQ_ROUTER"),
        stdin = init.socket(zmqctx, "ZMQ_ROUTER"),
        shell = init.socket(zmqctx, "ZMQ_ROUTER")
    )
    bind.socket(sockets$hb, url_with_port("hb_port"))
    bind.socket(sockets$iopub, url_with_port("iopub_port"))
    bind.socket(sockets$control, url_with_port("control_port"))
    bind.socket(sockets$stdin, url_with_port("stdin_port"))
    bind.socket(sockets$shell, url_with_port("shell_port"))

    executor <<- Executor$new(kernel=.self)
},

run = function() {
    while (1) {
        events <- poll.socket(list(sockets$hb, sockets$shell, sockets$control),
                              list("read", "read", "read"), timeout = -1L)
        if (events[[1]]$read) {
            # heartbeat
            hb_reply()
        }
        if (events[[2]]$read) {
            # Shell socket
            handle_shell()
        }

        if (events[[3]]$read) {  # Control socket
            handle_control()
        }
    }
})
)

#'Initialise and run the kernel
#'
#'@param connection_file The path to the IPython connection file, written by the frontend
#'@export 
main <- function(connection_file="") {
    if (connection_file == "") {
        # On Windows, passing the connection file in as a string literal fails,
        # because the \U in C:\Users looks like a unicode escape. So, we have to
        # pass it as a separate command line argument.
        connection_file = commandArgs(T)[1]
    }
    kernel <- Kernel$new(connection_file=connection_file)
    kernel$run()
}

#'Install the kernelspec to tell IPython (>= 3) about IRkernel
#'
#'@param user Install into user directory ~/.ipython or globally?
#'@export
installspec <- function(user=F) {
    srcdir = system.file("kernelspec", package="IRkernel")
    user_flag=ifelse(user, "--user", "")
    cmd = paste("ipython kernelspec install --replace --name ir", user_flag, srcdir, sep=" ")
    system(cmd, wait=TRUE)
}
# 2. faza: Obdelava, uvoz in čiščenje podatkov
source("uvoz/uvoz.r", encoding="UTF-8")
source("slike/grafi.R", encoding="UTF-8")

# 3. faza: Analiza in vizualizacija podatkov
source("vizualizacija/vizualizacija.r", encoding="UTF-8")

# 4. faza: Napredna analiza podatkov
#source("analiza/analiza.r")

cat("Končano.\n")# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Enkrat prvak", "Dvakrat prvak", "Večkrat prvak")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
veckrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) > 2))
dvakrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) == 2))
enkrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) < 2))
stevilo.naslovov.dirkaca[veckrat.prvak] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[dvakrat.prvak] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[enkrat.prvak] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)




source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()

# Funkcija, ki uvozi podatke iz datoteke drzave.csv
uvoziDrzave <- function() {
  return(read.table("podatki/drzave.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))
  
}

# Zapišimo podatke v razpredelnico države.
cat("Uvažam podatke o državah...\n")
drzave <- uvoziDrzave()


# 3. faza: Izdelava zemljevida

# Uvozimo funkcijo za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r")

# Uvozimo zemljevid.
cat("Uvažam zemljevid...\n")
svet <- uvozi.zemljevid("http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip",
                          "Svet", "ne_110m_admin_0_countries.shp", mapa = "zemljevid",
                          encoding = "Windows-1250")

t <- table(Stevilo.naslovov.dirkaca$Država)

najvec.zmag <- max(t)
najmanj.zmag <- min(t)


# Narišimo zemljevid v PDF.
cat("Rišem zemljevid...\n")
pdf("slike/Zmage_po_drzavah.pdf", width=6, height=4)

n = max(t)
u <- unique(t)
u <- u[order(u)]
barve <- rgb(0, 0, 1, match(t, u)/length(u))
plot(svet, col = barve[as.character(svet$name_long)], border = "grey")
title("Število naslovov po državah")
legend("left", legend = u, fill = rgb(0, 0, 1, (1:length(u))/length(u)), bg="white" )

#imena držav
text(coordinates(drzave[c("dolzina", "sirina")]), labels = drzave$drzava, col = "black", cex = 0.3)

dev.off()REBOL [
	Title:   "Red/System compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/utils/profiler.r
profiler/active?: no

do-cache %system/utils/r2-forward.r
do-cache %system/utils/int-to-bin.r
do-cache %system/utils/IEEE-754.r
do-cache %system/utils/virtual-struct.r
do-cache %system/utils/secure-clean-path.r
do-cache %system/linker.r
do-cache %system/emitter.r

system-dialect: make-profilable context [
	verbose:  	  0										;-- logs verbosity level
	job: 		  none									;-- reference the current job object	
	runtime-path: pick [%system/runtime/ %runtime/] encap?
	nl: 		  newline
	
	loader: do bind load-cache %system/loader.r 'self
	
	options-class: context [
		config-name:		none						;-- Preconfigured compilation target ID
		OS:					none						;-- Operating System
		OS-version:			none						;-- OS version
		ABI:				none						;-- optional ABI flags (word! or block!)
		link?:				no							;-- yes = invoke the linker and finalize the job
		debug?:				no							;-- reserved for future use
		build-prefix:		%builds/					;-- prefix to use for output file name (none: no prefix)
		build-basename:		none						;-- base name to use for output file name (none: derive from input name)
		build-suffix:		none						;-- suffix to use for output file name (none: derive from output type)
		format:				none						;-- file format
		type:				'exe						;-- file type ('exe | 'dll | 'lib | 'obj | 'drv)
		target:				'IA-32						;-- CPU target
		cpu-version:		6.0							;-- CPU version (default: Pentium Pro)
		verbosity:			0							;-- logs verbosity level
		sub-system:			'console					;-- 'GUI | 'console
		runtime?:			yes							;-- include Red/System runtime
		use-natives?:		no							;-- force use of native functions instead of C bindings
		debug?:				no							;-- emit debug information into binary
		need-main?:			no							;-- yes => emit a function prolog/epilog around global code
		PIC?:				no							;-- generate Position Independent Code
		base-address:		none						;-- base image memory address
		dynamic-linker: 	none						;-- ELF dynamic linker ("interpreter")
		syscall:			'Linux						;-- syscalls convention: 'Linux | 'BSD
		stack-align-16?:	no							;-- yes => align stack to 16 bytes
		literal-pool?:		no							;-- yes => use pools to store literals, no => store them inlined (default: no)
		unicode?:			no							;-- yes => use Red Unicode API for printing on screen
		red-pass?:			no							;-- yes => Red compiler was invoked
		red-only?:			no							;-- yes => stop compilation at Red/System level and display output
		red-store-bodies?:	yes							;-- no => do not store function! value bodies (body-of will return none)
		red-strict-check?:	yes							;-- no => defers undefined word errors reporting at run-time
		red-tracing?:		yes							;-- no => do not compile tracing code
		red-help?:			no							;-- yes => keep doc-strings from boot.red
		legacy:				none						;-- block of optional OS legacy features flags
	]
	
	compiler: make-profilable context [
		job:		 	 none							;-- shortcut for job object
		pc:			 	 none							;-- source code input cursor
		script:		 	 none							;-- source script file name
		none-type:	 	 [#[none]]						;-- marker for "no value returned"
		last-type:	 	 none-type						;-- type of last value from an expression
		locals: 	 	 none							;-- currently compiled function specification block
		definitions:  	 make block! 100
		enumerations: 	 make hash! 10
		expr-call-stack: make block! 1					;-- simple stack of nested calls for a given expression
		locals-init: 	 []								;-- currently compiler function locals variable init list
		func-name:	 	 none							;-- currently compiled function name
		block-level: 	 0								;-- nesting level of input source block
		catch-level:	 0								;-- nesting level of CATCH body block
		verbose:  	 	 0								;-- logs verbosity level
	
		imports: 	   	 make block! 10					;-- list of imported functions
		exports: 	   	 make block! 10					;-- list of exported symbols
		natives:	   	 make hash!  40					;-- list of functions to compile [name [specs] [body]...]
		ns-path:		 none							;-- namespaces access path
		ns-stack:		 none							;-- namespaces resolution stack
		ns-list:		 make hash!  8					;-- namespaces definition list [name [word type...]...]
		sym-ctx-table:	 make hash!  100				;-- reverse lookup table for contexts
		globals:  	   	 make hash!  40					;-- list of globally defined symbols from scripts
		aliased-types: 	 make hash!  10					;-- list of aliased type definitions
		keywords-list:	 make block! 20
		
		resolve-alias?:  yes							;-- YES: instruct the type resolution function to reduce aliases
		decoration:		 slash							;-- decoration separator for namespaces
		shift-right-sym: to word! ">>>"					;-- workaround REBOL LOAD limitation
		
		debug-lines: reduce [							;-- runtime source line/file information storage
			'records make block!  1000					;-- [address line file] records
			'files	 make hash!   20					;-- filenames table
		]
		
		pos:		none								;-- validation rules cursor for error reporting
		return-def: to-set-word 'return					;-- return: keyword
		fail:		[end skip]							;-- fail rule
		rule: value: v: none							;-- global parsing rules helpers
		
		number!: 	  [byte! integer!]					;-- reserved for internal use only
		bit-set!: 	  [byte! integer! logic!]			;-- reserved for internal use only
		any-float!:	  [float! float32! float64!]		;-- reserved for internal use only
		any-number!:  union number! any-float!			;-- reserved for internal use only
		pointers!:	  [pointer! struct! c-string!] 		;-- reserved for internal use only
		any-pointer!: union pointers! [function!]		;-- reserved for internal use only
		poly!:		  union any-number! pointers!		;-- reserved for internal use only
		any-type!:	  union poly! [logic!]			  	;-- reserved for internal use only
		type-sets:	  [									;-- reserved for internal use only
			number! poly! any-type! any-pointer!
			any-number! bit-set!
		]
		
		comparison-op: [= <> < > <= >=]
		
		functions: to-hash compose [
		;--Name--Arity--Type----Cc--Specs--		   Cc = Calling convention
			+		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			-		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			*		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			/		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			and		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			or		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			xor		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			//		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- modulo
			(to-word "%")		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- remainder (real syntax: %)
			>>		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right signed
			<<		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift left signed
			-**		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right unsigned
			=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			not		[1	inline	- [a [bit-set!] 		   return: [bit-set!]]]
			push	[1	inline	- [a [any-type!]]]
			pop		[0	inline	- [						   return: [integer!]]]
			throw	[1	inline	- [n [integer!]]]
		]
		
		repend functions [shift-right-sym copy functions/-**]
		
		user-functions: tail functions					;-- marker for user functions
		
		action-class: context [action: type: data: none]
		
		struct-syntax: [
			pos: opt [into ['align integer! opt ['big | 'little]]]	;-- struct's attributes
			pos: some [word! into [func-pointer | type-spec]]		;-- struct's members
		]
		
		pointer-syntax: ['integer! | 'byte! | 'float32! | 'float64! | 'float!]
		
		func-pointer: ['function! set value block! (check-specs '- value)]
		
		type-syntax: [
			'logic! | 'integer! | 'byte! | 'int16!		;-- int16! needed for AVR8 backend
			| 'float! | 'float32! | 'float64!
			| 'c-string!
			| 'pointer! into [pointer-syntax]
			| 'struct!  into [struct-syntax]
		]

		type-spec: [
			pos: some type-syntax | pos: set value word! (	;-- multiple types allowed for internal usage		
				unless any [
					all [v: find-aliased/prefix value v <> value find aliased-types v pos/1: v]			;-- rewrite the type to prefix it
					find aliased-types value
					all [v: resolve-ns value v <> value enum-type? v pos/1: v]	;-- rewrite the type to prefix it
					all [enum-type? value pos/1: 'integer!]
				][throw false]							;-- stop parsing if unresolved type			
			)
		]		
		
		keywords: make hash! [
			;&			 [throw-error "reserved for future use"]
			?? 			 [comp-print-debug]
			as			 [comp-as]
			assert		 [comp-assert]
			size? 		 [comp-size?]
			if			 [comp-if]
			either		 [comp-either]
			case		 [comp-case]
			switch		 [comp-switch]
			until		 [comp-until]
			while		 [comp-while]
			any			 [comp-expression-list]
			all			 [comp-expression-list/_all]
			exit		 [comp-exit]
			return		 [comp-exit/value]
			catch		 [comp-catch]
			declare		 [comp-declare]
			null		 [comp-null]
			context		 [comp-context]
			with		 [comp-with]
			comment 	 [comp-comment]
			
			true		 [also true pc: next pc]		  ;-- converts word! to logic!
			false		 [also false pc: next pc]		  ;-- converts word! to logic!
			
			func 		 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			function 	 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			alias 		 [raise-level-error "an alias"]	  ;-- alias declaration not allowed at this level
		]
		
		calling-keywords: [								;-- keywords accepted in expr-call-stack
			?? as assert size? if either case switch until while any all
			return catch
		]
		
		foreach [word action] keywords [append keywords-list word]
		foreach [name spec] functions  [append keywords-list name]
		
		calc-line: has [idx head-end prev p header][
			header: head pc
			idx: (index? pc) - header/1  				;-- calculate real pc position (not counting hidden header)
			prev: 1

			parse header [								;-- search for closest line marker
				skip									;-- skip over header length
				some [
					set p pair! (
						if p/2 = idx [return p/1]		;-- exact value position match
						if p/2 > idx [return prev]		;-- closest value position match 
						prev: p/1
					)
				]
			]
			return p/1									;-- return last marker
		]
		
		store-dbg-lines: has [dbg pos][
			dbg: debug-lines
			unless pos: find dbg/files script [
				pos: tail dbg/files
				append dbg/files script
			]
			repend dbg/records [
				emitter/tail-ptr calc-line index? pos
			]
		]
		
		quit-on-error: does [
			clean-up
			if system/options/args [quit/return 1]
			halt
		]
		
		throw-error: func [err [word! string! block!]][
			print [
				"*** Compilation Error:"
				either word? err [
					join uppercase/part mold err 1 " error"
				][reform err]
				"^/*** in file:" mold script
				either locals [join "^/*** in function: " func-name][""]
			]
			if pc [
				print [
					"*** at line:" calc-line lf
					"*** near:" mold copy/part pc 8
				]
			]
			quit-on-error
		]
		
		throw-warning: func [msg [string! block!] /near][
			print [
				"*** Warning:" 	reform msg
				"^/*** in:" 	mold script
				"^/*** at:" 	mold copy/part any [all [near back pc] pc] 8
			]
		]
		
		raise-level-error: func [kind [string!]][
			pc: back pc
			throw-error reform ["declaring" kind "at this level is not allowed"]
		]
		
		raise-casting-error: does [
			backtrack 'as
			throw-error "multiple type casting not allowed"
		]
		
		;raise-paren-error: does [
		;	pc: back pc
		;	throw-error "parens are only allowed nested in an expression"
		;]
		
		raise-runtime-error: func [error [integer!]][
			emitter/target/emit-get-pc				;-- get current CPU program counter address
			last-type: [integer!]					;-- emit-get-pc returns an integer! (required for next line)
			compiler/comp-call '***-on-quit reduce [error <last>] ;-- raise a runtime error
		]
		
		undecorate: func [value [word! path! set-word! set-path!] /local v pos][
			unless find v: mold value decoration [return value]
			
			while [pos: find v decoration][
				unless find ns-list to path! copy/part v pos [
					pos: next pos
					v: append replace/all copy/part head v pos decoration slash pos
					return load v
				]
				v: at v pos + 1
			]
			value
		]
		
		backtrack: func [value /local res][
			if find [word! path! set-word! set-path!] type?/word value [
				value: undecorate value
			]
			pc: any [res: find/only/reverse pc value pc]
			to logic! res
		]
		
		blockify: func [value][either block? value [value][reduce [value]]]

		literal?: func [value][
			not any [word? value get-word? value path? value block? value value = <last>]
		]
		
		not-initialized?: func [name [word!] /local pos][
			all [
				locals
				pos: find locals /local
				pos: find next pos name
				not find locals-init name
			]
		]
		
		get-alias-id: func [pos [hash!]][
			1000 + divide 1 + index? pos 2
		]
		
		get-type-id: func [value /local type alias][
			with-alias-resolution off [type: resolve-expr-type value]
			
			either alias: find-aliased/position type/1 [		
				get-alias-id alias
			][
				type: resolve-aliased type
				type: switch/default type/1 [
					any-pointer! ['int-ptr!]
					pointer! [pick [int-ptr! byte-ptr!] type/2/1 = 'integer!]
				][type/1]
				select emitter/datatype-ID type
			]
		]
		
		system-reflexion?: func [path [path! set-path!] /local def][
			if path/1 = 'system [
				switch path/2 [
					alias [
						unless path/3 [
							backtrack path
							throw-error "invalid system/alias path access"
						]
						unless def: find-aliased/position path/3 [
							backtrack path
							throw-error ["undefined alias name:" path/3]
						]
						last-type: [integer!]
						return get-alias-id def			;-- special encoding for aliases
					]
					words [
						unless path/3 [
							backtrack path
							throw-error "invalid system/words path access"
						]
						path: remove/part copy path 2
						return either 1 = length? path [
							either set-path? path [to set-word! path/1][path/1]
						][
							path
						]
					]
					; add new special reflective system path here
				]
			]
			none
		]
		
		base-type?: func [value][
			if block? value [value: value/1]
			to logic! find/skip emitter/datatypes value 3
		]
		
		unbox: func [value][
			either object? value [value/data][value]
		]
		
		clear-docstrings: func [spec [block!]][
			remove-each s spec [string? s]
			spec
		]
		
		get-return-type: func [name [word!] /check /local type spec][
			unless all [
				spec: find-functions name
				any [
					type: select spec/2/4 return-def
					check
				]
			][
				backtrack name
				throw-error ["return type missing in function:" name]
			]
			any [type none-type]
		]
		
		set-last-type: func [spec [block!]][
			if spec: select spec return-def [last-type: spec]
		]
		
		local-variable?: func [name [word!]][
			all [locals find locals name]
		]
		
		exists-variable?: func [name [word! set-word!]][
			name: to word! name
			to logic! any [
				local-variable? name
				find globals name
			]
		]
		
		select-globals: func [name [word!] /local pos][
			all [
				pos: find globals name
				pos/2
			]
		]
		
		get-variable-spec: func [name [word!]][
			any [
				all [locals select locals name]
				select-globals name
			]
		]
		
		get-arity: func [spec [block!] /local count][
			count: 0
			parse spec [opt block! any [word! block! (count: count + 1)]]
			count
		]
		
		any-path?: func [value][
			find [path! set-path! lit-path!] type?/word value
		]
		
		any-float?: func [type [block!]][
			find any-float! type/1
		]
		
		any-pointer?: func [type [block!]][
			type: first resolve-aliased type
			
			either find type-sets type [
				not empty? intersect get type any-pointer!
			][
				to logic! find any-pointer! type
			]
		]

		equal-types?: func [type1 [word!] type2 [word!]][
			type1: either find type-sets type1 [get type1][reduce [type1]]
			type2: either find type-sets type2 [get type2][reduce [type2]]
			not empty? intersect type1 type2
		]
		
		equal-types-list?: func [types [block!]][
			forall types [							;-- check if all last expressions are of same type
				unless types/1/1 [return none-type]	;-- test if type is defined
				types/1: resolve-aliased types/1	;-- reduce aliases and pseudo-types
				if all [
					not head? types
					not equal-types? types/-1/1 types/1/1
				][
					return none-type
				]
			]
			first head types						;-- all types equal, return the first one
		]
						
		with-alias-resolution: func [mode [logic!] body [block!] /local saved][
			saved: resolve-alias?
			resolve-alias?: mode	
			do body
			resolve-alias?: saved
		]
		
		find-aliased: func [type [word!] /prefix /position /local ns pos][
			if all [ns: resolve-ns type find aliased-types ns][type: ns]
			if prefix [return ns]
			pos: find aliased-types type
			either position [pos][all [pos pos/2]]
		]
		
		resolve-aliased: func [type [block!] /local name][
			name: type/1
			all [
				type/1								;-- ensure it is not [none]
				not base-type? name
				not find type-sets name
				not all [
					enum-type? name
					type: [integer!]
				]
				not type: find-aliased name
				throw-error ["unknown type:" type]
			]
			type
		]
		
		resolve-type: func [name [word!] /with parent [block! none!] /local type local?][
			type: any [
				all [parent select parent name]
				local?: all [locals select locals name]
				select-globals name
			]
			if all [not type find functions name][
				return reduce ['function! functions/(decorate-fun name)/4]
			]
			if any [
				all [not local?	any [enum-type? name enum-id? name]]
				all [type enum-type? type/1]
			][
				return [integer!]
			]
			unless any [not resolve-alias? none? type base-type? type/1][
				type: find-aliased type/1
			]
			type
		]
		
		resolve-struct-member-type: func [spec [block!] name [word!] /local type][
			unless type: select spec name [
				while [not all [any-path? pc/1 find pc/1 name]][pc: back pc]
				throw-error [
					"invalid struct member" to lit-word! name "in:" mold to path! pc/1
				]
			]
			either resolve-alias? [resolve-aliased type][type]
		]
		
		resolve-path-type: func [path [path! set-path!] /short /parent prev /local type path-error saved][
			path-error: [
				pc: skip pc -2
				throw-error "invalid path value"
			]
			either word? path/1 [
				either parent [
					resolve-struct-member-type prev path/1	;-- just check for correct member name
					with-alias-resolution on [
						type: resolve-type/with path/1 prev
					]
				][
					with-alias-resolution on [
						type: resolve-type path/1
					]
				]
			][
				type: reduce [type?/word path/1]
			]
			
			unless type path-error
			
			either tail? skip path 2 [
				switch/default type/1 [
					c-string! [
						check-path-index path 'string
						[byte!]
					]
					pointer!  [
						check-path-index path 'pointer
						reduce [type/2/1]				;-- return pointed value type
					]
					struct!   [
						unless word? path/2 [
							backtrack path
							throw-error ["invalid struct member" path/2]
						]
						type: resolve-struct-member-type type/2 path/2
						
						if all [
							not short
							not set-path? path
							type/1 = 'function!
						][
							type: select type/2 return-def
						]
						type
					]
				] path-error
			][
				either short [
					resolve-path-type/parent/short next path second type
				][
					resolve-path-type/parent next path second type
				]
			]
		]
		
		get-type: func [value /local type][
			switch/default type?/word value [
				none!	 [none-type]					;-- no type case (func with no return value)
				tag!	 [either value = <last> [last-type][ [logic!] ]]
				logic!	 [[logic!]]
				word! 	 [resolve-type value]
				char!	 [[byte!]]
				integer! [[integer!]]
				decimal! [[float!]]
				string!	 [[c-string!]]
				path!	 [resolve-path-type value]
				object!  [value/type]
				block!	 [
					if value/1 = 'not [return get-type value/2]	;-- special case for NOT multitype native
					
					either 'op = second get-function-spec value/1 [
						either base-type? type: get-return-type value/1 [
							type						;-- unique returned type, stop here
						][
							get-type value/2			;-- recursively search for left operand base type
						]
					][
						get-return-type value/1
					]
				]
				paren!	 [
					switch/default value/1 [
						struct!  [reduce pick [[value/2][value/1 value/2]] word? value/2]
						pointer! [reduce [value/1 value/2]]
					][
						next next reduce ['array! length? value	'pointer! get-type value/1]	;-- hide array size
					]
				]
				get-word! [
					type: resolve-type to word! value
					switch/default type/1 [
						function! [type]
						integer! byte! float! float32! [compose/deep [pointer! [(type/1)]]]
					][
						throw-error ["invalid datatype for a get-word:" mold type]
					]
				]
			][
				throw-error ["not accepted datatype:" type? value]
			]
		]
		
		enum-type?: func [name [word!] /local type][
			all [
				type: find/skip enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				reduce [next type]
			]
		]
		
		enum-id?: func [name [word!] /local pos][
			all [
				pos: find/skip next enumerations name 3
				reduce [pos/-1]
			]
		]

		get-enumerator: func [name [word!] /value /local pos][
			all [
				pos: find/skip next enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				pos/2
			]
		]
		
		set-enumerator: func [
			identifier [word!] name [word! block!] value [integer! word!] /local list v
		][
			store-ns-symbol identifier
			if ns-path [
				add-ns-symbol to set-word! identifier
				identifier: ns-prefix identifier
			]
			
			if word? name [name: reduce [name]]
			forall name [
				store-ns-symbol name/1
				if ns-path [
					add-ns-symbol to set-word! name/1
					name/1: ns-prefix name/1
				]
				check-enum-word name/1
			]
			name: head name
			
			if all [
				word? value
				none? value: get-enumerator resolve-ns value
			][
				throw-error ["cannot resolve literal enum value for:" form name]
			]
			forall name [
				if verbose > 3 [print ["Enum:" identifier "[" name/1 "=" value "]"]]
				repend enumerations [identifier name/1 value]
			]
			value: value + 1
		]

		resolve-expr-type: func [expr /quiet /local type func? spec][
			if block? expr [
				switch type?/word expr/1 [
					set-word! [expr: expr/2]			;-- resolve assigned value type
					set-path! [expr: to path! expr/1]	;-- resolve path type
				]
			]			
			func?: all [
				block? expr word? expr/1
				not find comparison-op expr/1
				spec: find functions expr/1 		 ;-- works for unary & binary functions only!
				spec: spec/2
			]
			type: case [
				object? expr [
					expr/type						 ;-- type casting case
				]
				all [func? find [op inline] spec/2][ ;-- works for unary & binary functions only!
					any [
						all [
							expr/1 <> 'not			;-- @@ issue with 'not return type
							spec: select spec/4 return-def
							base-type? spec/1		;-- determined return type
							spec
						]
						get-type expr/2				;-- recursively search for return type
					]
				]
				all [func? quiet][
					any [
						select spec/4 return-def	;-- workaround error throwing in get-return-value
						none-type
					]
				]
				'else [
					expr: get-type expr
					if resolve-alias? [expr: resolve-aliased expr]
					expr
				]
			]
			type
		]
		
		check-throw: does [
			unless any [locals positive? catch-level][
				backtrack 'throw
				throw-error "THROW used without a wrapping CATCH"
			]
		]
		
		push-call: func [action [word! set-word! set-path!]][
			append/only expr-call-stack action
			if verbose >= 4 [
				new-line/all expr-call-stack off
				?? expr-call-stack
			]
		]
		
		pop-calls: does [clear expr-call-stack]
		
		cast: func [obj [object!] /local value ctype type][
			value: obj/data
			ctype: resolve-aliased obj/type
			type: get-type value

			if all [type = obj/type type/1 <> 'function!][
				throw-warning/near [
					"type casting from" type/1 
					"to" obj/type/1 "is not necessary"
				] 'as
			]
			if any [
				all [type/1 = 'function! not find [function! integer!] ctype/1]
				all [find [float! float64!] ctype/1 not find [float! float64! float32!] type/1]
				all [find [float! float64!] type/1  not find [float! float64! float32!] ctype/1]
				all [type/1 = 'float32! not find [float! float64! integer!] ctype/1]
				all [ctype/1 = 'byte! find [c-string! pointer! struct!] type/1]
				all [
					find [c-string! pointer! struct!] ctype/1
					find [byte! logic!] type/1
				]
			][
				backtrack value
				throw-error [
					"type casting from" type/1
					"to" ctype/1 "is not allowed"
				]
			]	
			unless literal? value [return value]	;-- shield the following literal conversions
			
			switch ctype/1 [
				byte! [
					switch type/1 [
						integer! [value: to char! value and 255]
						logic! 	 [value: pick [#"^(01)" #"^(00)"] value]
					]
				]
				integer! [
					if find [byte! logic!] type/1 [
						value: to integer! value
					]
				]
				logic! [
					switch type/1 [
						byte! 	 [value: value <> null]
						integer! [value: value <> 0]
					]
				]
			]
			value
		]
		
		decorate-function: func [name [word!]][
			to word! join "_local_" form name
		]
		
		find-functions: func [name [word!]][
			if all [
				locals
				type: select locals name
				type/1 = 'function!
			][
				name: decorate-function name
			]
			any [
				find functions name
				find functions resolve-ns name
			]
		]

		get-function-spec: func [name [word!] /local spec][
			all [
				spec: find-functions name
				spec/2
			]
		]

		decorate-fun: func [name [word!] /local type][
			either all [
				locals
				type: select locals name
				block? type
				type/1 = 'function!
			][
				decorate-function name
			][
				name
			]
		]

		remove-func-pointers: has [vars name][
			vars: any [find/tail locals /local []]
			forall vars [
				if all [
					word? vars/1
					block? vars/2
					vars/2/1 = 'function!
				][
					name: decorate-function vars/1
					remove/part find functions name 2
				]
			]
		]
		
		init-local: func [name [word!] expr casted [block! none!] /local pos type][
			append locals-init name					;-- mark as initialized
			pos: find locals name
			unless block? pos/2 [					;-- if not typed, infer type
				insert/only at pos 2 type: any [
					casted
					resolve-expr-type expr
				]
				if verbose > 2 [print ["inferred type" mold type "for variable:" pos/1]]
			]
		]
		
		order-ctx-candidates: func [a b][				;-- order by increasing path size,
			to logic! not all [							;-- and word! before path!.
				path? a
				any [
					word? b
					all [path? b greater? length? a length? b]
				]
			]
		]
		
		store-ns-symbol: func [name [word!] /local pos][
			if ns-path [
				either pos: find/skip sym-ctx-table name 2 [
					either block? pos/2 [
						if find/only pos/2 ns-path [exit]
					][
						if ns-path = pos/2 [exit]
						pos/2: reduce [pos/2]
					]
					append/only pos/2 copy ns-path
					sort/compare pos/2 :order-ctx-candidates
				][
					append sym-ctx-table name
					append/only sym-ctx-table copy ns-path
				]
			]
		]
		
		add-ns-symbol: func [name [set-word!] /local ctx ns][
			name: to word! name
			if find second find/only ns-list ns-path name [exit]
			if ns-stack [
				ctx: tail ns-stack
				until [
					ctx: back ctx
					if all [
						ns: find/only ns-list to path! ctx/1
						find second ns name 
					][exit]
					head? ctx
				]
			]
			append second find/only ns-list ns-path name
		]
		
		add-symbol: func [name [word!] value type][
			unless type [type: get-type value]
			unless 'array! = first head type [type: copy type]
			append globals reduce [name type]
			type
		]
		
		add-function: func [type [word!] spec [block!] cc [word!]][
			repend functions [
				to word! spec/1 reduce [get-arity spec/3 type cc new-line/all spec/3 off]
			]
			if find-attribute spec/3 'callback [
				append last functions 'callback
			]
		]
		
		compare-func-specs: func [
			f-type [block!] c-type [block!] /with fun [word!] cb [get-word!] /local spec pos idx
		][
			if with [
				cb: to word! cb
				if functions/:cb/3 <> functions/:fun/3 [
					throw-error [
						"incompatible calling conventions between"
						fun "and" cb
					]
				]
			]
			if pos: find f-type /local [f-type: head clear copy pos] ;-- remove locals
			if block? f-type/1 [f-type: next f-type]	;-- skip optional attributes block
			if block? c-type/1 [c-type: next c-type]	;-- skip optional attributes block
			idx: 2
			foreach [name type] f-type [
				if type <> c-type/:idx [return false]
				idx: idx + 2
			]
			true
		]
		
		ns-decorate: func [path [path!] /global /set][
			to get pick [set-word! word!] to logic! set mold path	;-- unless / use: replace/all mold path slash decoration
		]

		ns-join: func [ns [path! word!] name [word! path! set-word! set-path!]][
			join ns to word! mold/flat name
		]

		ns-prefix: func [name [word! path! set-word! set-path!] /set][
			if set-word? name [name: to word! name]
			name: ns-join ns-path name
			either set [ns-decorate/set name][ns-decorate name]
		]
		
		check-enum-word: func [name [word!] /local error][
			case [
				all [find keywords name name <> 'context][
					error: ["attempt to redefine a protected keyword:" name]
				]
				find functions name [
					error: ["attempt to redefine existing function name:" name]
				]
				find definitions name [
					error:  ["attempt to redefine existing definition:" name]
				]
				find-aliased name [
					error:  ["attempt to redefine existing alias definition:" name]
				]
				base-type? name [
					error:  ["redeclaration of base type:" name ]
				]
				any [
					exists-variable? name
					get-variable-spec name
				][										;-- it's a variable
					error:  ["redeclaration of variable:" name]
				]
				enum-type? name [
					error:  ["redeclaration of enum identifier:" name ]
				]
				enum-id? name [
					error:  ["redeclaration of enumerator:" name ]
				]
			]
			if error [throw-error error]
		]
		
		check-keywords: func [name [word!]][
			if find keywords name [
				throw-error ["attempt to redefine a protected keyword:" name]
			]
		]
		
		check-path-index: func [path [path! set-path!] type [word!] /local ending enum-value][
			ending: path/2
			case [
				all [type = 'pointer ending = 'value][]	;-- pass thru case
				word? ending [
					either all [
						not local-variable? ending
						enum-value: get-enumerator ending
					][
						path/2: ending: enum-value
					][
						unless any [
							local-variable? ending
							find globals ending: resolve-ns ending
							get-enumerator ending
						][
							backtrack path
							throw-error ["undefined" type "index variable"]
						]
						if 'integer! <> first resolve-type ending [
							backtrack path
							throw-error [
								"attempt to use" type
								"indexing with a non-integer! variable"
							]
						]
					]
				]
				not integer? ending [
					backtrack path
					throw-error [
						"attempt to use" type
						"indexing with a non-integer! value"
					]
				]
			]
		]
		
		check-func-name: func [name [word!] /only][
			if find functions name [
				pc: back pc
				throw-error ["attempt to redefine existing function name:" name]
			]
			if any [enum-type? name	enum-id? name][
				pc: back pc
				throw-error ["attempt to redefine existing enumerator:" name]
			]
			if all [not only find any [locals globals] name][
				pc: back pc
				throw-error ["a variable is already using the same name:" name]
			]
		]
		
		check-duplicates: func [
			name [word!] args [block! none!] locs [block! none!]
			/local dups
		][
			if args [remove-each item args: copy args [not word? item]]
			if locs [remove-each item locs: copy locs [not word? item]]
			
			if any [
				all [args (length? unique args) <> length? args]
				all [locs (length? unique locs) <> length? locs]
				all [args locs not empty? dups: intersect args locs]
			][
				throw-error [
					"duplicate variable definition in function" name
					either dups [reform ["for:" mold/only new-line/all dups no]][""]
				]
			]
		]
		
		check-specs: func [
			name specs /extend
			/local type type-def spec-type attribs value args locs cconv pos
		][
			unless block? specs [
				throw-error "function definition requires a specification block"
			]
			cconv: ['cdecl | 'stdcall]
			attribs: [
				[cconv ['variadic | 'typed | 'custom]]
				| [['variadic | 'typed | 'custom] cconv]
				| 'catch | 'infix | 'variadic | 'typed | 'custom | 'callback | cconv
			]
			type-def: pick [[func-pointer | type-spec] [type-spec]] to logic! extend

			unless catch [
				parse specs [
					opt [								;-- function's attribute and main doc-string
						string! opt [into attribs]		;-- can be specified in any order
						| into attribs opt string!
					]
					pos: copy args any [pos: word! into type-def opt string!]	;-- arguments definition
					pos: opt [							;-- return type definition				
						set value set-word! (					
							rule: pick reduce [[into type-spec] fail] value = return-def
						) rule
						opt string!
					]
					pos: opt [/local copy locs some [pos: word! opt [into type-spec]]] ;-- local variables definition
				]
			][
				throw-error rejoin ["invalid definition for function " name ": " mold pos]
			]
			if block? args [
				clear-docstrings args
				foreach [name type] args [
					if enum-id? name [
						throw-warning ["function's argument redeclares enumeration:" name]
					]
				]
			]
			check-duplicates name args locs
		]
		
		check-conditional: func [name [word!] expr][
			if last-type/1 <> 'logic! [check-expected-type/key name expr [logic!]]
		]
		
		check-expected-type: func [name [word!] expr expected [block!] /ret /key /local type alias][
			unless any [not none? expr key][return none]   ;-- expr == none for special keywords
			if all [
				not all [object? expr expr/action = 'null] ;-- avoid null type resolution here
				not none? expr							;-- expr can be false, so explicit check for none is required
				first type: resolve-expr-type expr		;-- first => deep check that it's not [none]
			][											;-- check if a type is returned or none
				type: resolve-aliased type
				if alias: find-aliased expected/1 [expected: alias]
			]
			if all [
				ret
				block? expr
				any [set-word? expr/1 set-path? expr/1]
			][
				type: none
			]
			unless any [
				all [
					object? expr
					expr/action = 'null
					type: either expected/1 = 'any-type! [expr/type][expected]	;-- morph null type to expected
					any-pointer? expected
				]
				all [
					type
					any [
						find type-sets expected/1
						find type-sets type/1
					]
					equal-types? type/1 expected/1		;-- internal polymorphic case
				]
				all [
					type
					type/1 = 'function!
					any [
						find [any-type! any-pointer!] expected/1
						all [
							expected/1 = 'function!
							compare-func-specs/with type/2 expected/2 name expr	 ;-- callback case
						]
					]
				]
				expected = type 						;-- normal single-type case
				all [
					type
					type/1 = 'integer!
					enum-type? expected/1				;-- TODO: add also a value check for enums
				]
			][
				if expected = type [type: 'null]		;-- make null error msg explicit
				any [
					backtrack any [all [block? expr expr/1] expr]
					backtrack name
				]
				throw-error [
					reform case [
						ret   [["wrong return type in function:" name]]
						key   [[
							uppercase form name "requires a conditional expression"
							either find [while until] name ["as last expression"][""]
						]]
						'else [["argument type mismatch on calling:" name]]
					]
					"^/*** expected:" join mold expected #","
					"found:" mold new-line/all any [type [none]] no
				]
			]
			type
		]
		
		check-arguments-type: func [name args /local entry spec list type][
			if find [set-word! set-path!] type?/word name [exit]
			
			entry: find functions name
			if all [
				not empty? spec: entry/2/4 
				block? spec/1
			][
				spec: next spec							;-- jump over attributes block
			]
			list: clear []
			forall args [
				either all [decimal? args/1 spec/2/1 = 'float32!][
					args/1:	make action-class [			;-- inject type casting to float32!
						action: 'type-cast
						type: [float32!]
						data: args/1					;-- literal float!
					]
					append/only list spec/2				;-- pass-thru for float! values used as float32! arguments
				][
					append/only list check-expected-type name args/1 spec/2
				]
				spec: skip spec	2
			]
			if all [
				any [
					find emitter/target/comparison-op name
					find emitter/target/bitwise-op name
				]
				not equal-types? list/1/1 list/2/1		;-- allow implicit casting for math ops only
			][
				backtrack name
				throw-error [
					"left and right argument must be of same type for:" name
					"^/*** left:" join list/1/1 #"," "right:" list/2/1
				]
			]
			if find emitter/target/math-op name	[
				case [
					any [
						all [list/1/1 = 'byte! any-pointer? list/2]
						all [list/2/1 = 'byte! any-pointer? list/1]
					][
						backtrack name
						throw-error [
							"arguments must be of same size for:" name
							"^/*** left:" join list/1/1 #"," "right:" list/2/1
						]
					]
					any [string? unbox args/1 string? unbox args/2][
						backtrack name
						throw-error "a literal string cannot be used with a math operator"
					]
				]
			]
		]
		
		check-variable-arity?: func [spec [block!] /local attribs][
			all [
				attribs: get-attributes spec
				any [
					all [find attribs 'variadic 'variadic]
					all [find attribs 'typed 'typed]
					all [find attribs 'custom 'custom]
				]
			]
		]
		
		check-body: func [body][
			case/all [
				not block? :body [throw-error "expected a block of code"]
				empty? body  	 [throw-error "expected a non-empty block of code"]
			]
		]
		
		fetch-into: func [								;-- compile sub-block
			code [block! paren!] body [block!] /root
			/local save-pc level
		][
			if root [
				level: block-level						;-- save block level from parent context
				clear expr-call-stack
			]
			save-pc: pc
			pc: code
			do body
			if root [block-level: level]
			next pc: save-pc
		]
		
		get-attributes: func [spec [block!]][
			any [
				all [block? spec/1 spec/1]
				all [string? spec/1 block? spec/2 spec/2]
			]
		]
		
		find-attribute: func [spec [block!] name [word!]][
			either list: get-attributes spec [
				to logic! find list name
			][
				false
			]
		]
		
		get-cconv: func [specs [block!]][
			pick [cdecl stdcall] to logic! all [
				not empty? specs
				find-attribute specs 'cdecl
			]
		]
		
		fetch-func: func [name /local specs type cc attribs][
			name: to word! name
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			if ns-path [name: ns-prefix name]
			check-func-name name
			check-specs name specs: pc/2
			specs: copy specs
			clear-docstrings specs
			
			type: 'native
			cc:   'stdcall								;-- default calling convention
			
			if all [
				not empty? specs
				attribs: get-attributes specs
			][
				case [
					find attribs 'infix [
						if 2 <> get-arity specs [
							throw-error [
								"infix function requires 2 arguments, found"
								get-arity specs "for" name
							]
						]
						type: 'infix
					]
					find attribs 'cdecl   [cc: 'cdecl]
					find attribs 'stdcall [cc: 'stdcall]	;-- get ready when fastcall will be the default cc
				]
			]
			add-function type reduce [name none specs] cc
			emitter/add-native name
			repend natives [
				name specs pc/3 script
				all [ns-path copy ns-path]
				all [ns-stack copy/deep ns-stack]		;@@ /deep doesn't work on paths
			]
			pc: skip pc 3
		]
		
		reduce-logic-tests: func [expr /local test value][
			test: [logic? expr/2 logic? expr/3]
			
			if all [
				block? expr
				find [= <>] expr/1
				any test
			][
				expr: either all test [
					do expr								;-- let REBOL reduce the expression
				][
					expr: copy expr
					if any [
						all [expr/1 = '= not all [expr/2 expr/3]]
						all [expr/1 = first [<>] any [expr/2 = true expr/3 = true]]
					][
						insert expr 'not
					]
					remove-each v expr [any [find [= <>] v logic? v]]
					if any [
						all [
							word? expr/1
							any [
								get-variable-spec expr/1
								enum-id? expr/1
							]
						]
						paren? expr/1
						block? expr/1
						object? expr/1
					][
						expr: expr/1					;-- remove outer brackets if variable
					]
					expr
				]
			]
			expr
		]
		
		process-export: has [defs cc ns func? spec][
			if word? pc/2 [
				unless find [stdcall cdecl] cc: pc/2 [
					throw-error ["invalid calling convention specifier:" cc]
				]
				pc: next pc
			]
			foreach name pc/2 [
				func?: no
				unless any [word? name path? name][
					throw-error ["invalid exported symbol:" mold name]
				]
				if path? name [name: resolve-ns-path name]
				unless any [
					find globals name
					func?: find-functions name
				][
					throw-error ["undefined exported symbol:" mold name]
				]
				append exports name
				
				if func? [
					spec: select functions name
					spec/3: any [cc 'cdecl]
					unless spec/5 = 'callback [append spec 'callback]
				]
			]
		]
		
		process-import: func [defs [block!] /local lib list cc name specs spec id reloc pos][
			unless block? defs [throw-error "#import expects a block! as argument"]
			
			unless parse defs [
				some [
					pos: set lib string! (
						unless list: select imports lib [
							repend imports [lib list: make block! 10]
						]
					)
					pos: set cc ['cdecl | 'stdcall]		;-- calling convention	
					pos: into [
						some [
							specs:						;-- new function mapping marker
							pos: set name set-word! (
								name: to word! name
								store-ns-symbol name
								if ns-path [
									add-ns-symbol to set-word! name
									name: ns-prefix name
								]
								check-func-name name
							)
							pos: set id   string!   (repend list [id reloc: make block! 1])
							pos: set spec block!    (
								check-specs/extend name spec
								clear-docstrings spec
								specs: copy specs
								specs/1: name
								add-function 'import specs cc
								emitter/import-function name reloc
							)
						]
					]
				]
			][
				throw-error ["invalid import specification at:" pos]
			]		
		]
		
		process-syscall: func [defs [block!] /local name id spec pos][
			unless block? defs [throw-error "#syscall expects a block! as argument"]
			unless parse defs [
				some [
					pos: set name set-word! (check-func-name name: to word! name)
					pos: set id   integer!
					pos: set spec block!    (
						check-specs/extend name spec
						spec: copy spec
						clear-docstrings spec
						add-function 'syscall reduce [name none spec] 'syscall
						append last functions id		;-- extend definition with syscode
					)
				]
			][
				throw-error ["invalid syscall specification at:" pos]
			]
		]
		
		process-enum: func [name value /local enum-value enum-names][
			unless word? name [throw-error "enumeration expected a word as name"]
			
			either block? value [
				check-enum-word name 					;-- first checking enumeration identifier possible conflicts
				parse value [
					(enum-value: 0)
					any [
						[
							copy enum-names word!
							| (enum-names: make block! 10) some [
								set enum-name set-word!
								(append enum-names to word! enum-name)
							]	set enum-value [integer! | word!]
						] 
						(enum-value: set-enumerator name enum-names enum-value)
						| set enum-name 1 skip (
							throw-error ["invalid enumeration:" to word! enum-name]
						)
					]
				]
			][
				throw-error ["invalid enumeration (block required!):" mold value]
			]
		]
		
		process-call: func [code [block!] /local mark][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #call directive
				return none
			]
			mark: tail red/output
			red/process-call-directive code/2 yes
			remove/part pc 2
			insert pc mark
			clear mark
			none										;-- do not return an expression to compile
		]
		
		comp-chunked: func [body [block!]][
			emitter/chunks/start
			do body
			emitter/chunks/stop
		]

		comp-directive: has [body][
			switch/default pc/1 [
				#import  [process-import  pc/2  pc: skip pc 2]
				#export  [process-export  pc/2  pc: skip pc 2]
				#syscall [process-syscall pc/2	pc: skip pc 2]
				#call	 [process-call	  pc]
				#enum	 [process-enum pc/2 pc/3 pc: skip pc 3]
				#verbose [set-verbose-level pc/2 pc: skip pc 2]
				#script	 [								;-- internal compiler directive
					unless pc/2 = 'in-memory [
						compiler/script: secure-clean-path pc/2	;-- set the origin of following code
					]
					pc: skip pc 2
				]
			][
				throw-error ["unknown directive" pc/1]
			]
		]
		
		comp-print-debug: has [out][
			unless word? name: pc/2 [
				throw-error "?? needs a word as argument"
			]
			out: next next compose/deep [
				2 (to pair! reduce [calc-line 1])		;-- hidden line offset header
				print-line [
					2 (to pair! reduce [calc-line 1])	;-- hidden line offset header
					(join name ": ") (name)
				]
			]
			out/2: next next out/2
			change/part pc out 2
			none
		]
		
		comp-comment: does [
			pc: next pc
			either block? pc/1 [pc: next pc][fetch-expression]
			none
		]
		
		comp-with: has [ns list with-ns words res ctx][
			ns: pc/2
			unless all [any [word? ns block? ns] block? pc/3][
				throw-error "WITH invalid argument"
			]
			unless block? ns [ns: reduce [ns]]
			
			forall ns [
				ns/1: either path? ctx: resolve-ns/path ns/1 [ctx][to path! ctx]
				unless find/only ns-list ns/1 [throw-error ["undefined context" ns/1]]
			]
			with-ns: unique copy ns
			
			list: clear []
			foreach ns with-ns [
				either empty? res: intersect list words: to block! second find/only ns-list ns [
					append list words
				][
					throw-warning rejoin [
						"contexts are using identical word"
						pick ["s: " ": "] 1 < length? res
						res
					]
				]
			]

			list: copy with-ns
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack list
			
			fetch-into/root pc/3 [comp-dialect]
			
			pc: skip pc 3
			clear skip tail ns-stack negate length? list
			if empty? ns-stack [ns-stack: none]
			
			none
		]
		
		comp-context: has [name level][
			unless block? pc/2 [throw-error "context specification block is missing"]
			unless set-word? pc/-1 [throw-error "context's name setting is missing"]
			unless zero? block-level [
				pc: back pc
				throw-error "context has to be declared at root level"
			]
			
			check-keywords name: to word! pc/-1
			if any [										;@@ factorize this out
				all [locals find locals name]
				find globals name
				find functions name
				find aliased-types name
				find definitions name
				find enumerations name
			][
				pc: back pc
				throw-error "context name is already taken"
			]
			pc: next pc
			
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack to word! mold/flat name
			
			either ns-path [
				append ns-path to word! mold/flat name
			][
				ns-path: to lit-path! mold/flat name		;-- workaround newline flag remanence issue
			]
			either find/only ns-list ns-path [
				throw-error ["context" name "already defined"]
			][
				repend ns-list [copy ns-path make hash! 32]
			]

			fetch-into/root pc/1 [comp-dialect]
			
			remove back tail ns-path
			if empty? ns-path [ns-path: none]
			remove back tail ns-stack
			if empty? ns-stack [ns-stack: none]
			
			pc: next pc
			none
		]
		
		comp-declare: has [rule value pos offset ns][
			unless find [set-word! set-path!] type?/word pc/-1 [
				throw-error "assignment expected before literal declaration"
			]
			value: to paren! reduce either find [pointer! struct!] pc/2 [
				rule: get pick [struct-syntax pointer-syntax] pc/2 = 'struct!
				unless catch [parse pos: pc/3 rule][
					throw-error ["invalid literal syntax:" mold pos]
				]
				if all [
					pc/2 = 'struct!
					(length? pc/3) <> (length? unique/skip pc/3 2)
				][
					throw-error ["duplicate member name in struct:" mold pc/3]
				]
				if pc/3/1 = 'float64! [pc/3/1: 'float!]
				offset: 3
				[pc/2 pc/3]
			][
				unless all [word? pc/2 resolve-aliased reduce [pc/2]][
					throw-error ["declaring literal for type" pc/2 "not supported"]
				]
				value: pc/2
				if all [ns-path ns: find-aliased/prefix value][value: ns]
				offset: 2
				['struct! value]
			]
			pc: skip pc offset
			value
		]
		
		comp-null: does [
			pc: next pc
			make action-class [action: 'null type: [any-pointer!] data: 0]
		]
		
		comp-as: has [ctype ptr? expr type][
			ctype: pc/2
			if ptr?: find [pointer! struct! function!] ctype [ctype: reduce [pc/2 pc/3]]
			
			unless any [
				parse blockify ctype [func-pointer | type-syntax]
				find-aliased ctype
			][
				throw-error ["invalid target type casting:" ctype]
			]
			pc: skip pc pick [3 2] to logic! ptr?
			expr: fetch-expression

			if all [
				block? ctype
				ctype/1 = 'function!
				type: get-type expr
				type/1 = 'function!
			][
				unless compare-func-specs ctype/2 copy type/2 [
					throw-error "invalid functions casting: specifications not matching"
				]
			]
			if all [object? expr expr/action = 'null][
				pc: back pc
				throw-error "type casting on null value is not allowed"
			]
			make action-class [
				action: 'type-cast
				type: blockify ctype
				data: expr
			]
		]
		
		comp-assert: has [expr line][
			either job/debug? [
				line: calc-line
				pc: next pc
				expr: fetch-expression/final
				check-conditional 'assert expr			;-- verify conditional expression
				expr: process-logic-encoding expr yes

				insert/only pc next next compose [
					2 (to pair! reduce [line 1])			;-- hidden line offset header
					***-on-quit 98 as integer! system/pc
				]
				set [unused chunk] comp-block-chunked		;-- compile TRUE block
				emitter/set-signed-state expr				;-- properly set signed/unsigned state
				emitter/branch/over/on chunk reduce [expr/1] ;-- branch over if expr is true
				emitter/merge chunk
				last-type: none-type
				<last>
			][
				pc: next pc
				fetch-expression							;-- consume next expression
				none
			]
		]
		
		comp-alias: has [name pos][
			unless set-word? pc/-1 [
				throw-error "assignment expected for ALIAS"
			]
			unless find [struct! function!] pc/2 [
				throw-error "ALIAS only allowed for struct! and function!"
			]
			name: to word! pc/-1
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			all [
				not base-type? name
				ns-path
				name: ns-prefix name
			]
			if find aliased-types name [
				pc: back pc
				throw-error reform [
					"alias name already defined as:"
					mold aliased-types/:name
				]
			]
			if base-type? name [
				pc: back pc
				throw-error "a base type name cannot be defined as an alias name"
			]
			repend aliased-types [name reduce [pc/2 pc/3]]
			switch pc/2 [
				struct! [
					unless catch [parse pos: pc/3 struct-syntax][
						throw-error ["invalid struct syntax:" mold pos]
					]
				]
				function! [check-specs 'pointer pc/3]
			]
			pc: skip pc 3
			none
		]
		
		comp-size?: has [type expr][
			pc: next pc
			unless all [
				word? expr: pc/1
				type: any [
					all [base-type? expr expr]
					all [enum-type? expr [integer!]]
					find-aliased expr
				]
				pc: next pc
			][
				expr: fetch-expression/final	
				type: resolve-expr-type expr
			]
			emitter/get-size type expr
		]
		
		comp-exit: func [/value /local expr type ret][
			unless locals [
				throw-error [pc/1 "is not allowed outside of a function"]
			]
			pc: next pc
			ret: select locals return-def
			
			either value [				
				unless ret [							;-- check if return: declared
					throw-error [
						"RETURN keyword used without return: declaration in"
						func-name
					]
				]
				expr: fetch-expression/final/keep		;-- compile expression to return
				type: check-expected-type/ret func-name expr ret
				ret: either type [last-type: type <last>][none]
			][
				if ret [throw-error "EXIT keyword is not compatible with declaring a return value"]
			]
			emitter/target/emit-exit
			ret
		]
		
		comp-catch: has [offset][
			pc: next pc
			fetch-expression/keep/final
			if any [not last-type last-type <> [integer!]][
				backtrack 'catch
				throw-error "CATCH expects a threshold value of type integer!"
			]
			unless block? pc/1 [
				backtrack 'catch
				throw-error "CATCH requires a body block as 2nd argument"
			]
			
			catch-level: catch-level + 1
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			catch-level: catch-level - 1
			
			offset: emitter/target/emit-open-catch length? chunk/1
			foreach ptr chunk/2 [ptr/1: ptr/1 + offset]	;-- account for (catch-frame + push) opcodes
			emitter/merge chunk
			emitter/target/emit-close-catch
			last-type: none-type
			none
		]

		comp-block-chunked: func [/only /test name [word!] /local expr][
			emitter/chunks/start
			expr: either only [
				fetch-expression/final					;-- returns first expression
			][
				comp-block/final						;-- returns last expression
			]
			if test [
				check-conditional name expr				;-- verify conditional expression
				expr: process-logic-encoding expr no
			]
			reduce [
				expr 
				emitter/chunks/stop						;-- returns a chunk block!
			]
		]
		
		process-logic-encoding: func [expr invert? [logic!]][	;-- preprocess logic values
			case [
				logic? expr [ [#[true]] ]
				find [word! path!] type?/word expr  [
					emitter/target/emit-integer-operation '= [<last> 0]
					reduce [not invert?]
				]
				object? expr [
					expr: cast expr
					unless find [word! path!] type?/word any [
						all [block? expr expr/1] expr 
					][
						emitter/target/emit-integer-operation '= [<last> 0]
					]
					process-logic-encoding expr invert?
				]
				block? expr [
					case [
						find comparison-op expr/1 [expr]
						'else [process-logic-encoding expr/1 invert?]
					]
				]
				tag? expr [
					either last-type/1 = 'logic! [
						emitter/target/emit-integer-operation '= [<last> 0]
						reduce [not invert?]
					][expr] 
				]
				'else [expr]
			]
		]
		
		comp-if: has [expr unused chunk][		
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'if expr					;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
	
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/on chunk expr/1			;-- insert IF branching			
			emitter/merge chunk
			last-type: none-type
			<last>
		]
		
		comp-either: has [expr e-true e-false c-true c-false offset t-true t-false ret][
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'either expr				;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
			check-body pc/2								;-- check FALSE block
			
			set [e-true c-true]   comp-block-chunked	;-- compile TRUE block
			set [e-false c-false] comp-block-chunked	;-- compile FALSE block

			t-true:  resolve-expr-type/quiet e-true
			t-false: resolve-expr-type/quiet e-false

			last-type: either all [
				t-true/1 t-false/1
				t-true:  resolve-aliased t-true			;-- alias resolution is safe here
				t-false: resolve-aliased t-false
				equal-types? t-true/1 t-false/1
			][t-true][none-type]						;-- allow nesting if both blocks return same type

			if any [
				all [
					locals								;-- if in function body
					tail? pc							;-- and if at tail of body
					ret: select locals return-def		;-- and if function returns something
					ret/1 = 'logic!						;-- and if it returns a logic! value
				]
				all [
					not empty? expr-call-stack
					last-type/1 = 'logic!				;-- and if EITHER returns a logic! too
				]
			][
				if block? e-true  [emitter/logic-to-integer/with e-true  c-true]
				if block? e-false [emitter/logic-to-integer/with e-false c-false]
			]
		
			offset: emitter/branch/over c-false
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/adjust/on c-true negate offset expr/1	;-- skip over JMP-exit
			emitter/merge emitter/chunks/join c-true c-false
			<last>
		]
		
		comp-case: has [cases list test body op bodies offset types][
			pc: next pc
			cases: pc/1
			list:  make block! 8
			types: make block! 8
			
			until [										;-- collect and pre-compile all cases
				append expr-call-stack #test			;-- marker for disabling expression post-processing
				fetch-into cases [						;-- compile case test
					append/only list comp-block-chunked/only/test 'case
					cases: pc							;-- set cursor after the expression
				]
				clear find expr-call-stack #test
				
				append expr-call-stack #body			;-- marker for enabling expression post-processing
				fetch-into cases [						;-- compile case body
					append/only list body: comp-block-chunked
					append/only types resolve-expr-type/quiet body/1
				]
				clear find expr-call-stack #body
				tail? cases: next cases
			]
			
			bodies: comp-chunked [raise-runtime-error 100] ;-- raise a runtime error if unmatched value
			
			list: tail list								;-- point to last case test
			until [										;-- left join all cases in reverse order			
				list: skip list -2
				set [test body] list					;-- retrieve case-test and case-body chunks

				emitter/set-signed-state test/1			;-- properly set signed/unsigned state
				offset: negate emitter/branch/over bodies		;-- insert case exit branching
				emitter/branch/over/on/adjust body/2 test/1/1 offset	;-- insert case test branching
				
				body: emitter/chunks/join test/2 body/2	;-- join case test with case body
				bodies: emitter/chunks/join body bodies	;-- left join case with other cases
				head? list		
			]	
			emitter/merge bodies						;-- commit all to main code buffer
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-switch: has [expr save-type spec value values body bodies list types default pos][
			pc: next pc
			expr: fetch-expression/keep/final			;-- compile argument
			if any [none? expr last-type = none-type][
				throw-error "SWITCH argument has no return value"
			]
			save-type: last-type			
			check-body spec: pc/1
			foreach w [values list types][set w make block! 8]
			forall spec [								;-- resolve possible enumeration symbols
				if all [word? spec/1 spec/1 <> 'default][
					check-enum-symbol spec
				]
			]
			
			;-- check syntax and store parts in different lists
			unless parse spec [
				some [
					pos: copy value some [integer! | char!] 
					(repend values [value none])		;-- [value body-offset ...]
					pos: block! (
						fetch-into pos [				;-- compile action body
							body: comp-block-chunked
							append/only list body/2		
							append/only types resolve-expr-type/quiet body/1
						]
					)
				]
				opt [
					'default pos: block! (
						fetch-into pos [				;-- compile default body
							default: comp-block-chunked
							append/only types resolve-expr-type/quiet default/1
						]
					)
				]
			][
				throw-error ["wrong syntax in SWITCH block at:" copy/part pos 4]
			]

			;-- assemble all actions together, with exit at end for each one
			bodies: emitter/chunks/empty
			list: tail list								;-- point to last action
			until [										;-- left join all actions in reverse order		
				body: first list: back list
				unless empty? bodies/1 [
					emitter/branch/over bodies			;-- insert case exit branching
				]
				bodies: emitter/chunks/join body bodies	;-- left join action with other actions		
				change at values 2 * index? list length? bodies/1
				head? list		
			]
			
			;-- insert default clause or jump to runtime error
			either default [
				emitter/branch/over bodies          	;-- insert default exit branching
				bodies: emitter/chunks/join default/2 bodies ;-- insert default action
			][
				body: comp-chunked [raise-runtime-error 101] ;-- raise a runtime error if unmatched value
				bodies: emitter/chunks/join body bodies
			]

			;-- construct tests + branching and insert them at head
			last-type: save-type
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			values: tail values
			until [
				values: skip values -2
				foreach v values/1 [					;-- process multiple values per action
					body: comp-chunked [
						emitter/target/emit-integer-operation '= reduce [<last> v]
					]
					emitter/branch/over/on/adjust bodies [=] values/2	;-- insert action branching			
					bodies: emitter/chunks/join body bodies
				]
				head? values
			]
			emitter/merge bodies						;-- commit all to main code buffer	
			
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-until: has [expr chunk][
			pc: next pc
			check-body pc/1
			set [expr chunk] comp-block-chunked/test 'until
			emitter/branch/back/on chunk expr/1	
			emitter/merge chunk	
			last-type: none-type
			<last>
		]
		
		comp-while: has [expr unused cond body offset bodies][
			pc: next pc
			check-body pc/1								;-- check condition block
			check-body pc/2								;-- check body block
			
			set [expr cond]   comp-block-chunked/test 'while	;-- Condition block
			set [unused body] comp-block-chunked		;-- Body block
			
			if logic? expr/1 [expr: [<>]]				;-- re-encode test op
			offset: emitter/branch/over body			;-- Jump to condition
			bodies: emitter/chunks/join body cond
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/back/on/adjust bodies reduce [expr/1] offset ;-- Test condition, exit if FALSE
			emitter/merge bodies
			last-type: none-type
			<last>
		]
		
		comp-expression-list: func [/_all /local list offset bodies op][
			pc: next pc
			check-body pc/1								;-- check body block
			
			list: make block! 8
			pc: fetch-into pc/1 [
				while [not tail? pc][					;-- comp all expressions in chunks
					append/only list comp-block-chunked/only/test pick [all any] to logic! _all
				]
			]
			list: back tail list
			set [offset bodies] emitter/chunks/make-boolean			;-- emit ending FALSE/TRUE block
			if _all [emitter/branch/over/adjust bodies offset/1]	;-- conclude by a branch on TRUE
			offset: pick offset not _all				;-- branch to TRUE or FALSE 
			
			until [										;-- left join all expr in reverse order			
				op: either logic? list/1/1/1 [first [<>]][list/1/1/1]
				unless _all [op: reduce [op]]			;-- do not invert the test if ANY
				emitter/set-signed-state list/1/1		;-- properly set signed/unsigned state
				emitter/branch/over/on/adjust bodies op offset		;-- first emit branch				
				bodies: emitter/chunks/join list/1/2 bodies			;-- then left join expr
				also head? list	list: back list
			]	
			emitter/merge bodies
			last-type: [logic!]
			<last>
		]
		
		comp-assignment: has [name value n enum ns][
			push-call name: pc/1
			pc: next pc
			if set-word? name [
				n: to word! name
				unless any [locals local-variable? n][store-ns-symbol n]
				
				unless all [
					local-variable? n
					n = 'context						;-- explicitly allow 'context name for local variables
				][
					check-keywords n					;-- forbid keywords redefinition
				]
				if find definitions n [
					backtrack name
					throw-error ["redeclaration of definition" name]
				]
				if all [
					not local-variable? n
					enum: enum-id? n
				][
					backtrack name
					throw-error ["redeclaration of enumerator" name "from" enum]
				]
				if all [
					get-word? pc/1
					find functions to word! pc/1
				][
					throw-error "storing a function! requires a type casting"
				]
				unless local-variable? n [
					if all [ns-path none? locals][add-ns-symbol pc/-1]
					if all [ns: resolve-ns n ns <> n][name: to set-word! ns]
					check-func-name/only to word! name	;-- avoid clashing with an existing function name		
				]
			]
			if set-path? name [
				unless any [name/1 = 'system local-variable? name/1][
					name: resolve-ns-path name
				]
				if all [series? name value: system-reflexion? name][name: value]
			]
			
			either none? value: fetch-expression [		;-- explicitly test for none!
				none
			][
				new-line/all reduce [name value] no
			]
		]
		
		comp-func-args: func [name [word!] entry [hash!] /local attribute fetch expr args n pos][
			push-call name
			pc: next pc							;-- it's a function
			either attribute: check-variable-arity? entry/2/4 [
				fetch: [
					pos: pc
					expr: fetch-expression
					either attribute = 'typed [
						if all [expr = <last> none? last-type/1][
							pc: pos
							throw-error "expression has no defined return type"
						]
						append args id: get-type-id expr
						append/only args expr
						append args pick [#_ 0] id = emitter/datatype-ID/float! ;-- 32-bit padding
					][
						append/only args expr
					]
				]
				args: make block! 1
				either block? pc/1 [
					fetch-into pc/1 [until [do fetch tail? pc]]
					pc: next pc					;-- jump over arguments block
				][
					do fetch
				]
				reduce [name to-issue attribute args]
			][									;-- fixed arity case
				args: make block! n: entry/2/1
				loop n [append/only args fetch-expression]	;-- fetch n arguments
				new-line/all head insert/only args name no
			]
		]
		
		resolve-ns-path: func [path [path! set-path!] /local new pos][
			new: resolve-ns/path path/1					;-- try to prefix path/1

			either find/only ns-list to path! new [		;-- check if (prefixed) path/1 is a namespace
				new: to path! new
				until [									;-- collect all ns prefixes from head
					path: next path
					append new path/1					;-- move each path value to new one
					not find/only ns-list new			;-- while the new path is still a namespace
				]
				new: ns-decorate new					;-- prefix and convert to word 
				unless tail? next path [				;-- if non-ns remains in path
					new: append to path! new next path	;-- convert back to path by adding non-ns remain 
				]
				if set-path? path [
					new: to either word? new [set-word!][set-path!] new
				]
				new
			][
				unless word? new [path/1: ns-decorate new]	;-- only prefix+convert path/1 if required
				path
			]
		]
		
		comp-path: has [path value ns type name][
			path: pc/1
			if #":" = first mold path/1 [
				throw-error "get-path! syntax is not supported"
			]
			either all [
				not local-variable? path/1
				path: resolve-ns-path path
				word? path
			][
				if value: get-enumerator path [
					last-type: [integer!]
					pc: next pc
					return value
				]
				comp-word/with path
			][
				case [
					value: system-reflexion? path [
						either path/2 = 'words [
							return comp-word/with/root value ;-- re-route to global word resolution
						][
							pc: next pc
						]
					]
					'function! = first type: resolve-path-type/short path [
						name: to word! form path
						check-specs name type/2
						clear-docstrings type/2
						add-function 'routine reduce [name none type/2] get-cconv type/2
						append last functions reduce [path 'local]
						return comp-func-args name skip tail functions -2
					]
					'else [
						comp-word/path path/1				;-- check if root word is defined
						last-type: resolve-path-type path
					]
				]
				any [value path]
			]
		]
		
		comp-get-word: has [spec name ns symbol][
			name: resolve-ns to word! pc/1
			comp-word/with/check name
			
			if all [
				spec: find functions name
				spec: spec/2
			][
				unless find [native routine] spec/2 [
					throw-error "get-word syntax only reserved for native functions for now"
				]
				if all [
					symbol: last expr-call-stack
					spec: find functions symbol
					spec/2/2 = 'import					;-- only flag it when passed to external calls
					spec/2/5 <> 'callback
				][
					append spec/2 'callback				;@@ force cdecl ????
				]
			]
			also to get-word! name pc: next pc
		]
		
		direct-match-ns: func [ctx [path!] name [word!] path /local ns][
			if all [
				any [
					all [ns-stack find/only ns-stack ctx]
					all [ns-path find/only ns-path ctx]
				]
				ns: find/only ns-list ctx
				find ns/2 name
			][
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join ctx name
			]
		]
		
		match-ns: func [name [word!] ctx [word! path!] path /local pos][
			either pos: find ns-stack either path? ctx [ctx/1][ctx][ ;-- match (1st) context with stack
				if path? ctx [							;-- context hierarchy to match with stack
					foreach level ctx [					;-- match each context with next one on stack
						if pos/1 <> level [return none]	;-- if doesn't match, prefix doesn't apply
						pos: next pos					;-- next stack entry
					]
				]
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join to path! ctx name	;-- prefix and convert back to word
			][
				none									;-- no match on stack
			]
		]
		
		resolve-ns: func [name [word!] /path /local ctx pos][
			unless ns-stack [return name]				;-- no current ns, pass-thru

			if ctx: find/skip sym-ctx-table name 2 [	;-- fetch context candidates
				ctx: ctx/2								;-- SELECT/SKIP on hash! unreliable!
				either block? ctx [						;-- more than one candidate
					all [								;-- try direct matching first
						pos: find/only ctx to path! load mold ns-stack	;-- safer to-path conversion
						return either path [
							ns-join to path! first pos name
						][
							ns-decorate ns-join first pos name
						]
					]
					ctx: tail ctx						;-- start from last defined context
					until [
						ctx: back ctx
						if value: any [
							match-ns name ctx/1 path 
							direct-match-ns ctx/1 name path
						][
							return value				;-- prefix name if context on stack
						]
						head? ctx
					]									;-- no match found, pass-thru
				][										;-- one parent context only
					name: any [
						match-ns name ctx path		 	;-- prefix name if context is on stack
						direct-match-ns ctx name path
						name
					]
				]
			]
			name
		]
	
		comp-word: func [
			/path symbol [word!]
			/with word [word!]
			/root										;-- system/words/* pass-thru
			/check										;-- check word validity, do not consume input
			/local entry name local? spec type
		][
			name: pc/1
			if name = shift-right-sym [name: '-**]		;-- replace '>>> words produced by Red layer

			name: any [
				word
				symbol
				all [local-variable? name name]			;-- pass-thru for locals
				all [not root resolve-ns name]
				name
			]
			local?: local-variable? name
			case [
				all [
					not all [local? name = 'context]
					entry: select keywords name			;-- it's a reserved word
				][
					if find calling-keywords name [push-call pc/1]
					unless check [do entry]
				]
				any [
					all [
						local?
						any [
							all [						;-- block local function pointers
								block? type: select locals name
								'function! <> type/1
							]
							not block? type				;-- pass-thru
						]
					]
					all [
						find globals name
						'function! <> first get-type name	;-- block function pointers
					]
				][										;-- it's a variable
					if not-initialized? name [
						throw-error ["local variable" name "used before being initialized!"]
					]
					last-type: resolve-type name
					unless check [also name pc: next pc]
				]
				type: enum-type? name [
					last-type: type
					if verbose >= 3 [print ["ENUMERATOR" name "=" last-type]]
					unless check [also name pc: next pc]
				]
				all [
					not path
					entry: find-functions name
				][
					spec: entry/2/4
					if all [
						find-attribute spec 'infix
						path? pc/1
					][
						throw-error "infix functions cannot be called using a path"
					]
					unless check [comp-func-args name entry]
				]
				'else [throw-error ["undefined symbol:" mold name]]
			]
		]
		
		cast-null: func [variable [set-word! set-path!] /local casting][
			unless all [
				attempt [
					casting: get-type any [
						all [set-word? variable	to word! variable]
						to path! variable
					]
				]
				any-pointer? casting
			][
				backtrack variable
				throw-error "Invalid null assignment"
			]			
			casting
		]
		
		order-args: func [name [word!] args [block!]][
			if any [
				all [
					find [import native infix routine] functions/:name/2
					find [stdcall cdecl] functions/:name/3
				]
				all [
					functions/:name/2 = 'syscall
					job/syscall = 'BSD
				]
				all [
					functions/:name/2 = 'syscall		
					job/target = 'ARM					;-- odd, but required for Linux/ARM syscalls
					job/syscall = 'Linux
				]
			][		
				reverse args
			]
		]
		
		external-call?: func [spec [block!] /local attribs][
			to logic! any [
				spec/5 = 'callback
				all [
					attribs: get-attributes spec/4
					any [find attribs 'cdecl find attribs 'stdcall]
				]
			]
		]

		comp-call: func [
			name [word!] args [block!] /sub
			/local list type res align? left right dup var-arity? saved? arg expr spec
		][
			name: decorate-fun name
			list: either issue? args/1 [				;-- bypass type-checking for variable arity calls
				args/2
			][
				check-arguments-type name args
				args
			]
			order-args name list						;-- reorder argument according to cconv

			spec: functions/:name
			align?: all [
				args/1 <> #custom
				any [
					spec/2 = 'import					;@@ syscalls don't seem to need special alignment??
					all [spec/2 = 'routine external-call? spec]
				]
			]
			if align? [emitter/target/emit-stack-align-prolog args]
			
			if args/1 <> #custom [
				type: functions/:name/2
				either type <> 'op [
					forall list [						;-- push function's arguments on stack
						expr: list/1
						if block? unbox expr [comp-expression expr yes]	;-- nested call
						if object? expr [cast expr]
						if type <> 'inline [
							emitter/target/emit-argument expr functions/:name ;-- let target define how arguments are passed
						]
					]
				][										;-- nested calls as op argument require special handling
					if block? unbox list/1 [comp-expression list/1 yes]	;-- nested call
					left:  unbox list/1
					right: unbox list/2
					if saved?: all [block? left any [block? right path? right]][
						emitter/target/emit-save-last	;-- optionally save left argument result
					]
					if block? unbox list/2 [comp-expression list/2 yes]	;-- nested call
					if saved? [emitter/target/emit-restore-last]
				]
			]
			res: emitter/target/emit-call name args to logic! sub

			either res [
				last-type: res
			][
				set-last-type functions/:name/4			;-- catch nested calls return type
			]
			if align? [emitter/target/emit-stack-align-epilog args]
			res
		]
				
		comp-path-assign: func [
			set-path [set-path!] expr casted [block! none!]
			/local type new value
		][
			value: unbox expr
			if find [block! path! tag!] type?/word value [
				emitter/target/emit-move-path-alt		;-- save assigned value
			]
			if all [
				not local-variable? set-path/1
				enum-id? set-path/1
			][
				backtrack set-path
				throw-error ["enumeration cannot be used as path root:" set-path/1]
			]
			unless get-variable-spec set-path/1 [
				backtrack set-path
				throw-error ["unknown path root variable:" set-path/1]
			]
			type: resolve-path-type set-path			;-- check path validity
			new: resolve-aliased get-type expr		

			if type <> any [casted new][
				backtrack set-path
				throw-error [
					"type mismatch on setting path:" to path! set-path
					"^/*** expected:" mold type
					"^/*** found:" mold any [casted new]
				]
			]		
			emitter/access-path set-path either any [block? value path? value][
				 <last>
			][
				expr
			]
		]
		
		comp-variable-assign: func [
			set-word [set-word!] expr casted [block! none!]
			/local name type new value fun-name
		][
			name: to word! set-word		
			if find aliased-types name [
				backtrack set-word
				throw-error "name already used for as an alias definition"
			]
			if not-initialized? name [
				init-local name expr casted				;-- mark as initialized and infer type if required
			]

			if all [
				casted
				casted/1 = 'function!
				local-variable? name
			][
				fun-name: decorate-function name
				add-function 'routine reduce [fun-name none casted/2] get-cconv casted/2
				append last functions reduce [name 'local]
			]
			
			either type: any [
				get-variable-spec name					;-- test if known variable (local or global)	
				enum-id? name
			][
				type: resolve-aliased type
				value: get-type expr
				if block? expr [parse value [type-spec]] ;-- prefix return type if required	
				new: resolve-aliased value
				
				if type <> any [casted new][
					backtrack set-word
					throw-error [
						"attempt to change type of variable:" name
						"^/*** from:" mold type
						"^/***   to:" mold any [casted new]
					]
				]
			][
				unless zero? block-level [
					backtrack set-word
					throw-error "variable not declared"
				]
				if any [
					all [casted casted/1 = 'function!]
					all [expr = <last> casted: last-type last-type/1 = 'function!]
				][
					add-function 'routine reduce [name none casted/2] get-cconv casted/2
				]
				type: add-symbol name unbox expr casted  ;-- if unknown add it to global context	
			]
			if none? type/1 [
				backtrack set-word
				throw-error ["unable to determine a type for:" name]
			]
			value: unbox expr
			if any [block? value path? value][value: <last>]
			emitter/store name value type
		]
		
		comp-expression: func [expr keep? [logic!] /local variable boxed casting new? type][
			;-- preprocessing expression
			if all [block? expr find [set-word! set-path!] type?/word expr/1][
				variable: expr/1
				expr: expr/2							;-- switch to assigned expression
				if set-word? variable [
					new?: not exists-variable? variable
				]
			]			
			if object? expr [							;-- unbox type-casting object
				if all [variable expr/action = 'null][
					casting: cast-null variable
				]
				boxed: expr
				expr: cast expr
			]
			
			;-- dead expressions elimination
			if all [
				not keep?
				not any [tail? pc variable]				;-- not last expression nor assignment value
				1 >= length? expr-call-stack			;-- one (for math op) or no parent call
				'switch <> pick tail expr-call-stack -1
				any [
					all [
						any [
							word? expr 					;-- variable alone
							literal? expr				;-- literal, but not logic value
						]
						'logic! <> first get-type expr
					]
					all [
						block? expr
						functions/(decorate-fun expr/1)/2 = 'op	;-- math expression
						any [							;-- no return value, or return value type <> logic!
							not type: find functions/(expr/1)/4 return-def
							type/2/1 <> 'logic!
						]
					]
				]
			][exit]

			;-- emitting expression code
			either block? expr [
				type: comp-call expr/1 next expr 		;-- function call case (recursive)
				if type [last-type: type]				;-- set last-type if not already set
				if all [
					variable boxed						;-- process casting if result assigned to variable
					last-type/1 = 'logic!
					boxed/type  = 'integer!				;-- fixes #967
				][
					emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
					last-type: boxed/type
				]
			][
				last-type: either not any [
					all [new? literal? unbox expr]		;-- if new variable, value will be store in data segment
					all [set-path? variable not path? expr]	;-- value loaded at lower level
					tag? unbox expr
				][
					emitter/target/emit-load either boxed [boxed][expr]	;-- emit code for single value
					either all [boxed not decimal? unbox expr][
						emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
						boxed/type
					][
						resolve-expr-type expr
					]
				][
					resolve-expr-type expr
				]
			]
			
			;-- postprocessing result
			if all [
				any [
					keep?
					variable							;-- result needs to be stored
					all [
						'case = pick tail expr-call-stack -3
						#test <> pick tail expr-call-stack -2
						4 <= length? expr-call-stack
					]
				]
				block? expr								;-- and if expr is a function call		
				last-type/1 = 'logic!					;-- which return type is logic!
			][
				emitter/logic-to-integer expr/1			;-- runtime logic! conversion before storing
			]
			
			if all [									;-- clean FPU stack when required
				not any [keep? variable]
				block? expr
				word? expr/1
				any-float? get-return-type/check expr/1
				any [
					not find functions/(expr/1)/4 return-def	;-- clean if no return value
					1 = length? expr-call-stack					;-- or if return value not used
				]
			][
				emitter/target/emit-float-trash-last	;-- avoid leaving a x86 FPU slot occupied,
			]											;-- if return value is not used.
			
			;-- storing result if assignement required
			if variable [
				if all [boxed not casting][
					casting: resolve-aliased boxed/type
				]
				unless boxed [boxed: expr]
				switch type?/word variable [
					set-word! [comp-variable-assign variable expr casting]
					set-path! [comp-path-assign		variable boxed casting]
				]
			]
		]
		
		check-enum-symbol: func [code [any-block!] /local value][
			if all [									;-- if enum, replace it with its integer value
				word? code/1
				not local-variable? code/1
				value: get-enumerator resolve-ns code/1
			][
				change code value
			]
		]
		
		infix?: func [pos [block! paren!] /local specs][
			all [
				not tail? pos
				word? pos/1
				specs: find functions resolve-ns pos/1
				specs: specs/2
				find [op infix] specs/2
			]
		]
		
		check-infix-operators: has [pos][
			if infix? pc [
				either infix? back tail expr-call-stack [
					exit								;-- infix op already processed
				][
					throw-error "invalid use of infix operator"
				]
			]
			if infix? next pc [
				either find [set-word! set-path! struct!] type?/word pc/1 [
					throw-error "can't use infix operator here"
				][
					pos: 0								;-- relative index of next infix op
					until [								;-- search for all dependent infix op
						pos: pos + 2					;-- target next infix possible position
						insert pc pc/:pos				;-- transform to prefix notation
						remove at pc pos + 1
						not infix? at pc pos + 2		;-- exit when no more infix op found
					]
				]
			]
		]
		
		fetch-expression: func [/final /keep /local expr pass value][
			check-infix-operators
			
			if verbose >= 4 [print ["<<<" mold pc/1]]
			pass: [also pc/1 pc: next pc]
			
			if tail? pc [
				pc: back pc
				throw-error "missing argument"
			]
			if job/debug? [store-dbg-lines]
			
			check-enum-symbol pc

			expr: switch/default type?/word pc/1 [
				set-word!	[comp-assignment]
				word!		[comp-word]
				get-word!	[comp-get-word]
				path! 		[comp-path]
				set-path!	[comp-assignment]
				paren!		[comp-block/only]
				char!		[do pass]
				integer!	[do pass]
				string!		[do pass]
				decimal!	[do pass]
				block!		[also to paren! pc/1 pc: next pc]
				issue!		[comp-directive]
			][
				throw-error "datatype not allowed"
			]
			expr: reduce-logic-tests expr

			if final [
				if verbose >= 3 [?? expr]
				unless find [none! tag!] type?/word expr [
					comp-expression expr to logic! keep
				]
			]
			expr
		]
		
		comp-block: func [/final /only /local expr save-pc][
			block-level: block-level + 1
			save-pc: pc
			pc: pc/1

			either only [
				expr: either final [fetch-expression/final][fetch-expression]
				unless tail? pc [
					throw-error "more than one expression found in parentheses"
				]
			][
				while [not tail? pc][
					;if all [paren? pc/1 not infix? at pc 2][raise-paren-error]
					expr: either final [fetch-expression/final][fetch-expression]
					unless tail? pc [pop-calls]
				]
			]
			pc: next save-pc
			
			block-level: block-level - 1
			expr
		]
		
		comp-dialect: has [expr][
			block-level: 0
			while [not tail? pc][
				case [
					issue? pc/1 [comp-directive]
					all [
						set-word? pc/1
						find [func function] pc/2
					][
						pc: next pc
						fetch-func pc/-1				;-- allow function declaration at root level only
					]
					all [set-word? pc/1 pc/2 = 'alias][
						pc: next pc
						comp-alias						;-- allow alias declaration at root level only
					]
					paren? pc/1 [
						;unless infix? at pc 2 [raise-paren-error]
						expr: fetch-expression/final/keep
					]
					'else [expr: fetch-expression/final/keep]
				]
				pop-calls
				emitter/target/on-root-level-entry
			]
			expr
		]
		
		comp-func-body: func [
			name [word!] spec [block!] body [block!]
			/local args-sz local-sz expr ret
		][
			locals: spec
			func-name: name
			set [args-sz local-sz] emitter/enter name locals ;-- build function prolog
			pc: body
			
			expr: comp-dialect							;-- compile function's body
			
			if ret: select spec return-def [
				check-expected-type/ret name expr ret	;-- validate return value type
				if all [
					object? expr 
					find [block! tag!] type?/word expr/data
				][
					emitter/target/emit-casting expr no	;-- insert runtime type casting when required
					last-type: expr/type
				]
			]
			emitter/leave name locals args-sz local-sz	;-- build function epilog
			remove-func-pointers
			clear locals-init
			locals: func-name: none
		]
		
		comp-natives: does [			
			foreach [name spec body origin ns nss] natives [
				if verbose >= 2 [
					print [
						"---------------------------------------^/"
						"function:" name newline
						"---------------------------------------"
					]
				]
				script: origin
				ns-path: ns
				ns-stack: nss
				comp-func-body name spec body
			]
		]
		
		comp-header: has [pos][
			unless pc/1 = 'Red/System [
				throw-error "source is not a Red/System program"
			]
			pc: next pc
			unless block? pc/1 [
				throw-error "missing Red/System program header"
			]
			unless parse pc/1 [any [pos: set-word! skip]][
				throw-error ["invalid program header at:" mold pos]
			]
			pc: next pc
		]
		
		get-proto: func [name [word!]][
			switch/default job/OS [
				Windows [
					[handle [integer!]]
				]
				MacOSX [
					pick [
						[
							argc	[integer!]
							argv	[struct! [s [c-string!]]]
							envp	[struct! [s [c-string!]]]
							apple	[struct! [s [c-string!]]]
							pvars	[program-vars!]
						]
						[[cdecl]]
					] name = 'on-load
				]
			][											;-- Linux
				[[cdecl]]
			]
		]
		
		add-dll-callbacks: has [list code exp][			;-- add missing callbacks
			list: copy [on-load on-unload]
			if job/OS = 'Windows [
				append list [on-new-thread on-exit-thread]
			]
			code: make block! 1
			exp:  make block! 1
			
			foreach fun list [
				unless find/skip natives fun 6 [
					repend code [
						to set-word! fun 'func get-proto fun []	;-- stdcall
					]
				]
			]
			unless empty? code [
				pc: code
				comp-dialect
			]
		]

		run: func [obj [object!] src [block!] file [file!] /no-header /runtime /no-events][
			runtime: to logic! runtime
			job: obj
			pc: src
			script: secure-clean-path file
			unless no-header [comp-header]
			unless no-events [emitter/target/on-global-prolog runtime job/type]
			comp-dialect
			unless no-events [
				case [
					runtime [
						emitter/target/on-global-epilog yes	job/type ;-- postpone epilog event after comp-runtime-epilog
					]
					not job/runtime? [
						emitter/target/on-global-epilog no job/type
					]
				]
			]
		]
		
		finalize: does [
			if verbose >= 2 [print "^/---^/Compiling native functions^/---"]
			if job/type = 'dll [
				if empty? exports [
					throw-error "missing #export directive for library production"
				]
				add-dll-callbacks 						;-- make sure they are defined
			]
			comp-natives
			emitter/target/on-finalize
			if verbose >= 2 [print ""]
			emitter/reloc-native-calls
		]
	]
	
	set-verbose-level: func [level [integer!]][
		foreach ctx reduce [
			self
			loader
			compiler
			emitter
			emitter/target
			linker
		][
			ctx/verbose: level
		]
	]
	
	output-logs: does [
		case/all [
			verbose >= 1 [
				print [
					nl
					"-- compiler/globals --" nl mold new-line/all/skip to-block compiler/globals yes 2 nl
					"-- emitter/symbols --"  nl mold new-line/all/skip to-block emitter/symbols yes 2 nl
				]
			]
			verbose >= 2 [
				print [
					"-- compiler/functions --" nl mold new-line/all/skip to-block compiler/functions yes 2 nl
				]
			]
			verbose >= 6 [
				print [
					"-- emitter/code-buf --" nl mold emitter/code-buf nl
					"-- emitter/data-buf --" nl mold emitter/data-buf nl
					"as-string:"        	 nl mold as-string emitter/data-buf nl
				]
			]
		]
	]
	
	emit-main-prolog: has [name spec][
		either job/type = 'exe [
			emitter/target/on-init
		][												;-- wrap global code in a function
			name: '***-main
			compiler/add-function 'native reduce [name none []] 'stdcall
			spec: emitter/add-native name
			spec/2: 1
			emitter/target/emit-prolog name [] 0
		]
	]

	comp-start: has [script][
		emitter/libc-init?: yes
		emitter/start-prolog
		script:	either encap? [
			set-cache-base %system/runtime/
			%start.reds
		][
			secure-clean-path runtime-path/start.reds
		]
 		compiler/run/no-events job loader/process/own script script
 		emitter/start-epilog
 
		;-- selective clean-up of compiler's internals
 		remove/part find compiler/globals 'system 2		;-- avoid 'system redefinition clash
 		remove/part find emitter/symbols 'system 4
		clear compiler/definitions
		clear compiler/aliased-types
		emitter/libc-init?: no
	]
	
	comp-runtime-prolog: func [red? [logic!] /local script][
		script: either encap? [
			set-cache-base %system/runtime/
			%common.reds
		][
			secure-clean-path runtime-path/common.reds
		]
 		compiler/run/runtime job loader/process/own script script
 		
 		if red? [
 			unless empty? red/sys-global [
				set-cache-base %./
				compiler/run job loader/process red/sys-global %***sys-global.reds
 			]
 			set-cache-base %runtime/
 			script: pick [%red.reds %../runtime/red.reds] encap?
 			compiler/run job loader/process/own script script
 		]
 		set-cache-base none
	]
	
	comp-runtime-epilog: does [
		either job/need-main? [
			emitter/target/on-global-epilog no job/type	;-- emit main() epilog
		][
			switch job/type [
				exe [compiler/comp-call '***-on-quit [0 0]]	;-- call runtime exit handler
				dll [emitter/target/emit-epilog '***-main [] 0 0]
				drv [emitter/target/emit-epilog '***-main [] 0 0]
			]
		]
	]
	
	clean-up: does [
		compiler/ns-path: 
		compiler/ns-stack: 
		compiler/locals: none
		compiler/resolve-alias?:  yes
		
		clear compiler/imports
		clear compiler/exports
		clear compiler/natives
		clear compiler/ns-list
		clear compiler/sym-ctx-table
		clear compiler/globals
		clear compiler/definitions
		clear compiler/enumerations
		clear compiler/aliased-types
		clear compiler/user-functions
		clear compiler/debug-lines/records
		clear compiler/debug-lines/files
		clear emitter/symbols
	]
	
	make-job: func [opts [object!] file [file!] /local job][
		job: construct/with third opts linker/job-class	
		file: last split-path file					;-- remove path
		file: to-file first parse file "."			;-- remove extension
		case [
			none? job/build-basename [
				job/build-basename: file
			]
			slash = last job/build-basename [
				append job/build-basename file
			]
		]
		job
	]
	
	set 'dt func [code [block!] /local t0][
		t0: now/time/precise
		do code
		now/time/precise - t0
	]
	
	compile: func [
		files [file! block!]							;-- source file or block of source files
		/options
			opts [object!]
		/loaded 										;-- source code is already in LOADed format
			src	[block!]
		/local
			comp-time link-time err output
	][
		comp-time: dt [
			unless block? files [files: reduce [files]]
			
			unless opts [opts: make options-class []]
			job: make-job opts last files				;-- last input filename is retained for output name
			emitter/init opts/link? job
			if opts/verbosity >= 10 [set-verbose-level opts/verbosity]
			
			clean-up
			loader/init
			emit-main-prolog
			
			job/need-main?: to logic! any [
				job/need-main?							;-- pass-thru if set in config file
				all [
					job/type = 'exe
					not find [Windows MacOSX] job/OS
				]
			]
			
			if all [
				job/need-main?
				not opts/use-natives?
				opts/runtime?
			][
				comp-start								;-- init libC properly
			]
			
			if opts/runtime? [comp-runtime-prolog to logic! loaded]
			
			set-verbose-level opts/verbosity
			foreach file files [
				src: either loaded [
					loader/process/with src file
				][
					loader/process file
				]
				compiler/run job src file
			]
			set-verbose-level 0
			if opts/runtime? [comp-runtime-epilog]
			
			set-verbose-level opts/verbosity
			compiler/finalize							;-- compile all functions
			set-verbose-level 0
		]
		if verbose >= 5 [
			print [
				"-- emitter/code-buf (empty addresses):"
				nl mold emitter/code-buf nl
			]
		]

		if opts/link? [
			link-time: dt [
				job/symbols: emitter/symbols
				job/sections: compose/deep/only [
					code   [- 	(emitter/code-buf)]
					data   [- 	(emitter/data-buf)]
					import [- - (compiler/imports)]
				]
				if not empty? compiler/exports [
					append job/sections compose/deep/only [
						export [- - (compiler/exports)]
					]
				]
				if opts/debug? [
					job/debug-info: reduce ['lines compiler/debug-lines]
				]
				output: linker/build job
			]
		]
		
		set-verbose-level opts/verbosity
		output-logs
		if opts/link? [clean-up]

		reduce [
			comp-time
			link-time
			any [all [job/buffer length? job/buffer] 0]
			output
		]
	]
]
library('ForeCA')

args <- commandArgs(trailingOnly = TRUE)
arg_id <- args[1]
arg_dim <- as.numeric(args[2])

X <- ts(read.csv(sprintf('foreca_node_train_%s.csv', arg_id), header=FALSE))
ff <- foreca(X, n.comp=arg_dim)
summary(ff)
print(ff$loadings)
W <- matrix(ff$loadings, ncol=arg_dim)

write.matrix(W, sprintf('foreca_node_result_%s.csv', arg_id))
#' Default theme for EnvReportBC graphs and plots
#'
#' 
#' 
#' @import ggplot2
#' @param  base_size base font size (default = 12)
#' @param  base_family base font family (default = Verdana)
#' @param  use_sizes use relative font sizes (?)
#' @param  facet facetting? (advise to not use directly, is set by \code{theme_soe_facet})
#' @export
#' @keywords plotting theme
#' @return returns a plot theme
#' @examples \dontrun{
#' 
#'}
theme_soe <- function(base_size=12, base_family="Verdana", use_sizes=TRUE, facet = FALSE) {
  thm <- theme_foundation_null(base_size = base_size, 
                               base_family = base_family) +
    theme(
      text = element_text(color="black"),
      axis.line = element_line(colour="black"),
      axis.text = element_text(color = 'black'),
      axis.text.y = element_text(hjust = 1),
      axis.ticks = element_blank(),
      plot.title = element_text(vjust=2),
      legend.title = element_text(face="plain"),
      panel.background = element_blank(),
      panel.border = element_blank(),
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "grey80",size=0.5),
      axis.title.y = element_text(vjust=1, angle = 90),
      axis.title.x = element_text(vjust=0),
      panel.margin.x = unit(0, "lines"),
      panel.margin.y = unit(0, "lines"),
      plot.background = element_blank(),
      panel.border = element_blank(),
      legend.key = element_blank())
  
  if (use_sizes) {
    thm <- thm + theme_foundation_sizes(facet = facet)
  }
  
  thm
}  

#' Soe plot theme for facetted graphs
#' 
#' @import ggplot2
#' @param  base_size base font size (default = 12)
#' @param  base_family base font family (default = Verdana)
#' @param  use_sizes use relative font sizes (?)
#' @export
#' @keywords plotting theme
#' @return a ggplot2 theme
#' @examples \dontrun{
#' 
#'}
theme_soe_facet <- function(base_size=12, base_family="Verdana", use_sizes=TRUE) {
  theme_soe(facet = TRUE) + 
    theme(
      panel.margin.x = unit(.6,"lines"),
      panel.margin.y = unit(.6,"lines"),
      panel.border = element_rect(colour = "black", fill = NA),
      strip.background = element_rect(colour = "black", fill = "grey85"))
}

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
    geneName = geneNames[i]
    geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]

    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient != 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneNames), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=numCores)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
    geneName = geneNames[i]
    geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]

    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient != 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneNames), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=10)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])


if("data.table" %in% rownames(installed.packages()) == FALSE) install.packages("data.table")
if("plyr" %in% rownames(installed.packages()) == FALSE) install.packages("plyr")
if("reshape2" %in% rownames(installed.packages()) == FALSE) install.packages("reshape2")
if("glmnet" %in% rownames(installed.packages()) == FALSE) install.packages("glmnet")
if("GenomicRanges" %in% rownames(installed.packages()) == FALSE) { source("http://bioconductor.org/biocLite.R"); biocLite("GenomicRanges"); }
if("preprocessCore" %in% rownames(installed.packages()) == FALSE) { source("http://bioconductor.org/biocLite.R"); biocLite("preprocessCore"); }


suppressMessages(require(data.table)    )
suppressMessages(require(plyr)          )
suppressMessages(require(reshape2)      )
suppressMessages(require(glmnet)        )
suppressMessages(require(preprocessCore))
suppressMessages(require(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient != 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneDataList), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=10)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneDataList), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=10)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





### Lastest load into a package.

.First.lib <- function(lib, pkg){
  if(! is.loaded("spmd_initialize", PACKAGE = "pbdMPI")){
    library.dynam("pbdMPI", "pbdMPI", lib)
    if(pbdMPI::comm.is.null(0L) == -1){
      pbdMPI::init()
    }
  }

  library.dynam("pbdADIOS", pkg, lib)
} # End of .First.lib().

.Last.lib <- function(libpath){
  pbdADIOS::adios.finalize(pbdMPI::comm.rank())
  library.dynam.unload("pbdADIOS", libpath)
} # End of .Last.lib().
args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/final_dataset/final_bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		#file.remove(tempOut, showWarnings=F)
	}
	#file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=F)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
            if (length(enh.id) == 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene),
                                  variable=c("(Intercept)",
                                      colnames(covari)),
                                  coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) == 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)",
                                          colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneDataList), modelRNA,  geneDataList, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/final_dataset/final_bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		#file.remove(tempOut, showWarnings=F)
	}
	#file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=F)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
            if (length(enh.id) == 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene),
                                  variable=c("(Intercept)",
                                      colnames(covari)),
                                  coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) == 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)",
                                          colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == unique(xx))){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneDataList), function(xx){
    print(xx)
    tryCatch({
      modelRNA(xx,  geneDataList)
    }, error=function(e)
          { print(e)
        #    print(geneDataList[[xx]])
        }
            )}, 
    mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/final_dataset/final_bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		#file.remove(tempOut, showWarnings=F)
	}
	#file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=F)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene),
                                  variable=c("(Intercept)",
                                      colnames(covari)),
                                  coefficient=rep.int(0, ncol(covari)+1+length(enh.id)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    s1.fit <- predict(step1, newx=covari, s="lambda.1se")
    residual <- rna - s1.fit
    step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
    s2.c <- predict(step2, type="coefficients", s="lambda.1se")

    coefs <- c(unique(geneData$gene), unlist(s1.c[,1]), unlist(s2.c[-1,1]))
	#coefs = data.frame(gene=unique(geneData$gene), variable=rownames(s1.c), coefficient=s1.c[,1], row.names=NULL)
    return(coefs)
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")
results = parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)
results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





require(ggplot2)

## README

# Change the following two paths to the input path of where ScalaMeter stored the *dsv result files...
inputPath <- "~/Dropbox/TUD/Thesis/code/join/tmp/"
# ... and where you would like the script to output the graphs:
outputPath <- "/Users/ayedo/Dropbox/TUD/Thesis/document/img/evaluation/"
# To run the script use Rscript GeneratePlot.r, or use RStudio. When using RScript you might want to fix the
# size of the plots by changing the ggsave command options to a fixed size.


# Drops columns which are not required
processed_import <- function(path, name) {
  dt <- read.csv(path, stringsAsFactors=FALSE)
  cropped <- subset(dt, select=-c(units, success))
  cropped$Approach = name
  return(cropped)
}

rxj <- processed_import(paste0(inputPath, "twoCasesIndependend.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "twoCasesIndependend.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "twoCasesIndependend.Deterministic Choice.dsv"), "DCT")

rxj <- rxj[1:4, ]
nct <- nct[1:4, ]
dct <- dct[1:4, ]

all = rbind(rxj, nct, dct)

# Rename the param.Observables column
names(all)[names(all)=="param.Observables"] <- "observables"
all$observables <- factor(all$observables)

# The number of events sent per observable
sentEvents = 32768

# 1. Two Cases Independent: twice number of events sent per observable. Constant.
patternMatches = 2 * sentEvents

valuet = as.numeric(lapply(all$value, function(x) patternMatches / (x / 1000)))
fprime = as.numeric(lapply(all$value, function(m) (-patternMatches * 1000) / (m ** 2)))
diff = all$cihi - all$value
variance = as.numeric(lapply(diff, function(d) (d / 6.361) ** 2))
variancet = variance * as.numeric(lapply(fprime, function(x) x ** 2))
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=observables, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Observables") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Compositions") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black")) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(file=paste0(outputPath, "TwoChoiceNObservables.eps"))

# 2. N Case Independent: number of events sent per observable * number of cases

rxj <- processed_import(paste0(inputPath, "NCaseTwoIndependent.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "NCaseTwoIndependent.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "NCaseTwoIndependent.Deterministic Choice.dsv"), "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = all$choices * sentEvents
all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Number of Choices") +
    theme_bw() + 
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0))  +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) +
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(paste0(outputPath, "NChoiceTwoObservables.eps"))

# 3. 16 Case N Dependent: 16 * number of events sent per observable
rxj <- processed_import(paste0(inputPath, "NDependentCases.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "NDependentCases.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "NDependentCases.Deterministic Choice.dsv"), "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = rep(16 * sentEvents, length(all$choices))

all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Interdependentness") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(paste0(outputPath, "32ChoiceNInterdependent.eps"))
require(ggplot2)

## README
# Change the following two paths to the input path of where ScalaMeter stored the *dsv result files...
inputPath <- "~/Dropbox/TUD/Thesis/code/join/tmp/"
# ... and where you would like the script to output the graphs:
outputPath <- "/Users/ayedo/Dropbox/TUD/Thesis/document/img/evaluation/"

# Drops columns which are not required
processed_import <- function(path, name) {
  dt <- read.csv(path, stringsAsFactors=FALSE)
  cropped <- subset(dt, select=-c(units, success))
  cropped$Approach = name
  return(cropped)
}

rxj <- processed_import(paste0(inputPath, "twoCasesIndependend.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "twoCasesIndependend.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "twoCasesIndependend.Deterministic Choice.dsv"), "DCT")

rxj <- rxj[1:4, ]
nct <- nct[1:4, ]
dct <- dct[1:4, ]

all = rbind(rxj, nct, dct)

# Rename the param.Observables column
names(all)[names(all)=="param.Observables"] <- "observables"
all$observables <- factor(all$observables)

# The number of events sent per observable
sentEvents = 32768

# 1. Two Cases Independent: twice number of events sent per observable. Constant.
patternMatches = 2 * sentEvents

valuet = as.numeric(lapply(all$value, function(x) patternMatches / (x / 1000)))
fprime = as.numeric(lapply(all$value, function(m) (-patternMatches * 1000) / (m ** 2)))
diff = all$cihi - all$value
variance = as.numeric(lapply(diff, function(d) (d / 6.361) ** 2))
variancet = variance * as.numeric(lapply(fprime, function(x) x ** 2))
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=observables, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Observables") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Compositions") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black")) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(file=paste0(outputPath, "TwoChoiceNObservables.eps"))

# 2. N Case Independent: number of events sent per observable * number of cases

rxj <- processed_import(paste0(inputPath, "NCaseTwoIndependent.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "NCaseTwoIndependent.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "NCaseTwoIndependent.Deterministic Choice.dsv"), "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = all$choices * sentEvents
all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Number of Choices") +
    theme_bw() + 
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0))  +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) +
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(paste0(outputPath, "NChoiceTwoObservables.eps"))

# 3. 16 Case N Dependent: 16 * number of events sent per observable
rxj <- processed_import(paste0(inputPath, "NDependentCases.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "NDependentCases.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "NDependentCases.Deterministic Choice.dsv"), "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = rep(16 * sentEvents, length(all$choices))

all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Interdependentness") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(paste0(outputPath, "32ChoiceNInterdependent.eps"))
##' Fetches the chromosomal locations for all genes and sorts them within each chromosome. 
##' @params tcgaResults the list with TCGA results
##' @params ccleResults the list with CCLE results
##' @return a data.frame with locations for all genes
##' @author Andreas Schlicker (a.schlicker@nki.nl)
sortGenesByLocation = function(tcgaResults, ccleResults) {
	# Genes in all cancer types
	genes = rownames(tcgaResults[[1]]$prioritize.combined)
	for (n in 2:length(tcgaResults)) {
		genes = intersect(genes, rownames(tcgaResults[[n]]$prioritize.combined))
	}
	for (n in 1:length(ccleResults)) {
		genes = intersect(genes, rownames(ccleResults[[n]]$prioritize.combined))
	}

	# Find all gene locations
	mart = useMart(host="ensembl.org", path="/biomart/martservice", biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
	geneLoc = getBM(attributes=c("hgnc_symbol", "chromosome_name", "start_position", "end_position", "strand", "band"), filters=c("hgnc_symbol"), values=genes, mart=mart)
	# Remove all non-standard chromosome names and make everything numeric
	geneLoc = geneLoc[which(geneLoc[, "chromosome_name"] %in% c("1", "2", "3", "4", "5", "6", "7", "8", 
																															"9", "10", "11", "12", "13", "14", "15", 
																															"16", "17", "18", "19", "20", "21", "22", 
																															"X", "Y")), ]
	geneLoc[which(geneLoc[, "chromosome_name"] == "X"), "chromosome_name"] = "23"
	geneLoc[which(geneLoc[, "chromosome_name"] == "Y"), "chromosome_name"] = "24"
	geneLoc[, "chromosome_name"] = as.integer(geneLoc[, "chromosome_name"])
	
	geneLoc[which(geneLoc[, "strand"] == 1), "strand"] = "+"
	geneLoc[which(geneLoc[, "strand"] == -1), "strand"] = "-"
	
	# Return the sorted gene information
	geneLoc[order(geneLoc$chromosome_name, geneLoc$start_position), ]
}


##' Generates a chromosome plot for the selected score or the number of affected samples.
##' @params geneLocs the data.frame returned by sortGenesByLocation()
##' @params results either tcgaResults or ccleResults
##' @params cancType the selected four letter cancer code
##' @params chrom the selected chromosome; X is coded as 23 and Y as 24
##' @params scoreType which score was selected; one of "OG", "TS", "CO"
##' @return a list with two plotting objects, "score" the actual score and "affected" the percentage of affected samples
##' @author Andreas Schlicker (a.schlicker@nki.nl) 
getScorePlot = function(geneLocs, results, cancType, chrom, scoreType) {
	scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
	
	# Get the genes for the selected chromosome
	genes = subset(geneLocs, chromosome_name==chrom)
	
	# Get the score vector
	score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.score"]
  # And the percentage of affected samples
	affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"]
	if (scoreType == "TS") {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.score"] * -1
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	} else {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "combined.score"]
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"] - 
							 results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	}
	
	# Get two tracks, one for scores and the other one for percent affected samples 
	tracks = list(DataTrack(GRanges(seqnames=as.character(chrom),
																	ranges=IRanges(start=genes[, "start_position"],
																								 end=genes[, "end_position"]),
																	score,
																	strand="*"),
																	name="", 
																	background.title="white",
																	background.panel="white"),
			
								DataTrack(GRanges(seqnames=as.character(chrom),
																	ranges=IRanges(start=genes[, "start_position"],
																								 end=genes[, "end_position"]),
																	affected,
																	strand="*"),
																	name="",
																	background.title="white",
																	background.panel="white"))
			
	list(score=plotTracks(tracks[1], type=c("h", "g"),
						 ylim=c(min(unlist(lapply(tracks, function(x) { min(x@data) }))), 
										max(unlist(lapply(tracks, function(x) { max(x@data) })))),
						 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
						 main=""),
			 affected=plotTracks(tracks[2], type=c("h", "g"),
						 ylim=c(min(unlist(lapply(tracks, function(x) { min(x@data) }))), 
										max(unlist(lapply(tracks, function(x) { max(x@data) })))),
						 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
						 main=""))
}

library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)
library(GenomicRanges)

rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputSummaryFile = "/epigenomes/teamdata/H1_dummyData3.txt"
outputCoefsFile = "/epigenomes/teamdata/H1_dummyData3_coefs.txt"
numCores = 10
enhancerProximity = 1e+05


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile)
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, rangesGene = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, rangesGene = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@rangesGene@start[overlapGeneEnh@queryHits], end=grEnhancer@rangesGene@start[overlapGeneEnh@queryHits]+grEnhancer@rangesGene@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions
summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene), variable=c("(Intercept)", colnames(covari)), coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    coefs = data.frame(gene=unique(geneData$gene), variable=rownames(s1.c), coefficient=s1.c[,1], row.names=NULL)
	return(coefs)
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

results = parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)
results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData2.txt"
numCores = 10


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]
#geneData3 = dcast(geneData2, id+gene+patient~regionvariable)
write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0)){return(cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))

res = t(parallel::mclapply(500:600, function(ii){
#    print(ii)
    modelRNA(ii, geneDataList)
}, mc.cores=4))






library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData2.txt"
numCores = 10


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]
#geneData3 = dcast(geneData2, id+gene+patient~regionvariable)
write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
	rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
	colnames(rnaData)[3] = "RNA"
	geneData = geneData[geneData$variable != "RNA", ]
	geneData = dcast(geneData, gene+patient~region+variable)
	geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 4


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(1:4, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData2.txt"
numCores = 10


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]
#geneData3 = dcast(geneData2, id+gene+patient~regionvariable)
write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
	rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
	colnames(rnaData)[3] = "RNA"
	geneData = geneData[geneData$variable != "RNA", ]
	geneData = dcast(geneData, gene+patient~region+variable)
	geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 4


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    metaData.id <- grep("id|gene|end|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 4


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(1:4, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == "combined" & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type=="combined" & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")#,
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")

	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
  geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=16, face="bold"),
	      axis.title.x=element_text(color="gray30", size=16, face="bold"),
	      strip.text.x=element_text(color="gray30", size=16, face="bold"),
	      legend.text=element_text(color="gray30", size=16, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }
  }
}
##' view 2
comp1view2Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)     
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)     
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }
  }
}

##' main call to page1 gene data frame
geneDataFrameResultSet = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }
  }
}
## see: http://stackoverflow.com/questions/9298765/print-latex-table-directly-to-an-image-png-or-other
## also maybe useful: http://tex.stackexchange.com/questions/11866/compile-a-latex-document-into-a-png-image-thats-as-short-as-possible
make.png <- function(obj, resolution=NULL) {
  name <- tempfile('x')
  texFile <- paste(name,".tex",sep="")
  pngFile <- paste(name,".png",sep="")
  sink(file=texFile)
  cat('
      \\documentclass[12pt]{report}
      \\usepackage[paperwidth=11in,paperheight=8in,noheadfoot,margin=0in]{geometry}
      \\usepackage[T1]{fontenc}
      \\usepackage{booktabs}
      \\begin{document}\\pagestyle{empty}
      {\\Large
      ')
  save <- booktabs(); on.exit(table_options(save), add=TRUE)
  latex(obj)

  cat('
      }\\end{document}
      ')
  sink()
  wd <- setwd(tempdir()); on.exit(setwd(wd), add=TRUE)
  texi2dvi(file=texFile, index=FALSE)

  cmd <- paste("dvipng -T tight -o",
               shQuote(pngFile),
               if(!is.null(resolution)) paste("-D",resolution) else "",
               shQuote(paste(name,".dvi",sep="")))
  invisible(sys(cmd))
  cleaner <- c(".tex",".aux",".log",".dvi")
  invisible(file.remove(paste(name,cleaner,sep="")))
  pngFile
}

newGuid <- function(){
  gsub("-", "_", UUIDgenerate(), fixed=TRUE)

  #paste(sample(c(letters[1:6],0:9),30,replace=TRUE),collapse="")
}

## preserve names of x
setdiff.c <<- function(x, y){
  z <- setdiff(x, y)
  x1 <- names(x)
  if(!is.null(x1)){
    names(x1) <- x
    names(z) <- x1[z]
    z
  } else z
}
isEmpty <<- function(x){
  is.null(x) || length(x)==0 || all(is.na(x)) || all(x=='')
}

ifnull <- function(x, d){
  if(is.null(x)) d else x
}
ifempty <- function(x, d){
  if(isEmpty(x)) d else x
}

null2String <- function(x){
  ifnull(x,"")
}
empty2NULL <- function(x){
  ifempty(x,NULL)
}

getDefaultMeasures <- function(dat){
  names(dat)[sapply(dat, function(x) typeof(x)=="double")]
}

getDefaultFieldsList <- function(dat){
  x <- lapply(names(dat), function(n) reactiveValues('name'=n, 'type'=typeof(dat[[n]])))
  names(x) <- names(dat)
  x
}

convertSheetNameToDatName <- function(sheetName){
  paste(sheetName, '(Aggregated Data)', sep=' ')
}

names2formula <- function(nms){
  if(!isEmpty(nms)){
    paste(nms, collapse=" + ")
  } else " . "
}

isFieldUninitialized <- function(obj, field){
  class(obj[[field]])=="uninitializedField"
}

are.vectors.different <- function(x, y){
  if(isEmpty(x)){
    !isEmpty(y)
  } else {
    isEmpty(y) || any(x!=y)
  }
}

## convert d so that the specified columns of d are measures and the rest are dims
## measures: can be either logical or charecter vector
forceMeasures <<- function(d, measures){
  if(!is.logical(measures)) measures <- names(d) %in% measures
  for(n in seq_along(measures)){
    if(measures[n]){
      if(!is.numeric(d[[n]])) d[[n]] <- as.numeric(d[[n]])
    } else {
      if(!is.factor(d[[n]])) d[[n]] <- as.factor(d[[n]])
    }
  }
  d
}

## list with reference semantics
## for later use (challenge: how to delete a field dynamically similarly to deleting a list item by setting it to NULL)
refList <- setRefClass("refList")
names.refList <- function(x) ls(x)[-1] # get rid of "getClass"

DatClass <- setRefClass("DatClass", fields=c("staticProperties","dynamicProperties","datR","fieldNames","moltenDat","moltenNames"),
                        methods=list(setDatDependencies=function(){
                          fieldNames <<- reactive({
                            if(length(dynamicProperties[['fieldsList']])){
                              x <- names(dynamicProperties[['fieldsList']])
                              names(x) <- make.unique(sapply(dynamicProperties[['fieldsList']],
                                                             function(y) y[['name']]), sep='_')
                              x
                            } else c()
                          })
                          datR <<- reactive({
                            if(is.null(dynamicProperties[['dat']])){
                              ## fetch from database etc.

                            } else {
                              dat <- forceMeasures(dynamicProperties[['dat']],
                                             dynamicProperties[['measures']])
                              label(dat, self=FALSE) <- names(fieldNames())
                              dat
                            }
                          })

                          measureName <- 'MeasureNames'
                          moltenDat <<- reactive({
                            if(!isEmpty(dynamicProperties[['measures']])){
                              melt(datR(), measure.vars=dynamicProperties[['measures']],
                                   variable_name=measureName)
                            }
                          })
                          moltenNames <<- reactive({
                            x <- setdiff.c(fieldNames(), dynamicProperties[['measures']])
                            x[measureName] <- measureName
                            x['MeasureValues'] <- MoltenMeasuresName
                            x
                          })
                        },
                        removeDatDependencies=function(){
                          datR <<- NULL; fieldNames <<- NULL; moltenDat <<- NULL; moltenNames <<- NULL
                        }))

createNewDatClassObj <- function(dat=NULL, name='Data', nameOriginal=NULL, type='file'){
  x <- DatClass$new('staticProperties'=list('type'=type, 'nameOriginal'=nameOriginal))
  if(is.null(dat)){
    x[['dynamicProperties']] <- reactiveValues('fieldsList'=list())
  } else {
    activeField <- if(length(names(dat))) names(dat)[1] else ''
    x[['dynamicProperties']] <- reactiveValues('dat'=dat, 'name'=name,
                                               'fieldsList'=getDefaultFieldsList(dat),
                                               'activeField'=activeField,
                                               'measures'=getDefaultMeasures(dat))
  }
  x$setDatDependencies()
  x
}


SheetClass <- setRefClass("SheetClass",
                          fields=c("dynamicProperties","datR",
                                   "fieldNames","measuresR","plotCore","plotR",
                                   "tableR","layerNames"))
createNewLayer <- function(){
  reactiveValues('geom'='point', 'statType'='identity', 'yFun'='sum', 'layerPositionType'='identity',
                 'activeAes'='aesX',
                 'aesList'=sapply(AesChoicesSimpleList,
                                  function(x) reactiveValues('aesAggregate'=FALSE,'aesDiscrete'=TRUE,'aesMapOrSet'='map'), simplify=FALSE))
}
createNewSheetObj <- function(name='Sheet'){
  SheetClass$new(
    'dynamicProperties'=reactiveValues(
      'name'=name,
      'datId'='', 'combineMeasures'=FALSE, 'outputType'='plot',
      'columns'='', 'colChoices'='',
      'rows'='', 'rowChoices'='',
      'outputTable'=NULL,
      'outputDataframe'=NULL,
      'layerList'=list(
        'Plot'=createNewLayer()),
      'activeLayer'='Plot'))
}



require(stringr)

#Rotor 1
I     <- list("EKMFLGDQVZNTOWYHXUSPAIBRCJ","Q")
names(I) <- c("Enc","Step")

#Rotor 2
II    <- list("AJDKSIRUXBLHWTMCQGZNPYFVOE","E")
names(II) <- c("Enc","Step")

#Rotor 3
III   <- list("BDFHJLCPRTXVZNYEIWGAKMUSQO","V")
names(III) <- c("Enc","Step")

#Rotor 4
IV    <- list("ESOVPZJAYQUIRHXLNFTGKDCMWB","J")
names(IV) <- c("Enc","Step")

#Rotor 5
V     <- list("VZBRGITYUPSDNHLXAWMJQOFECK","Z")
names(V) <- c("Enc","Step")

#Rotor 6
VI    <- list("JPGVOUMFYQBENHZRDKASXLICTW",c("Z","M"))
names(V) <- c("Enc","Step")

#Rotor 7
VII   <- list("NZJHGRCXMYSWBOUFAIVLPEKQDT",c("Z","M"))
names(VII) <- c("Enc","Step")

#Rotor 8
VIII  <- list("FKQHTLXOCBJSPDZRAMEWNIUYGV",c("Z","M"))
names(VIII) <- c("Enc","Step")

#Rotor Beta
Beta  <- list("LEYJVCNIXWPBQMDRTAKZGFUHOS",NULL)
names(Beta) <- c("Enc","Step")

#Rotor Gamma
Gamma <- list("FSOKANUERHMBTIYCWLQPZXVGJD",NULL)
names(Gamma) <- c("Enc","Step")

RefB  <- "YRUHQSLDPXNGOKMIEBFZCWVJAT"
RefC  <- "FVPJIAOYEDRZXWGCTKUQSBNMHL"

RefBt <- "ENKQAUYWJICOPBLMDXZVFTHRGS"
RefCt <- "RDOBJNTKVEHMLFCWZAXGYIPSUQ"

C26 <- function(x){
  if(x < 1) x <- 26 + x
  if(x >26) x <- x - 26
  return(x)
}

Enigma <- function(Rotors = list(III,II,I), RingSetting = c(1,1,1), RotorPos = c("A","A","A"), Reflector = RefB, Plugboard = NULL, Text = "HENK"){
  
  Rotor1 <- strsplit(Rotors[[length(Rotors)]]$Enc, "")[[1]]
  Rotor1 <- cbind(Rotor1,LETTERS)
  Rotor1T<- Rotors[[length(Rotors)]]$Step
  
  Rotor2 <- strsplit(Rotors[[length(Rotors) - 1]]$Enc, "")[[1]]
  Rotor2 <- cbind(Rotor2,LETTERS)
  Rotor2T<- Rotors[[length(Rotors) - 1]]$Step
  
  Rotor3 <- strsplit(Rotors[[length(Rotors) - 2]]$Enc, "")[[1]]
  Rotor3 <- cbind(Rotor3,LETTERS)
  Rotor3T<- Rotors[[length(Rotors) - 2]]$Step
  
  
  if(length(Rotors) == 4){
    Rotor4 <- strsplit(Rotors[length(Rotors) - 3]$Enc, "")[[1]]
    Rotor4 <- cbind(Rotor4,LETTERS)
  }
  
  RingSetting1 <- RingSetting[length(RingSetting)]
  RingSetting2 <- RingSetting[length(RingSetting)-1]
  RingSetting3 <- RingSetting[length(RingSetting)-2]
  if(length(RingSetting) == 4) RingSetting4 <- RingSetting[length(RingSetting)-3]
  
#   Rotor1 <- cbind(Rotor1,c(LETTERS[RingSetting1:26],LETTERS[0:(RingSetting1-1)]))
#   Rotor2 <- cbind(Rotor2,c(LETTERS[RingSetting2:26],LETTERS[0:(RingSetting2-1)]))
#   Rotor3 <- cbind(Rotor3,c(LETTERS[RingSetting3:26],LETTERS[0:(RingSetting3-1)]))
  
  
  Reflec <- strsplit(Reflector, "")[[1]]
  Reflec <- cbind(Reflec,LETTERS)
  
  Plugb <- cbind(LETTERS,LETTERS)
  if(!is.null(Plugboard)){
    for(s in 1:length(Plugboard)){
      SwapL <- strsplit(Plugboard[[s]],"")[[1]]
      Plugb[Plugb[,1]==SwapL[1],2] <- SwapL[2]
      Plugb[Plugb[,1]==SwapL[2],2] <- SwapL[1]
    }
  }
  
  TextIn <- strsplit(Text, "")[[1]]
  
  RotorPos1 <- 
  RotorPos2 <- 
  RotorPos3 <- 
  
  for(i in 1:length(TextIn)){
    
    RotorPos1 <- C26(RotorPos1 + 1)
    
    if(any(LETTERS[C26(RotorPos1 - 1)] == Rotor1T)) RotorPos2 <- C26(RotorPos2 + 1)
    
    if(any(LETTERS[C26(RotorPos1 - 2)] == Rotor1T) & 
         any(LETTERS[C26(RotorPos2)] == Rotor2T)){
      RotorPos3 <- C26(RotorPos3 + 1)
      RotorPos2 <- C26(RotorPos2 + 1)
    }	
    
    if(length(RotorPos) == 4) c(RotorPos4,RotorPos3,RotorPos2,RotorPos1)
    if(length(RotorPos) == 3) c(RotorPos3,RotorPos2,RotorPos1)
    
    inpL <- TextIn[i]
    inpL <- Plugb[Plugb[,1] == inpL,2]
    
    inp1 <- C26(which(LETTERS == inpL) + (RotorPos1 - 1) - (RingSetting1 - 1))
    out1 <- Rotor1[Rotor1[,2] == LETTERS[inp1], 1]
    out1 <- C26(which(LETTERS == out1) - (RotorPos1 - 1) + (RingSetting1 - 1))
    
    inp2 <- LETTERS[C26(out1 + (RotorPos2 - 1) - (RingSetting2 - 1))]
    out2 <- Rotor2[Rotor2[,2] == inp2, 1]
    out2 <- C26(which(LETTERS == out2) - (RotorPos2 - 1) + (RingSetting2 - 1))
    
    inp3 <- LETTERS[C26(out2 + (RotorPos3 - 1) - (RingSetting3 - 1))]
    out3 <- Rotor3[Rotor3[,2] == inp3, 1]
    out3 <- C26(which(LETTERS == out3) - (RotorPos3 - 1) + (RingSetting3 - 1))
    
    if(length(RotorPos) == 4){
      inp4 <- LETTERS[C26(out3 + (RotorPos4 - 1) - (RingSetting4 - 1))]
      out4 <- Rotor4[Rotor4[,2] == inp4, 1]
      out4 <- C26(which(LETTERS == out4) - (RotorPos4 - 1) + (RingSetting4 - 1))
      
      outR <- Reflec[Reflec[,2] == LETTERS[out4], 1]
      outR <- which(LETTERS == outR)
      
      inp4 <- LETTERS[C26(outR + (RotorPos4 - 1))]
      out4 <- Rotor4[Rotor4[,1] == inp4, 2]
      outR <- C26(which(LETTERS == out4) - (RotorPos4 - 1))
    } else {
      outR <- Reflec[Reflec[,2] == LETTERS[out3], 1]
      outR <- which(LETTERS == outR)
    }
    
    inp3 <- LETTERS[C26(outR + (RotorPos3 - 1))]
    out3 <- Rotor3[Rotor3[,1] == inp3, 2]
    out3 <- C26(which(LETTERS == out3) - (RotorPos3 - 1))
    
    inp2 <- LETTERS[C26(out3 + (RotorPos2 - 1))]
    out2 <- Rotor2[Rotor2[,1] == inp2, 2]
    out2 <- C26(which(LETTERS == out2) - (RotorPos2 - 1))
    
    inp1 <- LETTERS[C26(out2 + (RotorPos1 - 1))]
    out1 <- Rotor1[Rotor1[,1] == inp1, 2]
    out1 <- C26(which(LETTERS == out1) - (RotorPos1 - 1))
    outL <- LETTERS[out1]
    outL <- Plugb[Plugb[,2] == outL,1]
    
    
    if(length(RotorPos) == 4) c(RotorPos4,RotorPos3,RotorPos2,RotorPos1)
    if(length(RotorPos) == 3) c(RotorPos3,RotorPos2,RotorPos1)   
    
    print(outL)
  }
}

setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_name <- resource_key
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        list(value = do.call(base::source, source_args)$value,
             preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
library(pbdMPI, quiet = TRUE)
library(pbdDMAT, quiet = TRUE)
library(pbdADIOS, quiet = TRUE)
library(raster, quiet=TRUE)
library(ggplot2, quiet=TRUE)
library(grid, quiet=TRUE)

## begin function definitions

raster_plot <- function(x, nrow, ncol, basename="raster", sequence=1, swidth=3)
{
    x <- data.frame(rasterToPoints(raster(matrix(x, nrow, ncol),
                                          xmn=0, xmx=ncol, ymn=0, ymx=nrow)))
    names(x) <- c("x", "y", basename)
    png(paste(basename, "_", formatC(sequence, width=swidth, flag=0), "_",
              comm.rank(), ".png", sep=""))
    print(ggplot(x, aes_string(x="x", y="y", fill=basename)) + geom_raster() +
          theme_minimal() + theme(axis.text.x=element_blank(),
                                  axis.ticks.x=element_blank(),
                                  axis.title.x=element_blank(),
                                  legend.position="none",
                                  plot.margin=unit(c(0,0,0,0),"cm")
                                  )
          )
    dev.off()
}
## end function definitions


## Initialize MPI and ADIOS 

init.grid() ## MPI/DMAT intializer
adios.init.noxml() ## Write without using XML ## WR
adios.read.init.method("ADIOS_READ_METHOD_BP", params="verbose=3") ## Initialize reading method

adios.allocate.buffer(300) ## allocating size for ADIOS application in MB ## WR

groupname <- "restart" ## WR
adios_group_ptr <-  adios.declare.group(groupname,"") ## WR

adios.select.method(adios_group_ptr, "MPI", "", "") ## WR
filename <- "/Users/pragnesh/5.1.1/SGN_pbdADIOS/SGN_23_dec/pbdADIOS/demo/test_heat_w.bp" ## WR


## specify and open file for reading
dir.data <- "/Users/pragnesh/5.1.1/SGN_pbdADIOS/dataset" 
file <- paste(dir.data, "heat.bp", sep="/")

timeout.read <- 1 ## in sec
read.file.ptr <- adios.read.open(file, adios.timeout=timeout.read, "ADIOS_READ_METHOD_BP",
                          adios.lockmode="ADIOS_LOCKMODE_NONE") ## Calling adios read function

## select variable to read
variable <- "T"

## get variable dimensions
varinfo = adios.inq.var(read.file.ptr, variable)
block <- adios.inq.var.blockinfo(read.file.ptr, varinfo)

#comm.print("Before custom.inq.var.ndim")


ndim <- custom.inq.var.ndim(varinfo)
dims <- custom.inq.var.dims(varinfo)

## get dimensions and split
#source("pbdADIOS/tests/partition.r")
source("/Users/pragnesh/5.1.1/SGN_pbdADIOS/SGN_23_dec/pbdADIOS/demo/partition.r")

g.dim <- dims # global.dim on write
split <- c(TRUE, FALSE)
my.data.partition <- data.partition(seq(0, 0, along.with=g.dim), g.dim, split)
my.dim <- my.count <- my.data.partition$my.dim # local.dim on write
my.start <- my.data.partition$my.start # local.offset on write
my.grid <- my.data.partition$my.grid

adios.define.var(adios_group_ptr, "T", "", toString(my.dim), toString(g.dim), toString(my.start))  ## WR

errno <- 0 # Default value 0
steps <- 0
retval <- 0
bufsize <- 10
buffer <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a0 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a1 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a2 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
rhs <- cbind(rep(1, bufsize), poly(1:bufsize, degree=2))

while(errno != -21) { ## This is hard-coded for now. -21=err_end_of_stream
    steps = steps + 1 ## Double check with Norbert. Should it start with 1 or 2

    ## set reading bounding box
    adios.selection  <- adios.selection.boundingbox(ndim, my.start, my.count)
    comm.print("Selection.boundingbox complete ...")
    
    ## schedule the read
    adios.data <- adios.schedule.read(varinfo, my.start, my.count, read.file.ptr,
                                      adios.selection, variable, 0, 1)
    comm.print("Schedule read complete ...")
    
    ## perform the read
    adios.perform.reads(read.file.ptr, 1)
    comm.print("Perform read complete ...")

    data_chunk <- custom.data.access(adios.data, adios.selection, varinfo)
    comm.print("Data access complete ...")

    ## print a few to verify
    comm.cat("first 5:", head(data_chunk, 5),"\n")
    comm.cat("last 5:", tail(data_chunk, 5),"\n")

    ## shape into matrix with first dim as rows
    ## local reshape dimensions
    my.ncol <- prod(my.dim[2])
    my.nrow <- my.dim[1]
    ldim <- c(my.nrow, my.ncol)

    ## global reshape dimensions
    g.ncol <- prod(g.dim[2])
    g.nrow <- g.dim[1]
    gdim <- c(g.nrow, g.ncol)
    
    ## now glue into a ddmatrix
    ##  x <- matrix(data_chunk, nrow=my.nrow, ncol=my.ncol, byrow=FALSE)
    ##  X <- new("ddmatrix", Data=x, dim=gdim, ldim=ldim, bldim=ldim, ICTXT=2)

    ## Fit a quadratic to a moving window of 10 steps
    ## Actually don't need the ddmatrix for this and can go straight
    ## from data_chunk into buffer matrix
    buffer <- rbind(buffer[-1, ], data_chunk)

    ## plot the original local matrix (swapping row to col - C to R)
    raster_plot(data_chunk, my.ncol, my.nrow, "T", steps)
    
    ## fit data and plot three coefficient raster plots
    if(steps >= bufsize)
        {
            fit <- lm.fit(rhs, buffer)$coefficients
    ##         raster_plot(fit[1, ], my.ncol, my.nrow, "a0", steps)
             raster_plot(fit[2, ], my.ncol, my.nrow, "a1", steps)
             raster_plot(fit[3, ], my.ncol, my.nrow, "a2", steps)
      
    ## All these work fine!
    ##    X <- as.blockcyclic(X, bldim=c(4, 4))
    ##    X.pc <- prcomp(X)
    ##    comm.print(X.pc)
    
    ##
    ## Here, write out the results of the analysis
    a0 <- fit[1, ]
    a1 <- fit[2, ]
    a2 <- fit[3, ]
    ## now use adios to write (T, a0, a1, a2). All are with dimensions:
    ##       global.dim = g.dim
    ##       local.dim = my.dim = my.count
    ##       local.offset = my.start
  
     adios_file_ptr <- adios.open(groupname, filename, "a") ## WR

     groupsize <- object.size(data_chunk) ## Ask george       ## WR

     adios.group.size(adios_file_ptr, groupsize) ## WR
     adios.write(adios_file_ptr, "T", data_chunk) ## WR
     adios.close(adios_file_ptr) ## WR
     barrier() ## WR

    ## insert adios writing code here  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
     }
    
    ## try to get more data
    adios.advance.step(read.file.ptr, 0, adios.timeout.sec=1)
    comm.print(paste("Done advance.step", steps, "..."))
     
    ## check errors
    errno <- adios.errno()
    #comm.cat("Error Num",errno, "\n")

    ## if error is timeout (or EOF)
    if(errno == -22){ #-22 = err_step_notready
        comm.cat(comm.rank(), "Timeout waiting for more data. Quitting ...\n")
        break
    }
if(steps > 20) break
} # While end 

comm.print("Broke out of loop ...")
adios.read.close(read.file.ptr)
comm.print("File closed")
adios.read.finalize.method("ADIOS_READ_METHOD_BP")
comm.print("Finalized adios ...")

adios.finalize(pbdMPI:::comm.rank()) # ADIOS finalize ## WR

finalize() # pbdMPI finalize

#!/usr/bin/r
# r --slave --quiet --args *.dat < boxplot.r
file <- commandArgs(trailingOnly=T)[1]
print( file )
t <- read.table(
        file, 
        sep="\t",
        header=T,
        fill=T
        )

base <- sub( "(^[^.]+).*", "\\1", file )
image <- paste( base, "png", sep="." )
png( image )

p <- list(
        boxwex = 0.1,
        ylab   = "Times, s"
        )
boxplot( t, pars=p )

#'@title arrange_ggplot2
#'@description
#'Arranges ggplot2 plot objects in a grid using code from Stephen Turner's website.
#'from http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html
#'use pdf(); arrange(p1,p2,ncol=1); dev.off() to save the plot to a file
#'@param list list of plot objects
#'@param ncol number of columns, can be null
#'@param nrow number of rows, can be null
#'@param as.table boolean, determines order in grid
#'@export

arrange_ggplot2 <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
  library(ggplot2)
  library(grid)
  vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
  
  dots <- list(...)
  n <- length(dots)
  if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
  if(is.null(nrow)) { nrow = ceiling(n/ncol)}
  if(is.null(ncol)) { ncol = ceiling(n/nrow)}
  ## NOTE see n2mfrow in grDevices for possible alternative
  grid.newpage()
  pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
  ii.p <- 1
  for(ii.row in seq(1, nrow)){
    ii.table.row <- ii.row	
    if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
    for(ii.col in seq(1, ncol)){
      ii.table <- ii.p
      if(ii.p > n) break
      print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
      ii.p <- ii.p + 1
    }
  }
}

#'@title vertical_dotchart
#'@description
#'Produces a vertical dot chart, with a metric variable giving the length of a horizontal 
#'line segment and a dot colored by a grouping variable.  Each row in the data frame becomes a 
#'row in the dotchart.  The y variable is a label for each row, and rows can be grouped
#'by a grouping variable.  The plot can be sorted in descending order of the x metric variable,
#'or grouped by the grouping variable and then sorted.   
#'
#'@param df Data frame to be plotted
#'@param x_var Name of the metric variable to be plotted, as a string
#'@param x_label Name of the metric variable as a plot legend string
#'@param y_var Name of the categorical variable labeling each row in the data frame
#'@param y_label Name of the categorical variable, as a plot legend string
#'@param y_group_var Name of a categorical variable which groups the rows
#'@param legend_title Title of the legend for groups, defaults to "Experiment Group"
#'@param sort.by.xvar Boolean flag to sort rows by the metric variable, defaults to TRUE
#'@param group.by.ygroup Boolean flag to sort groups of rows by the grouping variable, defaults to TRUE
#'@return ggplot2 object
#'@export

vertical_dotchart <- function(df, 
                              x_var = xvar, 
                              x_label = xlabel, 
                              y_var = yvar, 
                              y_label = "Experiment", 
                              y_group_var = NULL, 
                              legend_title = "Experiment Group",
                              sort.by.xvar = TRUE, 
                              group.by.ygroup = TRUE) {
  
  require(ggplot2)
  require(ggthemes)

  # prevent a conflict if the user doesn't set the flag but leaves off a grouping variable
  if(is.null(y_group_var)) {
    group.by.ygroup = FALSE
  }
  
  if(sort.by.xvar == TRUE) {
      df$yvar_sorted <- reorder(df[[y_var]], df[[x_var]])
      plt <- ggplot(df, aes_string(x = x_var, y = "yvar_sorted")) 
    } else {
      plt <- ggplot(df, aes_string(x = x_var, y = y_var))
    }

  plt <- plt + ylab(y_label)
  plt <- plt + xlab(x_label)
  
  if(!is.null(y_group_var)) {
    plt <- plt + geom_segment(aes_string(yend = "yvar_sorted"), xend = 0, color = "grey50")
    plt <- plt + geom_point(size = 3, aes_string(color = y_group_var)) + labs(color = legend_title)
  } else {
    plt <- plt + geom_segment(aes_string(yend = y_var), xend = 0, color = "grey50")
    plt <- plt + geom_point(size = 3)
  }

  plt <- plt + theme_pander()
  plt <- plt + theme(panel.grid.major.x = element_blank(),
                     panel.grid.minor.x = element_blank(),
                     strip.background = element_blank(), strip.text = element_blank())
  if(group.by.ygroup == TRUE) {
    form <- as.formula(paste(y_group_var, "~", ".", sep = " "))
    plt <- plt + facet_grid(form, scales = "free_y", space = "free_y")
  }
  
  plt
}


library(proto)
StatEllipse <- proto(ggplot2:::Stat,
{
  required_aes <- c("x", "y")
  default_geom <- function(.) GeomPath
  objname <- "ellipse"
  
  calculate_groups <- function(., data, scales, ...){
    .super$calculate_groups(., data, scales,...)
  }
  calculate <- function(., data, scales, level = 0.75, segments = 51,...){
    dfn <- 2
    dfd <- length(data$x) - 1
    if (dfd < 3){
      ellipse <- rbind(c(NA,NA))  
    } else {
      require(MASS)
      v <- cov.trob(cbind(data$x, data$y))
      shape <- v$cov
      center <- v$center
      radius <- sqrt(dfn * qf(level, dfn, dfd))
      angles <- (0:segments) * 2 * pi/segments
      unit.circle <- cbind(cos(angles), sin(angles))
      ellipse <- t(center + radius * t(unit.circle %*% chol(shape)))
    }
    
    ellipse <- as.data.frame(ellipse)
    colnames(ellipse) <- c("x","y")
    return(ellipse)
  }
}
)

#' @title stat_ellipse
#' @description 
#' ggplot2 confidence ellipse from https://raw.github.com/JoFrhwld/FAAV/master/r/stat-ellipse.R
#' @export
stat_ellipse <- function(mapping=NULL, data=NULL, geom="path", position="identity", ...) {
  require(proto)
  StatEllipse$new(mapping=mapping, data=data, geom=geom, position=position, ...)
}



# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context = NULL, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (remember) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()

    # Set the first cache environment
    if (length(stages) > 0) {
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage))
          function(...) stage$run(verbose = verbose, .depth = .depth + 1, ...)
        else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) stage$run(...)
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]]))
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        function(...)
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message)
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      before_env <-
        if (nested_run) run_stage(..., remember_flag = TRUE)$before
        else { # a leaf / terminal node
          if (is.null(env <- stages[[stage_index]]$cached_env))
            stop("Cannot run this stage yet because some previous stages have ",
                 "not been executed.")

          # Restart execution from cache, so set context to the cached environment.
          copy_env(context, env)
          env
        }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) run_stage(...) 
    }
    else if (remember) run_stage(..., remember_flag = FALSE)
    else run_stage(...)

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      node <- treeSkeleton$new(stages[[stage_index]])$successor()
      if (!is.null(node)) # Prepare a cache for the future!
        copy_env(node$object$cached_env <- new.env(parent = parent.env(context)), context)
      # TODO: Remove this hack used for printing
      else {
        root <- .self$.root()
        root$.finished <- TRUE
      }
    }

    if (display_message)
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
  }

  if (remember && remember_flag) list(before = before_env, after = context)
  else invisible(TRUE)
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    # TODO: Match by name *OR* index
    if (stagenames[[stage_index]] %in% names(stages)) {
      # If both are stageRunners, try to coalesce our sub-stages.
      if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          is.stagerunner(other_runner$stages[[stage_index]])) {
          stages[[names(stages)[stage_index]]]$coalesce(
            other_runner$stages[[stage_index]])
      # If both are not stageRunners, copy the cached_env if and only if
      # the stored function and its environment are identical
      } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          !is.stagerunner(other_runner$stages[[stage_index]]) &&
          !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
          #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
          #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
          # This is way too tricky and far beyond my abilities..
          #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
          #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
          ) {
        stages[[names(stages)[stage_index]]]$cached_env <<-
          new.env(parent = parent.env(context))
        if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
            is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
          copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                   other_runner$stages[[stage_index]]$cached_env)
          stages[[names(stages)[stage_index]]]$executed <<- 
            other_runner$stages[[stage_index]]$executed
        }
      }
    }
  })
  .set_parents()
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL


setClass('tracked_environment')

#' @export
setClassUnion('anyEnvironment', c('environment', 'tracked_environment'))

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'anyEnvironment', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#stageRunnerNode <- function(fn, parent_obj, parent_env = parent.frame()) {
#  env <- new.env(parent = parent_env)
#  class(env) <- c('stageRunnerNode', class(env))
#  env$fn <- fn
#
#  # Make a stageRunnerNode commensurate with treeSkeleton
#  # parent will be set later
#  if (!missing(parent_obj)) attr(env, 'parent') <- parent_obj
#  attr(env, 'children') <- list()
#
#  env
#}

#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      if (is(.context, 'tracked_environment')) {
        objectdiff::commit(.context) <<- ''
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context = NULL, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (remember) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()

    # Set the first cache environment
    if (length(stages) > 0) {
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage))
          function(...) stage$run(verbose = verbose, .depth = .depth + 1, ...)
        else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) stage$run(...)
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]]))
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        function(...)
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message)
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      before_env <-
        if (nested_run) run_stage(..., remember_flag = TRUE)$before
        else { # a leaf / terminal node
          if (is.null(env <- stages[[stage_index]]$cached_env))
            stop("Cannot run this stage yet because some previous stages have ",
                 "not been executed.")

          # Restart execution from cache, so set context to the cached environment.
          copy_env(context, env)
          env
        }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) run_stage(...) 
    }
    else if (remember) run_stage(..., remember_flag = FALSE)
    else run_stage(...)

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      node <- treeSkeleton$new(stages[[stage_index]])$successor()
      if (!is.null(node)) # Prepare a cache for the future!
        copy_env(node$object$cached_env <- new.env(parent = parent.env(context)), context)
      # TODO: Remove this hack used for printing
      else {
        root <- .self$.root()
        root$.finished <- TRUE
      }
    }

    if (display_message)
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
  }

  if (remember && remember_flag) list(before = before_env, after = context)
  else invisible(TRUE)
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    # TODO: Match by name *OR* index
    if (stagenames[[stage_index]] %in% names(stages)) {
      # If both are stageRunners, try to coalesce our sub-stages.
      if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          is.stagerunner(other_runner$stages[[stage_index]])) {
          stages[[names(stages)[stage_index]]]$coalesce(
            other_runner$stages[[stage_index]])
      # If both are not stageRunners, copy the cached_env if and only if
      # the stored function and its environment are identical
      } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          !is.stagerunner(other_runner$stages[[stage_index]]) &&
          !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
          #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
          #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
          # This is way too tricky and far beyond my abilities..
          #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
          #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
          ) {
        stages[[names(stages)[stage_index]]]$cached_env <<-
          new.env(parent = parent.env(context))
        if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
            is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
          copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                   other_runner$stages[[stage_index]]$cached_env)
          stages[[names(stages)[stage_index]]]$executed <<- 
            other_runner$stages[[stage_index]]$executed
        }
      }
    }
  })
  .set_parents()
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'environment', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#stageRunnerNode <- function(fn, parent_obj, parent_env = parent.frame()) {
#  env <- new.env(parent = parent_env)
#  class(env) <- c('stageRunnerNode', class(env))
#  env$fn <- fn
#
#  # Make a stageRunnerNode commensurate with treeSkeleton
#  # parent will be set later
#  if (!missing(parent_obj)) attr(env, 'parent') <- parent_obj
#  attr(env, 'children') <- list()
#
#  env
#}

#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

REBOL [
    Title:   "Rectangle-pack"
    Date:    14-Feb-2012/20:39:44+1:00
    Name:    'rectangle-pack
    Version: 1.0.0
	History: [
		1.0.0 27-Oct-2010 {Initial version}
		1.1.0 14-Feb-2012 {
			Added pow2-rectangle-pack and pow2-box-pack functions.
			It's possible to specify pre-sorting method} 
	]
    File: %rectangle-pack.r
    Author: "Oldes"
    Owner: none
    Rights: none
    Needs: none
    Tabs: none
    Usage: [
		probe pow2-rectangle-pack [
			120x10 "img1"
			125x5  "img2"
			100x4  "img3"
		]
		probe pow2-box-pack [
			120x10 "img1"
			125x5  "img2"
			100x4  "img3"
		]
	]
    Purpose: none
    Comment: {
    This code was inspired by this page:
    http://www.blackpawn.com/texts/lightmaps/default.html
    It's not exactly the same as this one is not using recursion, but works fine for my purposes.
    Here are for example packed bitmaps into 256x256 texture:
    http://box.lebeda.ws/~hmm/rebol/rectangle-pack-result.jpg
    }
    History: none
    Language: none
    Type: none
    Email: none
]

ctx-rectangle-pack: context [
	padding: 1x1
	max-size: 8192x8192
	verbose: 0
	
	round-to-pow2: func[v /local p][ repeat i 14 [if v <= (p: 2 ** i) [return p]] none]
	
	max-pow2-size: func[data /local maxpair ][
		maxpair:  0x0
		foreach [size id] data [
			maxpair: max maxpair size
		]
		maxpair/x: to-integer round-to-pow2 maxpair/x
		maxpair/y: to-integer round-to-pow2 maxpair/y
		maxpair
	]
	min-pow2-size: func[data /local minpair ][
		minpair:  0x0
		foreach [size id] data [
			minpair: max minpair size
		]
		minpair/x: to-integer round-to-pow2 minpair/x
		minpair/y: to-integer round-to-pow2 minpair/y
		minpair
	]
	pow2-area: func[size][
		(round-to-pow2 size/x) * (round-to-pow2 size/y)
	]
	
	set 'pow2-box-pack func[images /method sort-method /local size data-to-process result][

		size: min-pow2-size images
		size: as-pair tmp: min size/x size/y tmp
		
		data-to-process: copy images

		while [
			not empty? second result: rectangle-pack/method data-to-process size sort-method
		][
			size: size * 2
			;print reform ["retry with size:" size]
		]
		reduce [size result]
	]
	
	set 'pow2-rectangle-pack func[images /method sort-method /local size data-to-process result][

		minsize: min-pow2-size images
		data-to-process: copy images

		minArea:   to-integer #{7FFFFFFF}
		minResult: none
		
		size: minsize
		until [
			until [
				result: rectangle-pack/method data-to-process size sort-method
				area: size/x * size/y
				;print ["test size:" size]
				if empty? second result [
					if minArea >= area [
						;print ["???" result/3  ]
						if any [
							none? minResult
							minArea > area
							(pow2-area size) < (pow2-area minResult/1)
							all [
								(pow2-area size) = (pow2-area minResult/1)
								any [
									size/x = size/y
									(max size/x size/y) < (max minResult/1/x minResult/1/y)
								]
							]
						][
							minArea: area
							minResult: reduce [size result]
							;print ["NEW MIN AREA:" area]
						]
					]
					break
				]
				size/x: size/x * 2
				;print ["?X" area minArea]
				not all [
					area < minArea
					size/x <= max-size/x
				]
			]
			size/y: size/y * 2
			size/x: minsize/x
			area: pow2-area size
			;print ["?Y" area minArea size/y]
			not all [
				area <= minArea
				size/y <= max-size/y
			]
		]
		
		;print "-----------"
		;probe minArea
		unless minResult [
			probe result
			minResult: reduce [max-size result]
		]
		minResult
	]

	set 'rectangle-pack func[
		"Takes block of sizes and ids and tries to pack them to specified area, returns block with placed and skiped data"
		size-data   [block!] "block with [size1 id1 size2 id2 ...]"
		target-area [pair! ] "Size of the target area"
		/method sort-method 
		/local placed skiped free-bins free-area placed? rw rh rx ry width height
	][
		if verbose > 0 [print ["RECTPACK to size:" target-area]]

		;sort-method: 3 ;louka kytky

		sort/compare/skip size-data func[a b /local oa ob][
			switch/default sort-method [
				2 [
					;precedence: side Y
					case [
						a/y < b/y [ 1]
						a/y > b/y [-1]
						a/x < b/x [ 1]
						a/x > b/x [-1]
						true      [ 0]
					]
				]
				3 [
					;predecence: area
					case[
						(oa: a/x * a/y) > (ob: b/x * b/y) [-1]
						oa < ob                           [ 1]
						true                              [ 0]
					]
				]
				4 [
					;precedence: any side's size
					case[
						(oa: max a/x a/y) > (ob: max b/x b/y) [-1]
						oa < ob                           [ 1]
						true                              [ 0]
					]
				]
			][;default = 1:
				;precedence: side X
				case [
					a/x < b/x [ 1]
					a/x > b/x [-1]
					a/y < b/y [ 1]
					a/y > b/y [-1]
					true      [ 0]
				]
			]
		] 2
		
		placed:    copy []
		skiped:    copy []
		free-bins: reduce [target-area/x target-area/y 0 0]
		
		foreach [size id] size-data [
			free-bins: head free-bins
			placed?: false
			while [not tail? free-bins][
				set [rw rh rx ry] free-bins
				width:  size/x + padding/x
				height: size/y + padding/y
				either all [
					width <= rw
					height <= rh
				][
					repend placed [as-pair rx ry size id]
					placed?: true
					change/part free-bins reduce either (rw  - width) > (rh - height) [
						[
							free-bins/1 - width
							free-bins/2
							free-bins/3 + width
							free-bins/4
							width
							free-bins/2 - height
							free-bins/3
							free-bins/4 + height
						]
					][
						[
							free-bins/1 - width
							height
							free-bins/3 + width
							free-bins/4
							free-bins/1
							free-bins/2 - height
							free-bins/3
							free-bins/4 + height
						]
					] 4
					break
				][
					free-bins: skip free-bins 4
				]
			]
			unless placed? [
				;print ["NOT FOUND SPACE FOR:" size "^/^-" id]
				repend skiped [size id]
			]
		]
		free-area: 0
		foreach [rw rh rx ry] free-bins [
			free-area: free-area + (rw * rh)
		]

		new-line/skip placed true 3
		reduce [placed skiped free-area]
	]
]

REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	;--                 [objects images shapes sounds strings]
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   40]
		%PlanetaZluta      [600     1300   100    250   40]
		%PlanetaTermiti    [600     1300   100    290   40]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 300 40]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 0.5 * length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script exe console files][
		script: temp-dir/red-console.red
		exe: temp-dir/console
		
		if Windows? [append exe %.exe]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < build-date				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			
			files: [%help.red %input.red %wcwidth.reds %win32.reds %POSIX.reds]
			
			foreach file files [write temp-dir/:file read-cache console/:file]

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			foreach file files [delete temp-dir/:file]

			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and 
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/", 
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#' 
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    if (name_exists("object$output$options$data")) {
      data_restore_on_exit <- object$output$options$data
      on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
      object$output$options$data <- NULL
    }
    if (name_exists("object$output$options$label")) {
      label_restore_on_exit <- object$output$options$label
      on.exit(object$output$options$label <- label_restore_on_exit, add = TRUE)
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

 # TODO: (RK) Read default_options in from config, so a user can
 # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- list(data = switch(1 + name_exists("object$output$options$data"), 
                              NULL, object$output$options$data), 
                label = switch(1 + name_exists("object$output$options$label"), 
                               NULL, object$output$options$label))

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == "combined" & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="#034b87", og.score="gray98") 
	colorMid = list(combined.score="gray98"),
	colorHigh = list(combined.score="#880000", ts.score="gray98", og.score="#880000")

	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=16, face="bold"),
	      axis.title.x=element_text(color="gray30", size=16, face="bold"),
	      strip.text.x=element_text(color="gray30", size=16, face="bold"),
	      legend.text=element_text(color="gray30", size=16, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	)
}


REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script exe console][
		script: temp-dir/red-console.red
		exe: temp-dir/console
		
		if Windows? [append exe %.exe]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < build-date				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly=T)
if (length(args) < 1) {
  print("Please pass the CSV file as a command line argument.")
  quit()
}
fpath <- gsub("summary-|.csv$", "", args[1])
print(paste(fpath, ".png", sep=""))

profiles <- read.csv(args[1], header=T)

print(profiles)

f2si2<-function (number, rounding=F, sep=" ") 
{
    lut <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-09, 1e-06, 
        0.001, 1, 1000, 1e+06, 1e+09, 1e+12, 1e+15, 1e+18, 1e+21, 
        1e+24)
    pre <- c("y", "z", "a", "f", "p", "n", "u", "m", "", "k", 
        "M", "G", "T", "P", "E", "Z", "Y")
    ix <- findInterval(number, lut)
    if (ix>0 && lut[ix]!=1) {
        if (rounding==T) {
         sistring <- paste(round(number/lut[ix]), pre[ix], sep=sep)
        }
        else {
         sistring <- paste(number/lut[ix], pre[ix], sep=sep)
        }
    }
    else {
        sistring <- as.character(number)
    }
    return(sistring)
}


xlb <- c("H1", "H2", "H3", "H4", "H5", "Hx", "P1", "P2", "P3", "P4", "P5", "Px")
kpos <- pretty(c(0, max(profiles$suburi_keys)), n=10)
klb <- sapply(kpos, FUN=f2si2, rounding=T, sep="")
spos <- pretty(c(0, max(profiles$profile_size)), n=10)
slb <- sapply(spos, FUN=f2si2, rounding=T, sep="")
tpos <- pretty(c(0, max(profiles$profiling_time/60)), n=10)
tlb <- sapply(tpos, FUN=f2si2, rounding=T, sep="")

keybar <- paste(fpath, "-keys-barplot.png", sep="")
png(keybar, height=500, width=800, pointsize=18)

par(mar=c(5,9,2,2)+0.1)
bplt <- barplot(profiles$suburi_keys, names.arg=profiles$profile_id, horiz=T, las=2, axes=F, xlim=c(0, max(kpos)))#
axis(1, at=kpos, labels=klb)
text(x=profiles$suburi_keys, y=bplt, labels=sapply(profiles$suburi_keys, FUN=f2si2, rounding=T, sep=""), pos=4, offset=0.2, xpd=T)
title(xlab="Number of Sub-URI Keys")

dev.off()


keyline <- paste(fpath, "-keys-lineplot.png", sep="")
png(keyline, height=500, width=800, pointsize=18)

par(mar=c(4,4,2,2)+0.1)
plot(profiles$suburi_keys, type='b', xaxt="n", yaxt="n", ylab="", xlab="", ylim=c(0, max(kpos)))
axis(1, at=c(1:12), labels=xlb)
axis(2, at=kpos, labels=klb)
title(ylab="Number of Sub-URI Keys", xlab="Max segments (H: Host segments, P: Path segments)")

dev.off()


sizeline <- paste(fpath, "-filesize-lineplot.png", sep="")
png(sizeline, height=500, width=800, pointsize=18)

par(mar=c(4,4,2,2)+0.1)
plot(profiles$profile_size, type='b', xaxt="n", yaxt="n", ylab="", xlab="", ylim=c(0, max(spos)))
axis(1, at=c(1:12), labels=xlb)
axis(2, at=spos, labels=slb)
title(ylab="Profile size", xlab="Max segments (H: Host segments, P: Path segments)")

dev.off()


timeline <- paste(fpath, "-time-lineplot.png", sep="")
png(timeline, height=500, width=800, pointsize=18)

par(mar=c(4,4,2,2)+0.1)
plot(profiles$profiling_time/60, type='b', xaxt="n", yaxt="n", ylab="", xlab="", ylim=c(0, max(tpos)))
axis(1, at=c(1:12), labels=xlb)
axis(2, at=tpos, labels=tlb)
title(ylab="Profiling time (minutes)", xlab="Max segments (H: Host segments, P: Path segments)")

dev.off()
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and 
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/", 
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#' 
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      data_restore_on_exit <- object$object$container$output$options$data
      label_restore_on_exit <- object$object$container$output$options$label
      on.exit(object$object$container$output$options$data <- data_restore_on_exit, add = TRUE)
      on.exit(object$object$container$output$opitons$label <- label_restore_on_exit, add = TRUE)
      object$object$container$output$options$data <- NULL
      object$object$container$output$options$label <- NULL
    } else {
      data_restore_on_exit <- object$output$options$data
      label_restore_on_exit <- object$output$options$label
      on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
      on.exit(object$output$opitons$label <- label_restore_on_exit, add = TRUE)
      object$output$options$data <- NULL
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

#  format_function <- function(opts) {
#    environment(common_file_formatter) <- environment()
#    opts <- common_file_formatter(opts)
#    if (is.element('bucket', names(opts)))
#      opts$s3path <- paste0("s3://", opts$bucket, "/")
#    opts
#  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object <- list(data = object$object$container$output$options$data, 
                     label = object$object$container$output$options$label)
    } else {
      object <- list(data = object$output$options$data, 
                     label = object$output$options$label)
    }
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
#!/usr/bin/env Rscript

library(ggplot2)
library(reshape)

hours_m = as.numeric(read.csv("analysis/time-hours-stats.csv",header=F,nrows=1))
hours_stdev = as.numeric(read.csv("analysis/time-hours-stats.csv",
                                  header=F,nrows=1,skip=1))

df <- data.frame(freqs=hours_m,stdev=hours_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=0:23,y=freqs)) +
  xlab("Hour of Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity') +
  #geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-hours-bar.png",width=7,height=6)

hours = read.csv("analysis/time-hours-full.csv",header=F)
df = melt(hours)
p <- ggplot(df, aes(x=value)) +
  stat_ecdf(aes(group = variable)) +
  theme(legend.title=element_blank()) +
  xlab("Number of Hourly Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-hours-ecdf.png",width=7,height=6)

wdays_m = as.numeric(read.csv("analysis/time-wdays-stats.csv",header=F,nrows=1))
wdays_stdev = as.numeric(read.csv("analysis/time-wdays-stats.csv",
                                  header=F,nrows=1,skip=1))
wday_str = c("Mon","Tues","Weds","Thurs","Fri","Sat","Sun")
df <- data.frame(freqs = wdays_m, wdays = factor(wday_str,levels=wday_str),
                 stdev=wdays_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=wdays,y=freqs)) +
  xlab("Week Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(y=freqs)) +
  geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-wdays-bar.png",width=7,height=6)

wdays = read.csv("analysis/time-wdays-full.csv",header=F)
df <- melt(wdays)
p <- ggplot(df, aes(x=value)) +
  stat_ecdf(aes(group=variable,colour=variable)) +
  scale_color_manual(
      name="",
      values = c("#CCE5FF", "#99CCFF", "#66B2FF", "#3399FF",
                 "#0080FF", "#0066CC", "#004C99"),
      labels = c("Mon", "Tues", "Weds", "Thurs", "Fri", "Sat", "Sun")
  ) +
  theme(legend.title=element_blank()) +
  xlab("Number of Daily Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-wdays-ecdf.png",width=7,height=6)

top_cmds = read.csv("analysis/top-cmds.csv",header=T)
df <- data.frame(
  freqs = top_cmds[[1]],
  cmd_names = factor(top_cmds[[2]],levels=top_cmds[[2]])
)
p <- ggplot(df,aes(x=cmd_names,y=freqs)) +
  xlab("Command") +
  ylab("Frequency") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
ggsave("plots/top-cmds.png",width=7,height=6)

cmd_lengths = as.numeric(read.csv("analysis/cmd-lengths.csv",header=F))
df = data.frame(cmd_lengths)
p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)),
      breaks=seq(0,max(df),10),
      minor_breaks=seq(0,max(df),5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-full.png",width=7,height=6)

p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)/3),
      breaks=seq(0,max(df)/3,10),
      minor_breaks=seq(0,max(df)/3,5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-zoomed.png",width=7,height=6)
REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script bin exe console][
		script: temp-dir/red-console.red
		exe:	temp-dir/console
		
		bin: either slash = first system/options/boot [
			system/options/boot
		][
			join system/options/path system/options/boot
		]
		if Windows? [
			append exe %.exe
			if %.exe <> suffix? bin [append bin %.exe]
		]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < modified? bin				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      data_restore_on_exit <- object$object$container$output$options$data
      label_restore_on_exit <- object$object$container$output$options$label
      on.exit(object$object$container$output$options$data <- data_restore_on_exit, add = TRUE)
      on.exit(object$object$container$output$opitons$label <- label_restore_on_exit, add = TRUE)
      object$object$container$output$options$data <- NULL
      object$object$container$output$options$label <- NULL
    } else {
      data_restore_on_exit <- object$output$options$data
      label_restore_on_exit <- object$output$options$label
      on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
      on.exit(object$output$opitons$label <- label_restore_on_exit, add = TRUE)
      object$output$options$data <- NULL
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_data_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object <- list(data = object$object$container$output$options$data, 
                     label = object$object$container$output$options$label)
    } else {
      object <- list(data = object$output$options$data, 
                     label = object$output$options$label)
    }
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 'data')
}
# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3   = construct_s3_adapter,
                          r    = construct_R_adapter,
                          data = construct_data_adapter)
#!/usr/bin/env Rscript

library(ggplot2)
library(reshape)

hours_m = as.numeric(read.csv("analysis/time-hours-stats.csv",header=F,nrows=1))
hours_stdev = as.numeric(read.csv("analysis/time-hours-stats.csv",
                                  header=F,nrows=1,skip=1))

df <- data.frame(freqs=hours_m,stdev=hours_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=0:23,y=freqs)) +
  xlab("Hour of Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity') +
  #geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-hours-bar.png",width=7,height=6)

hours = read.csv("analysis/time-hours-full.csv",header=F)
p <- ggplot() +
  stat_ecdf(aes(x=hours[[1]])) +
  stat_ecdf(aes(x=hours[[2]])) +
  stat_ecdf(aes(x=hours[[3]])) +
  stat_ecdf(aes(x=hours[[4]])) +
  stat_ecdf(aes(x=hours[[5]])) +
  stat_ecdf(aes(x=hours[[6]])) +
  stat_ecdf(aes(x=hours[[7]])) +
  stat_ecdf(aes(x=hours[[8]])) +
  stat_ecdf(aes(x=hours[[9]])) +
  stat_ecdf(aes(x=hours[[10]])) +
  stat_ecdf(aes(x=hours[[11]])) +
  stat_ecdf(aes(x=hours[[12]])) +
  stat_ecdf(aes(x=hours[[13]])) +
  stat_ecdf(aes(x=hours[[14]])) +
  stat_ecdf(aes(x=hours[[15]])) +
  stat_ecdf(aes(x=hours[[16]])) +
  stat_ecdf(aes(x=hours[[17]])) +
  stat_ecdf(aes(x=hours[[18]])) +
  stat_ecdf(aes(x=hours[[19]])) +
  stat_ecdf(aes(x=hours[[20]])) +
  stat_ecdf(aes(x=hours[[21]])) +
  stat_ecdf(aes(x=hours[[22]])) +
  stat_ecdf(aes(x=hours[[23]])) +
  stat_ecdf(aes(x=hours[[24]])) +
  theme(legend.title=element_blank()) +
  xlab("Number of Hourly Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-hours-ecdf.png",width=7,height=6)

wdays_m = as.numeric(read.csv("analysis/time-wdays-stats.csv",header=F,nrows=1))
wdays_stdev = as.numeric(read.csv("analysis/time-wdays-stats.csv",
                                  header=F,nrows=1,skip=1))
wday_str = c("Mon","Tues","Weds","Thurs","Fri","Sat","Sun")
df <- data.frame(freqs = wdays_m, wdays = factor(wday_str,levels=wday_str),
                 stdev=wdays_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=wdays,y=freqs)) +
  xlab("Week Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(y=freqs)) +
  geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-wdays-bar.png",width=7,height=6)

wdays = read.csv("analysis/time-wdays-full.csv",header=F)
p <- ggplot() +
  stat_ecdf(data=data.frame(wdays[[1]]),aes(x=wdays[[1]],colour="m")) +
  stat_ecdf(data=data.frame(wdays[[2]]),aes(x=wdays[[2]],colour="t")) +
  stat_ecdf(data=data.frame(wdays[[3]]),aes(x=wdays[[3]],colour="w")) +
  stat_ecdf(data=data.frame(wdays[[4]]),aes(x=wdays[[4]],colour="th")) +
  stat_ecdf(data=data.frame(wdays[[5]]),aes(x=wdays[[5]],colour="f")) +
  stat_ecdf(data=data.frame(wdays[[6]]),aes(x=wdays[[6]],colour="s")) +
  stat_ecdf(data=data.frame(wdays[[7]]),aes(x=wdays[[7]],colour="su")) +
  scale_color_manual(
      name="",
      breaks = c("m","t","w","th","f","s","su"),
      values = c("m"="#CCE5FF", "t"="#99CCFF", "w"="#66B2FF", "th"="#3399FF",
                 "f"="#0080FF", "s"="#0066CC", "su"="#004C99"),
      labels = c("m"="Mon", "t"="Tues", "w"="Weds", "th"="Thurs", "f"="Fri",
                 "s"="Sat", "su"="Sun")
  ) +
  theme(legend.title=element_blank()) +
  xlab("Number of Daily Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-wdays-ecdf.png",width=7,height=6)

top_cmds = read.csv("analysis/top-cmds.csv",header=T)
df <- data.frame(
  freqs = top_cmds[[1]],
  cmd_names = factor(top_cmds[[2]],levels=top_cmds[[2]])
)
p <- ggplot(df,aes(x=cmd_names,y=freqs)) +
  xlab("Command") +
  ylab("Frequency") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
ggsave("plots/top-cmds.png",width=7,height=6)

cmd_lengths = as.numeric(read.csv("analysis/cmd-lengths.csv",header=F))
df = data.frame(cmd_lengths)
p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)),
      breaks=seq(0,max(df),10),
      minor_breaks=seq(0,max(df),5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-full.png",width=7,height=6)

p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)/3),
      breaks=seq(0,max(df)/3,10),
      minor_breaks=seq(0,max(df)/3,5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-zoomed.png",width=7,height=6)
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object$output$options$data <- NULL
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_data_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object <- list(data = object$output$options$data, 
                     label = object$output$options$label)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}
# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3   = construct_s3_adapter,
                          r    = construct_R_adapter,
                          data = construct_data_adapter)
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141221_0133"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  ###
  # BE AWARE: hard-coded switching from 'memory savings in %' to 'speedup factor'.
  ##
  # memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)
  memorySavingComparedToTheOther <- (theOther$footprintInBytes_median / ours$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}

# http://stackoverflow.com/questions/11340444/is-there-an-r-function-to-format-number-using-unit-prefix
formatCsUnits__ <- function (number,rounding=T) 
{
  lut <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-09, 1e-06, 
           0.001, 1, 1000, 1e+06, 1e+09, 1e+12, 1e+15, 1e+18, 1e+21, 
           1e+24)
  pre <- c("y", "z", "a", "f", "p", "n", "u", "m", "", "K", 
           "M", "G", "T", "P", "E", "Z", "Y")
  ix <- findInterval(number, lut)
  if (lut[ix]!=1) {
    if (rounding==T) {
      sistring <- paste(formatC(number/lut[ix], digits=0, format="f"),pre[ix], sep="")
    }
    else {
      sistring <- paste(formatC(number/lut[ix], digits=0, format="f"), pre[ix], sep="")
    } 
  }
  else {
    sistring <- paste(round(number, digits=0))
  }
  return(sistring)
}

formatCsUnits <- Vectorize(formatCsUnits__)

formatFactor__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    digits = 2
    
    if (rounding==T) {
      x <- format(round(arg, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(arg, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatFactor <- Vectorize(formatFactor__)

formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  arg_fmt <- formatFactor(arg, rounding=T)
  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg_fmt, "}$", sep = "")
  } else {
    paste("$", arg_fmt, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

### 
# Cache Statistics
##
benchmarksPerfStatFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "perf-stat", "log", sep=".")
benchmarksPerfStat <- read.csv(benchmarksPerfStatFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarksPerfStat) <- c("L1_REF", "L1_MISSES", "L3_REF", "L3_MISSES")

# benchmarksPerfStat$L2_MISSES <- benchmarksPerfStat$L2_REF - benchmarksPerfStat$L2_HIT

benchmarksPerfStat$L1_HIT <- benchmarksPerfStat$L1_REF - benchmarksPerfStat$L1_MISSES
benchmarksPerfStat$L3_HIT <- benchmarksPerfStat$L3_REF - benchmarksPerfStat$L3_MISSES

benchmarksPerfStat$L1_HIT_RATE <- benchmarksPerfStat$L1_HIT / benchmarksPerfStat$L1_REF
# benchmarksPerfStat$L2_HIT_RATE <- benchmarksPerfStat$L2_HIT / benchmarksPerfStat$L2_REF
benchmarksPerfStat$L3_HIT_RATE <- benchmarksPerfStat$L3_HIT / benchmarksPerfStat$L3_REF

benchmarksPerfStat$L1_MISS_RATE <- 1 - benchmarksPerfStat$L1_HIT_RATE
# benchmarksPerfStat$L2_MISS_RATE <- 1 - benchmarksPerfStat$L2_HIT_RATE
benchmarksPerfStat$L3_MISS_RATE <- 1 - benchmarksPerfStat$L3_HIT_RATE

#data.frame(benchmarksCleaned, benchmarksPerfStat)


#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(data.frame(benchmarksCleaned, benchmarksPerfStat), id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)



###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- dataFormatter(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# ###
# # Results as saving percentags
# ##
# measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
# measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')
# dataFormatter <- latexMathPercent
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)

# ###
# # Results as speedup factors
# ##
# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# dataFormatter <- latexMathFactor
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)


createCacheStatTable <- function(input, dataType, dataStructureOrigin, measureVars, benchmarkName, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Benchmark == benchmarkName & input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
  
  my_ylim <- range(0, 1.0)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT_RATE, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT_RATE, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT_RATE)
  boxplot(ylim=my_ylim, benchmarksCast$VF_SCALA_L1_HIT_RATE, benchmarksCast$VF_SCALA_L2_HIT_RATE, benchmarksCast$VF_SCALA_L3_HIT_RATE)
  boxplot(ylim=my_ylim, benchmarksCast$VF_CLOJURE_L1_HIT_RATE, benchmarksCast$VF_CLOJURE_L2_HIT_RATE, benchmarksCast$VF_CLOJURE_L3_HIT_RATE)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT_RATE, benchmarksCast$VF_SCALA_L1_HIT_RATE, benchmarksCast$VF_CLOJURE_L1_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT, benchmarksCast$VF_SCALA_L1_HIT, benchmarksCast$VF_CLOJURE_L1_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_REF, benchmarksCast$VF_SCALA_L1_REF, benchmarksCast$VF_CLOJURE_L1_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_MISSES, benchmarksCast$VF_SCALA_L1_MISSES, benchmarksCast$VF_CLOJURE_L1_MISSES)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT_RATE, benchmarksCast$VF_SCALA_L2_HIT_RATE, benchmarksCast$VF_CLOJURE_L2_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT, benchmarksCast$VF_SCALA_L2_HIT, benchmarksCast$VF_CLOJURE_L2_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_REF, benchmarksCast$VF_SCALA_L2_REF, benchmarksCast$VF_CLOJURE_L2_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_MISSES, benchmarksCast$VF_SCALA_L2_MISSES, benchmarksCast$VF_CLOJURE_L2_MISSES)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT_RATE, benchmarksCast$VF_SCALA_L3_HIT_RATE, benchmarksCast$VF_CLOJURE_L3_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT, benchmarksCast$VF_SCALA_L3_HIT, benchmarksCast$VF_CLOJURE_L3_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_REF, benchmarksCast$VF_SCALA_L3_REF, benchmarksCast$VF_CLOJURE_L3_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_MISSES, benchmarksCast$VF_SCALA_L3_MISSES, benchmarksCast$VF_CLOJURE_L3_MISSES)
  
  sel <- c("Param_size", "Param_valueFactoryFactory", "L3_MISSES")
  tmp <- dcast(input[input$Benchmark == benchmarkName & input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size + Param_valueFactoryFactory ~ variable)[sel]  
  # tmp[,3:NCOL(tmp)] <- round(tmp[,3:NCOL(tmp)], 2)
  tmp[,3:NCOL(tmp)] <- formatCsUnits(tmp[,3:NCOL(tmp)])
  
  
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
  
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
#   tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
#   tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)
  
  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  
  
  
#   ###
#   # Create boxplots as well
#   ##
#   outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
#   fontScalingFactor <- 1.2
#   pdf(outFileName, family = "Times", width = 10, height = 3)
#   
#   selection <- tableAll[2:NCOL(tableAll)]
#   names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
#   
#   par(mar = c(3.5,4.75,0,0) + 0.1)
#   par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
#   
#   boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
#           cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
#   
#   z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
#   zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
#   par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
#   axis(2, at=z, labels=zz, las=2,
#        cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
#   
#   #   abline(v =  5.5)
#   
#   #abline(h =  0.75, lty=3)
#   #abline(h =  0.5, lty=3)
#   #abline(h =  0.25, lty=3)
#   abline(h =  0)
#   abline(h = -0.5, lty=3)
#   dev.off()
#   embed_fonts(outFileName)
  
}

###
# Results as speedup factors
##
measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
dataFormatter <- latexMathFactor

# createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "EntryIteration", dataFormatter)
createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "Iteration", dataFormatter)
createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "EqualsRealDuplicate", dataFormatter)

# createCacheStatTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createCacheStatTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    object$output$options$data <- NULL
    object$output$options$label <- NULL
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_data_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = list(data = object$output$options$data, 
                            label = object$output$options$label), 
                 name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- paste(opts$s3path, "data", "label", 
        sep = "_")
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}
# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3   = construct_s3_adapter,
                          r    = construct_R_adapter,
                          data = construct_data_adapter)
REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script bin exe console][
		script: temp-dir/red-console.red
		exe:	temp-dir/console
		
		bin: either slash = first system/options/boot [
			system/options/boot
		][
			join system/options/home system/options/boot
		]
		if Windows? [
			append exe %.exe
			if %.exe <> suffix? bin [append bin %.exe]
		]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < modified? bin				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
0.5.0#!/usr/bin/env Rscript

library(ggplot2)
library(reshape)

hours_m = as.numeric(read.csv("analysis/time-hours.csv",header=F,nrows=1))
hours_stdev = as.numeric(read.csv("analysis/time-hours.csv",header=F,nrows=1,skip=1))

p <- ggplot() +
  xlab("Hour of Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(x=0:23.,y=hours_m)) +
  theme_bw()
  # TODO: Error bars.
ggsave("plots/time-hours.png",width=7,height=6)

wdays_m = as.numeric(read.csv("analysis/time-wdays.csv",header=F,nrows=1))
wdays_stdev = as.numeric(read.csv("analysis/time-wdays.csv",header=F,nrows=1,skip=1))
wday_str = c("Mon","Tues","Weds","Thurs","Fri","Sat","Sun")
df <- data.frame(freqs = wdays_m, wdays = factor(wday_str,levels=wday_str))
p <- ggplot(df,aes(x=wdays,y=freqs)) +
  xlab("Week Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
  # TODO: Error bars.
ggsave("plots/time-wdays.png",width=7,height=6)

top_cmds = read.csv("analysis/top-cmds.csv",header=T)
df <- data.frame(
  freqs = top_cmds[[1]],
  cmd_names = factor(top_cmds[[2]],levels=top_cmds[[2]])
)
p <- ggplot(df,aes(x=cmd_names,y=freqs)) +
  xlab("Command") +
  ylab("Frequency") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
ggsave("plots/top-cmds.png",width=7,height=6)
REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script bin exe console][
		script: temp-dir/red-console.red
		exe:	temp-dir/console
		bin:	join system/options/home system/options/boot
		
		if Windows? [
			append exe %.exe
			append bin %.exe
		]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < modified? bin				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141220_1214"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  ###
  # BE AWARE: hard-coded switching from 'memory savings in %' to 'speedup factor'.
  ##
  # memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)
  memorySavingComparedToTheOther <- (theOther$footprintInBytes_median / ours$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}

# http://stackoverflow.com/questions/11340444/is-there-an-r-function-to-format-number-using-unit-prefix
formatCsUnits__ <- function (number,rounding=T) 
{
  lut <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-09, 1e-06, 
           0.001, 1, 1000, 1e+06, 1e+09, 1e+12, 1e+15, 1e+18, 1e+21, 
           1e+24)
  pre <- c("y", "z", "a", "f", "p", "n", "u", "m", "", "K", 
           "M", "G", "T", "P", "E", "Z", "Y")
  ix <- findInterval(number, lut)
  if (lut[ix]!=1) {
    if (rounding==T) {
      sistring <- paste(formatC(number/lut[ix], digits=0, format="f"),pre[ix], sep="")
    }
    else {
      sistring <- paste(formatC(number/lut[ix], digits=0, format="f"), pre[ix], sep="")
    } 
  }
  else {
    sistring <- paste(round(number, digits=0))
  }
  return(sistring)
}

formatCsUnits <- Vectorize(formatCsUnits__)

formatFactor__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    digits = 2
    
    if (rounding==T) {
      x <- format(round(arg, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(arg, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatFactor <- Vectorize(formatFactor__)

formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  arg_fmt <- formatFactor(arg, rounding=T)
  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg_fmt, "}$", sep = "")
  } else {
    paste("$", arg_fmt, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

### 
# Cache Statistics
##
benchmarksPerfStatFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "perf-stat", "log", sep=".")
benchmarksPerfStat <- read.csv(benchmarksPerfStatFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarksPerfStat) <- c("L1_REF", "L1_MISSES", "L2_REF", "L2_HIT", "L3_REF", "L3_MISSES")

benchmarksPerfStat$L2_MISSES <- benchmarksPerfStat$L2_REF - benchmarksPerfStat$L2_HIT

benchmarksPerfStat$L1_HIT <- benchmarksPerfStat$L1_REF - benchmarksPerfStat$L1_MISSES
benchmarksPerfStat$L3_HIT <- benchmarksPerfStat$L3_REF - benchmarksPerfStat$L3_MISSES

benchmarksPerfStat$L1_HIT_RATE <- benchmarksPerfStat$L1_HIT / benchmarksPerfStat$L1_REF
benchmarksPerfStat$L2_HIT_RATE <- benchmarksPerfStat$L2_HIT / benchmarksPerfStat$L2_REF
benchmarksPerfStat$L3_HIT_RATE <- benchmarksPerfStat$L3_HIT / benchmarksPerfStat$L3_REF

benchmarksPerfStat$L1_MISS_RATE <- 1 - benchmarksPerfStat$L1_HIT_RATE
benchmarksPerfStat$L2_MISS_RATE <- 1 - benchmarksPerfStat$L2_HIT_RATE
benchmarksPerfStat$L3_MISS_RATE <- 1 - benchmarksPerfStat$L3_HIT_RATE

#data.frame(benchmarksCleaned, benchmarksPerfStat)


#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(data.frame(benchmarksCleaned, benchmarksPerfStat), id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)



###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- dataFormatter(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# ###
# # Results as saving percentags
# ##
# measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
# measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')
# dataFormatter <- latexMathPercent
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)

# ###
# # Results as speedup factors
# ##
# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# dataFormatter <- latexMathFactor
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)


createCacheStatTable <- function(input, dataType, dataStructureOrigin, measureVars, benchmarkName, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Benchmark == benchmarkName & input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
  
  my_ylim <- range(0, 1.0)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT_RATE, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT_RATE, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT_RATE)
  boxplot(ylim=my_ylim, benchmarksCast$VF_SCALA_L1_HIT_RATE, benchmarksCast$VF_SCALA_L2_HIT_RATE, benchmarksCast$VF_SCALA_L3_HIT_RATE)
  boxplot(ylim=my_ylim, benchmarksCast$VF_CLOJURE_L1_HIT_RATE, benchmarksCast$VF_CLOJURE_L2_HIT_RATE, benchmarksCast$VF_CLOJURE_L3_HIT_RATE)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT_RATE, benchmarksCast$VF_SCALA_L1_HIT_RATE, benchmarksCast$VF_CLOJURE_L1_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT, benchmarksCast$VF_SCALA_L1_HIT, benchmarksCast$VF_CLOJURE_L1_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_REF, benchmarksCast$VF_SCALA_L1_REF, benchmarksCast$VF_CLOJURE_L1_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_MISSES, benchmarksCast$VF_SCALA_L1_MISSES, benchmarksCast$VF_CLOJURE_L1_MISSES)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT_RATE, benchmarksCast$VF_SCALA_L2_HIT_RATE, benchmarksCast$VF_CLOJURE_L2_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT, benchmarksCast$VF_SCALA_L2_HIT, benchmarksCast$VF_CLOJURE_L2_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_REF, benchmarksCast$VF_SCALA_L2_REF, benchmarksCast$VF_CLOJURE_L2_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_MISSES, benchmarksCast$VF_SCALA_L2_MISSES, benchmarksCast$VF_CLOJURE_L2_MISSES)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT_RATE, benchmarksCast$VF_SCALA_L3_HIT_RATE, benchmarksCast$VF_CLOJURE_L3_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT, benchmarksCast$VF_SCALA_L3_HIT, benchmarksCast$VF_CLOJURE_L3_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_REF, benchmarksCast$VF_SCALA_L3_REF, benchmarksCast$VF_CLOJURE_L3_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_MISSES, benchmarksCast$VF_SCALA_L3_MISSES, benchmarksCast$VF_CLOJURE_L3_MISSES)
  
  sel <- c("Param_size", "Param_valueFactoryFactory", "L3_MISSES")
  tmp <- dcast(input[input$Benchmark == benchmarkName & input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size + Param_valueFactoryFactory ~ variable)[sel]  
  # tmp[,3:NCOL(tmp)] <- round(tmp[,3:NCOL(tmp)], 2)
  tmp[,3:NCOL(tmp)] <- formatCsUnits(tmp[,3:NCOL(tmp)])
  
  
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
  
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
#   tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
#   tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)
  
  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  
  
  
#   ###
#   # Create boxplots as well
#   ##
#   outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
#   fontScalingFactor <- 1.2
#   pdf(outFileName, family = "Times", width = 10, height = 3)
#   
#   selection <- tableAll[2:NCOL(tableAll)]
#   names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
#   
#   par(mar = c(3.5,4.75,0,0) + 0.1)
#   par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
#   
#   boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
#           cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
#   
#   z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
#   zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
#   par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
#   axis(2, at=z, labels=zz, las=2,
#        cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
#   
#   #   abline(v =  5.5)
#   
#   #abline(h =  0.75, lty=3)
#   #abline(h =  0.5, lty=3)
#   #abline(h =  0.25, lty=3)
#   abline(h =  0)
#   abline(h = -0.5, lty=3)
#   dev.off()
#   embed_fonts(outFileName)
  
}

###
# Results as speedup factors
##
measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
dataFormatter <- latexMathFactor

createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "EntryIteration", dataFormatter)
createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "Iteration", dataFormatter)
createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "EqualsRealDuplicate", dataFormatter)

# createCacheStatTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createCacheStatTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)
library(pbdMPI, quiet = TRUE)
library(pbdDMAT, quiet = TRUE)
library(pbdADIOS, quiet = TRUE)
library(raster, quiet=TRUE)
library(ggplot2, quiet=TRUE)
library(grid, quiet=TRUE)

## begin function definitions
adios.init <- function(method="ADIOS_READ_METHOD_BP", par="verbose=3")
{
    invisible(adios.read.init.method("ADIOS_READ_METHOD_BP",
                                     params="verbose=3"))
}

adios.open <- function(file, timeout=1, method="ADIOS_READ_METHOD_BP",
                       lockmode="ADIOS_LOCKMODE_NONE")
{
    ## timeout default is 1 sec
    pt <- adios.read.open(file, adios.timeout=timeout, "ADIOS_READ_METHOD_BP",
                          adios.lockmode="ADIOS_LOCKMODE_NONE")
    if(comm.rank() == 0) bpls <- system(paste("bpls", file), intern=TRUE)
    else bpls <- NULL
    bpls <- bcast(bpls)
    list(pt=pt, bpls=bpls)
}

raster_plot <- function(x, nrow, ncol, basename="raster", sequence=1, swidth=3)
{
    x <- data.frame(rasterToPoints(raster(matrix(x, nrow, ncol),
                                          xmn=0, xmx=ncol, ymn=0, ymx=nrow)))
    names(x) <- c("x", "y", basename)
    png(paste(basename, "_", formatC(sequence, width=swidth, flag=0), "_",
              comm.rank(), ".png", sep=""))
    print(ggplot(x, aes_string(x="x", y="y", fill=basename)) + geom_raster() +
          theme_minimal() + theme(axis.text.x=element_blank(),
                                  axis.ticks.x=element_blank(),
                                  axis.title.x=element_blank(),
                                  legend.position="none",
                                  plot.margin=unit(c(0,0,0,0),"cm")
                                  )
          )
    dev.off()
}
## end function definitions

init.grid()
adios.init()

## specify and open file for reading
dir.data <- "/lustre/atlas/scratch/ost/stf006/heat"
file <- paste(dir.data, "heat.bp", sep="/")
file.ptr <- adios.open(file)

## select variable to read
variable <- "T"

## get variable dimensions
varinfo = adios.inq.var(file.ptr$pt, variable)
block <- adios.inq.var.blockinfo(file.ptr$pt, varinfo)
ndim <- custom.inq.var.ndim(varinfo)
dims <- custom.inq.var.dims(varinfo)

## get dimensions and split
source("pbdADIOS/tests/partition.r")
g.dim <- dims # global.dim on write
split <- c(TRUE, FALSE)
my.data.partition <- data.partition(seq(0, 0, along.with=g.dim), g.dim, split)
my.dim <- my.count <- my.data.partition$my.dim # local.dim on write
my.start <- my.data.partition$my.start # local.offset on write
my.grid <- my.data.partition$my.grid

## partition across first dimension (expects at least 2d)
slice_size0 <- as.integer(dims[1] %/% comm.size())
slice_size <- slice_size0
if(comm.rank() == (comm.size() - 1))
    slice_size <- as.integer(slice_size + (dims[1] %% comm.size()))
start <- c(as.integer(comm.rank() * slice_size0), rep(0, ndim - 1))
count <- c(slice_size, as.integer(dims[2:ndim]))

errno <- 0 # Default value 0
steps <- 0
retval <- 0
bufsize <- 10
buffer <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a0 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a1 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a2 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
rhs <- cbind(rep(1, bufsize), poly(1:bufsize, degree=2))

while(errno != -21) { ## This is hard-coded for now. -21=err_end_of_stream
    steps = steps + 1 ## Double check with Norbert. Should it start with 1 or 2

    ## set reading bounding box
    adios.selection  <- adios.selection.boundingbox(ndim, my.start, my.count)
    comm.print("Selection.boundingbox complete ...")
    
    ## schedule the read
    adios.data <- adios.schedule.read(varinfo, my.start, my.count, file.ptr$pt,
                                      adios.selection, variable, 0, 1)
    comm.print("Schedule read complete ...")
    
    ## perform the read
    adios.perform.reads(file.ptr$pt, 1)
    comm.print("Perform read complete ...")

    data_chunk <- custom.data.access(adios.data, adios.selection, varinfo)
    comm.print("Data access complete ...")

    ## print a few to verify
    comm.cat("first 5:", head(data_chunk, 5),"\n")
    comm.cat("last 5:", tail(data_chunk, 5),"\n")

    ## shape into matrix with first dim as rows
    ## local reshape dimensions
    my.ncol <- prod(my.dim[2])
    my.nrow <- my.dim[1]
    ldim <- c(my.nrow, my.ncol)

    ## global reshape dimensions
    g.ncol <- prod(g.dim[2])
    g.nrow <- g.dim[1]
    gdim <- c(g.nrow, g.ncol)
    
    ## now glue into a ddmatrix
    ##  x <- matrix(data_chunk, nrow=my.nrow, ncol=my.ncol, byrow=FALSE)
    ##  X <- new("ddmatrix", Data=x, dim=gdim, ldim=ldim, bldim=ldim, ICTXT=2)

    ## Fit a quadratic to a moving window of 10 steps
    ## Actually don't need the ddmatrix for this and can go straight
    ## from data_chunk into buffer matrix
    buffer <- rbind(buffer[-1, ], data_chunk)

    ## plot the original local matrix (swapping row to col - C to R)
    raster_plot(data_chunk, my.ncol, my.nrow, "T", steps)
    
    ## fit data and plot three coefficient raster plots
    if(steps >= bufsize)
        {
            fit <- lm.fit(rhs, buffer)$coefficients
    ##         raster_plot(fit[1, ], my.ncol, my.nrow, "a0", steps)
    ##         raster_plot(fit[2, ], my.ncol, my.nrow, "a1", steps)
    ##         raster_plot(fit[3, ], my.ncol, my.nrow, "a2", steps)
        }
    
    ## All these work fine!
    ##    X <- as.blockcyclic(X, bldim=c(4, 4))
    ##    X.pc <- prcomp(X)
    ##    comm.print(X.pc)
    
    ##
    ## Here, write out the results of the analysis
    a0 <- fit[1, ]
    a1 <- fit[2, ]
    a2 <- fit[3, ]
    ## now use adios to write (T, a0, a1, a2). All are with dimensions:
    ##       global.dim = gdim
    ##       local.dim = my.dim = my.count
    ##       local.offset = my.start

    ## insert adios writing code here  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    
    ## try to get more data
    adios.advance.step(file.ptr$pt, 0, adios.timeout.sec=1)
    comm.print(paste("Done advance.step", steps, "..."))
     
    ## check errors
    errno <- adios.errno()
    comm.cat("Error Num",errno, "\n")

    ## if error is timeout (or EOF)
    if(errno == -22){ #-22 = err_step_notready
        comm.cat(comm.rank(), "Timeout waiting for more data. Quitting ...\n")
        break
    }
if(steps > 20) break
} # While end 

comm.print("Broke out of loop ...")
adios.read.close(file.ptr$pt)
comm.print("File closed")
adios.read.finalize.method("ADIOS_READ_METHOD_BP")
comm.print("Finalized adios ...")
finalize() # pbdMPI finalize

library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=TRUE, add.comment=TRUE, 
                               add.row.margin=TRUE, add.col.margin=TRUE,
                               style=None) {
  #print(str(tabular))
  
  if ( is.null(caption(tabular)) ) { add.caption  <- FALSE}
  if ( is.null(col.margin(tabular)) ) { add.col.margin  <- FALSE}
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------

  caption <- attr(tabular, 'caption')
  col.margin <- attr(tabular, 'col.margin')
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  attr(tabular, 'caption') <- caption
  attr(tabular, 'col.margin') <- col.margin
  rm(caption, col.margin)
  
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- caption(tabular)
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(as.data.frame(as.vector(col.margin(tabular))))
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000", halign='right')
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = sheet, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = sheet, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = sheet, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1, spacer_rows=2) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 1 + spacer_rows
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#!/usr/bin/env Rscript

# Parse the --file= argument out of command line args and
# determine where base directory is so that we can source
# our common sub-routines
arg0 <- sub("--file=(.*)", "\\1", grep("--file=", commandArgs(), value = TRUE))
dir0 <- dirname(arg0)
source(file.path(dir0, "common.r"))

theme_set(theme_grey(base_size = 17))

# Setup parameters for the script
params = matrix(c(
  'help',    'h', 0, "logical",
  'width',   'x', 2, "integer",
  'height',  'y', 2, "integer",
  'outfile', 'o', 2, "character",
  'indir',   'i', 2, "character",
  'tstart',  '1',  2, "integer",
  'tend',    '2',  2, "integer",
  'ylabel1stgraph', 'Y',  2, "character",
  'title', 't',  2, "character"
  ), ncol=4, byrow=TRUE)

# Parse the parameters
opt = getopt(params)

if (!is.null(opt$help))
  {
    cat(paste(getopt(params, command = basename(arg0), usage = TRUE)))
    q(status=1)
  }

# Initialize defaults for opt
if (is.null(opt$width))   { opt$width   = 1280 }
if (is.null(opt$height))  { opt$height  = 960 }
if (is.null(opt$indir))   { opt$indir  = "current"}
if (is.null(opt$outfile)) { opt$outfile = file.path(opt$indir, "summary.png") }
if (is.null(opt$ylabel1stgraph)) { opt$ylabel1stgraph = "Op/sec" }
if (is.null(opt$title)) { opt$title = "Throughput" }

# Load the benchmark data, passing the time-index range we're interested in
b = load_benchmark(opt$indir, opt$tstart, opt$tend)

# If there is no actual data available, bail
if (nrow(b$latencies) == 0)
{
  stop("No latency information available to analyze in ", opt$indir)
}

png(file = opt$outfile, width = opt$width, height = opt$height)

# First plot req/sec from summary
plot1 <- qplot(elapsed, successful / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = opt$title) +

                geom_smooth(aes(y = successful / window, colour = "ok"), size=0.5) +
                geom_point(aes(y = successful / window, colour = "ok"), size=2.0) +

                geom_smooth(aes(y = failed / window, colour = "error"), size=0.5) +
                geom_point(aes(y = failed / window, colour = "error"), size=2.0) +

                scale_colour_manual("Response", values = c("#FF665F", "#188125"))


# Setup common elements of the latency plots
latency_plot <- ggplot(b$latencies, aes(x = elapsed)) +
                   facet_grid(. ~ op) +
                   labs(x = "Elapsed Secs", y = "Latency (ms)")

# Plot median, mean and 95th percentiles
plot2 <- latency_plot + labs(title = "Mean, Median, and 95th Percentile Latency") +
            geom_smooth(aes(y = median, color = "median"), size=0.5) +
            geom_point(aes(y = median, color = "median"), size=2.0) +

            geom_smooth(aes(y = mean, color = "mean"), size=0.5) +
            geom_point(aes(y = mean, color = "mean"), size=2.0) +

            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot 99th percentile
plot3 <- latency_plot + labs(title = "99th Percentile Latency") +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X99_9th","X99th" ),
            #                 labels = c("99.9th", "99th"))

# Plot 99.9th percentile
plot4 <- latency_plot + labs(title = "99.9th Percentile Latency") +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

# Plot 100th percentile
plot5 <- latency_plot + labs(title = "Maximum Latency") +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

grid.newpage()

pushViewport(viewport(layout = grid.layout(5, 1)))

vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

print(plot1, vp = vplayout(1,1))
print(plot2, vp = vplayout(2,1))
print(plot3, vp = vplayout(3,1))
print(plot4, vp = vplayout(4,1))
print(plot5, vp = vplayout(5,1))

dev.off()
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=TRUE, add.comment=TRUE, 
                               add.row.margin=TRUE, add.col.margin=TRUE,
                               style=None) {
  #print(str(tabular))
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { 
    caption <- attr(tabular, 'caption')
    tabular <- as.data.frame(tabular)
    attr(tabular, 'caption') <- caption
    rm(caption)
  }
  
  if ('svytable' %in% class(tabular)) {
    caption <- attr(tabular, 'caption')
    tabular <- as.data.frame.matrix(tabular) 
    attr(tabular, 'caption') <- caption
    rm(caption)
  }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000", halign='right')
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = sheet, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = sheet, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = sheet, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1, spacer_rows=2) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 1 + spacer_rows
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141218_0337"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)
#' Conduct an aggregate query on amcat
#'
#' This function is similar to using the 'show table' function in AmCAT. It allows you to specify a
#' number of queries and get the number of hits per search term, per period, etc.
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param axis1 The first grouping (break/group by) variable, e.g. year, month, week, day, or medium
#' @param axis2 The second grouping (break/group by) variable, e.g. medium. Do not use a date interval here.
#' @param ... additional arguments to pass to the AmCAT API. 
#' @return A data frame with hits per group
#' @export
amcat.aggregate <- function(conn, queries, labels=queries, sets, axis1=NULL, axis2=NULL, ...) {
  result = NULL
  queries = as.character(queries)
  for (i in 1:length(queries)) {
    if (!is.na(queries[i])) {
      
      r = tryCatch(amcat.getobjects(conn,"aggregate", filters=list(q=queries[i], sets=sets, axis1=axis1, axis2=axis2, ...)),
                   error=function(e) {warning("Error on querying '", labels[i], "': ", e$message); NULL})
      if (is.null(r)) next
      if (nrow(r) > 0) {
        if (names(r)[1] == "count") {
          r$query = labels[i]
          result = rbind(result, r)
        } else {
          warning(paste("Error on querying",labels[i]))
        }
      }
    }
  }  
  # convert axis1 to Date object if needed
  if (!is.null(axis1))
    if (axis1 %in% c("year", "quarter", "month", "week", "day")) result[, axis1] = as.Date(result[, axis1])
  return(result)
}

#' Conduct a query on amcat
#'
#' This function is similar to using the 'show article list' function in AmCAT. It allows you to specify a
#' number of queries and get document metadata and number of hits per document
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param ... additional arguments to pass to the AmCAT API, e.g. extra filters
#' @return A data frame with hits per article
#' @export
amcat.hits <- function(conn, queries, labels=queries, sets, minimal=T, ...) {
  result = NULL
  for (i in 1:length(queries)) {
    q = paste("count", queries[i], sep="#")
    r = amcat.getobjects(conn, "search",filters=list(q=q, col="hits", sets=sets, minimal=minimal, ...))
    if (nrow(r) > 0) {
      r$query = labels[i]
      result = rbind(result, r)
    } else {
      warning(paste("Query",labels[i]," produced no results"))
    }
  }
  return(result)
}
#Code for eBird migration project
# (c) 2013 -2014 Sarah Supp 

library(ggmap)
library(maptools)
library(fields)
library(sp)
library(raster)
library(maps)
library(mapdata)
library(rgdal)
library(raster)
library(gamm4)

#set working directory
main = "C:/Users/sarah/Dropbox/ActiveResearchProjects/Hummingbird_eBirdMigration"
figpath = "C:/Users/sarah/Dropbox/ActiveResearchProjects/Hummingbird_eBirdMigration/Figures"
gitpath = "C:/Users/sarah/Documents/GitHub/hb-migration"
wd = "C:/Users/sarah/Dropbox/ActiveResearchProjects/Hummingbird_eBirdMigration/data"
setwd(wd)


#---------------------------------------------------------------------------------------
#              predict migration paths, dates, speed, and error across years
#---------------------------------------------------------------------------------------

# read in summary of effort data (Number of eBird checklists submitted per day per year)
effort = read.table("FAL_hummingbird_data/checklist_12_2004-2013wh_grp.txt", header=TRUE, as.is=TRUE)

# read in country outline shp files
USAborder = readShapePoly("borders/USA_adm/USA_adm0.shp")
Mexborder = readShapePoly("borders/MEX_adm/MEX_adm0.shp")
Canborder = readShapePoly("borders/CAN_adm/CAN_adm0.shp")

# read in the altitude layers, make rasters
elev = raster("alt_5m_bil/alt.bil")

# plot elev + map for extent
myext <- c(-175, -50, 15, 75)
plot.new()
#plot(elev, ext = myext, xlab="Longitude", ylab = "Latitude", xlim = c(-175,-50), ylim = c(15,75), col=gray(0:256/256))

borders <- function(){
  plot(USAborder, ext=myext, border="black", add=TRUE)
  plot(Mexborder, ext=myext, border="black", add=TRUE)
  plot(Canborder, ext=myext, border="black", add=TRUE)
}

plot(elev, ext=myext, addfun=borders, ylab="Latitude", xlab="Longitude", xlim = c(-175,-50), ylim = c(15,75), col=gray(0:256/256)) 

# read in the north america equal area hex grid map (FAL) and format for use
# other options include a quad map (terr_4h6/nw_vector_grid.shp) or a hexmap with land only (terr_4h6/terr_4h6.shp", sep="")
hexgrid = readShapePoly(paste(main, "/data/icosahedron_land_and_sea/icosahedron.shp", sep="")) #hex with land and sea, cropped to North America

# plot the hexgrid on a map of north america
plot(NA, NA, xlim=c(-175, -50), ylim=c(15, 75), xlab = "Longitude", ylab = "Latitude")
map('worldHires', c("usa", "canada", "mexico"), add=TRUE, fill=T, col="lightblue")
plot(hexgrid, add=T)

# make a North America base map
noam = get_map(location = "North America", zoom=3, maptype = "terrain", color = "bw")

# map total birder effort 2004:2013
eft = PlotChecklistMap(effort, hexgrid, wd)
rm(eft)

# read in eBird data
files = list.files(pattern = "*.txt")

#for each eBird file, print the number sightings per year and per month.
#plot the locations of sightings on a map, color coded by month
for (f in 1:length(files)){
  
  require(ggmap)
  require(ggplot2)
  require(plyr)
  require(reshape2)
  require(Rmisc)
  require(sp)
  require(raster)
  require(segmented)
  source(paste(gitpath, "/migration-fxns.r", sep=""))
  
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                    "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                    "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")
  
  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)
  
  #grab species name for setting directory paths and naming figures
  species = humdat$SCI_NAME[1] 
  species = gsub(" ","", species, fixed=TRUE)
  species = gsub("\"", "", species, fixed=TRUE)
  
  # set years of data to use - data after 2007 is more reliable
  years = c(2004:2013)

  #start a new directory
  dirpath = paste(figpath, "/", species, sep="")
     #dir.create(dirpath, showWarnings = TRUE, recursive = FALSE) #only need if directory did not previously exist
  
  #show how many records there are for the species across the years, write to txt file
  #yeartable = PlotRecords(humdat$YEAR, species)
  #ggsave(file=paste(dirpath, "/", "years", species, ".pdf", sep=""))
  
  write.table(yeartable, file = paste(dirpath, "/", species,".txt",sep=""), row.names=FALSE)
  
  #save a figure of the geographic number of checklists for the species, over all the years
  #count = PlotChecklistMap(humdat, hexgrid, dirpath)
  
  for (y in 1:length(years)){
    yrdat = humdat[which(humdat$YEAR == years[y]),]
    yreffort = effort[which(effort$YEAR == years[y]),]
    
    #plot frequency of sightings per month
    #monthtable = PlotRecords(yrdat$month, species)
    
    #get daily weighted mean location 
    meanlocs = AlternateMeanLocs(yrdat, species, hexgrid, yreffort)
    
    #use GAM model to predict daily location along a smoothing line
    preds = EstimateDailyLocs(meanlocs)
    
    #use gam approach to estimate rough starting points for segmentation from the mean loc latitude data
    startpoints = round(Est3MigrationDates(meanlocs))
    migration = startpoints
    
    #save a plot of the species migration route mapped onto continent with real observations
    pdf(file = paste(dirpath, "/trimmed-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
    BasePlotMigration(preds, yrdat, migration, elev, USAborder, Mexborder, Canborder, myext)
    dev.off() 
    
    #save a plot of the species migration mapped onto an elevation raster
    pdf(file = paste(dirpath, "/elev-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
    ElevPlotMigration(preds, yrdat, migration, elev, USAborder, Mexborder, Canborder, myext)
    dev.off() 
    
    #get Great Circle distances traveled each day between predicted daily locations
    dist = DailyTravel(preds, 4, 5, species, years[y], migration)
    
    #estimate migration speed for spring and fall
    speed = MigrationSpeed(dist, migration)
    
    #plot smoothed migration trajectory for the species and year
    #mig_path = PlotMigrationPath(preds, noam, species, years[y])
    #ggsave(mig_path, file=paste(dirpath, "/", "migration", species, years[y], ".pdf", sep=""))
    
#     #plot occurrences with lines showing beginning and end of migration
     PlotOccurrences(meanlocs, species, years[y], migration)
     ggsave(file=paste(dirpath, "/", "occurrences", species, years[y], ".tiff", sep=""), dpi=600)

    #Subset western species by flyway data (check bias in SE US data points) Sensu La Sorte et al in press - 
        #"The role of atmospheric conditions in the seasonal dynamics of North American migration flyways" - JOurnal of Biogeography
    if (species %in% c("Archilochusalexandri", "Selasphorusplatycercus", "Selasphorusrufus", "Selasphoruscalliope")) {
          
      #only use data west of the 103rd meridian (western flyway)
      west_yrdat = yrdat[which(yrdat$LONGITUDE <= -103),]
      
      #get daily weighted mean location 
      west_meanlocs = AlternateMeanLocs(west_yrdat, species, hexgrid, yreffort)
      
      #use GAM model to predict daily location along a smoothing line
      west_preds = EstimateDailyLocs(west_meanlocs)
      
      #use gam approach to estimate rough starting points for segmentation from the mean loc latitude data
      west_migration = round(Est3MigrationDates(west_meanlocs))
      
      #get Great Circle distances traveled each day between predicted daily locations
      west_dist = DailyTravel(west_preds, 4, 5, species, years[y], west_migration)
      
      #estimate migration speed for spring and fall
      west_speed = MigrationSpeed(west_dist, west_migration)
      
      #save a plot of the species migration route mapped onto continent with real observations
      pdf(file = paste(dirpath, "/WEST_trimmed-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
      BasePlotMigration(west_preds, west_yrdat, west_migration, elev, USAborder, Mexborder, Canborder, myext)
      dev.off() 
      
      #save a plot of the species migration mapped onto an elevation raster
      pdf(file = paste(dirpath, "/WEST_elev-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
      ElevPlotMigration(west_preds, west_yrdat, west_migration, elev, USAborder, Mexborder, Canborder, myext)
      dev.off() 
    }

    else {
      #create dummy variables for the eastern species. In this case, west == all variables
      west_preds = preds
      west_migration = migration
      west_speed = speed
    }

    #add year to preds, so we can save it to compare across years
    preds$year = years[y]
    west_preds$year = years[y]
    
    if (y == 1){
      pred_data = preds
      migdates = data.frame("spr_begin" = migration[[1]], "spr_end" = migration[[2]], 
                            "fal_begin" = migration[[2]], "fal_end" = migration[[3]],
                            "species" = species, "year" = years[y])
      migspeed = data.frame("spr" = speed[1], "fal" = speed[2], "species" = species, "year" = years[y])
      
      west_pred_data = west_preds
      west_migdates = data.frame("spr_begin" = west_migration[1], "spr_end" = west_migration[2], 
                                 "fal_begin" = west_migration[2], "fal_end" = west_migration[3],
                                 "species" = species, "year" = years[y])
      west_migspeed = data.frame("spr" = west_speed[1], "fal" = west_speed[2], "species" = species, "year" = years[y])
    }
    else{
      pred_data = rbind(pred_data, preds)
      dates = c(migration[[1]], migration[[2]], migration[[2]], migration[[3]], "species" = species, year = years[y])
      speed = c(speed, species, years[y])
      migdates = rbind(migdates, dates)
      migspeed = rbind(migspeed, speed)
      
      west_pred_data = rbind(west_pred_data, west_preds)
      west_dates = c(west_migration[[1]], west_migration[[2]], west_migration[[2]], west_migration[[3]], "species" = species, year = years[y])
      west_speed = c(west_speed, species, years[y])
      west_migdates = rbind(west_migdates, west_dates)
      west_migspeed = rbind(west_migspeed, west_speed)
    }
    
    if (y == length(years)){
      #write migration timing and speed data to file
      write.table(migdates, file = paste(getwd(), "/output_data/migration", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(migspeed, file = paste(getwd(), "/output_data/speed", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(pred_data, file = paste(getwd(), "/output_data/centroids", species, ".txt", sep=""), 
                  append=FALSE,row.names=FALSE)
      
      #write western flyway migration timing and speed data to file
      write.table(west_migdates, file = paste(getwd(), "/output_data/west_migration", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(west_migspeed, file = paste(getwd(), "/output_data/west_speed", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(west_pred_data, file = paste(getwd(), "/output_data/west_centroids", species, ".txt", sep=""), 
                  append=FALSE,row.names=FALSE)
    }
    
    rm(list=ls()[ls() %in% c("sitemap", "meanmap", "yrdat", "meanlocs", "migration", "preds", "dist", "mig_path", "speed",
                             "west_migration", "west_preds", "west_dist", "west_speed")])   # clears the memory of the map and year-level data
  }
  rm(list=ls()[!ls() %in% c("f", "files", "noam", "hexgrid", "effort", "pred_data", "migdates", 
                            "wd", "main", "gitpath","figpath", "USAborder", "Mexborder", "Canborder", "elev", "myext")])   # clears the memory of everything except the file list, iterator, and base map
}


#---------------------------------------------------------------------------------------
#                   compare migration rates and dates across species
#---------------------------------------------------------------------------------------
require(ggmap)
require(ggplot2)
require(plyr)
require(reshape2)
require(Rmisc)
require(sp)
require(raster)
require(gamm4)
require(chron)
require(fields)
require(RColorBrewer)
source(paste(gitpath, "/migration-fxns.r", sep=""))

setwd(wd)

# read in eBird data for migration speed, dates, and predicted path (should be in same order for species)
rfiles = list.files(path = paste(getwd(), "/output_data/", sep=""), pattern = "west_speed", full.names=TRUE)
mfiles = list.files(path = paste(getwd(), "/output_data/", sep=""), pattern = c("west_migration.*txt"), full.names=TRUE)
cfiles = list.files(path = paste(getwd(), "/output_data/", sep=""), pattern = "west_centroids.*.txt", full.names=TRUE)

# species ordered by data files, body sizes from Dunning 2008, migration distance from Nature Serve centroids
species = c("Black-chinned", "Ruby-throated", "Calliope", "Broad-tailed", "Rufous")
mass = c(3.4, 3.1, 2.65, 3.55, 3.5)
distance = c(1721.49, 2765.86, 3252.82, 1737.89, 4102.58)
spdata = data.frame(species, mass, distance, "lat_r2"= NA, "lon_r2" = NA, "spr_speed" = NA,
                    "fal_speed" = NA, "spr_date" = NA, "fal_date" = NA)


#------------------------------------------ ANALYZE THE DATA -------------------------------------

#-------------------- 
#       model to test variance in lat and lon across years, with year as a random effect
#-------------------- get gamm4 results using all years (2004-2013) and later years (2008-2013)
for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds_sub = preds[which(preds$year > 2007),]
  print(preds[1,1]) #species name
  years = c(2004:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    spring = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday < dates[y,2]),]
    fall = preds[which(preds$year == years[y] & preds$jday > dates[y,2] & preds$jday <= dates[y,4]),]
    
    if (y == 1){
      migpreds = between
      pred_spr = spring
      pred_fal = fall
    }
    else{
      migpreds = rbind(migpreds, between)
      pred_spr = rbind(pred_spr, spring)
      pred_fal = rbind(pred_fal, fall)
    }
  }
  
  # subset the seasonal data by the recent years (2008-2013)
  pred_spr_sub = pred_spr[which(pred_spr$year > 2007),]
  pred_fal_sub = pred_fal[which(pred_fal$year > 2007),]
  
  #gam analysis to determine variance across years, using all of the daily centroids (Jday 1-365) in each year
  lon_gam = gamm4(lon ~ s(jday, k=10), random = ~(1|year), data = preds_sub)
  print (paste("R2 for Longitude is:", round(summary(lon_gam$gam)$r.sq,4)))
  lat_gam = gamm4(lat ~ s(jday, k=10), random = ~(1|year), data=preds_sub)
  print (paste("R2 for Latitude is:", round(summary(lat_gam$gam)$r.sq,4)))
  
  #gam analysis to determine variance across years, using only spring centroids (start of spring to peak latitude date)
  lon_gam_spr = gamm4(lon ~ s(jday, k=10), random = ~(1|year), data=pred_spr_sub)
  print (paste("R2 for spring Longitude is:", round(summary(lon_gam_spr$gam)$r.sq,4)))
  lat_gam_spr = gamm4(lat ~ s(jday, k=10), random = ~(1|year), data=pred_spr_sub)
  print (paste("R2 for spring Latitude is:", round(summary(lat_gam_spr$gam)$r.sq,4)))
  
  #gam analsysis to determine variance across years, using only fall centroids (peak latitude to end of fall date)
  lon_gam_fal = gamm4(lon ~ s(jday, k=10), random = ~(1|year), data=pred_fal_sub)
  print (paste("R2 for fall Longitude is:", round(summary(lon_gam_fal$gam)$r.sq,4)))
  lat_gam_fal = gamm4(lat ~ s(jday, k=10), random = ~(1|year), data=pred_fal_sub)
  print (paste("R2 for fall Latitude is:", round(summary(lat_gam_fal$gam)$r.sq,4)))
  
  spdata[f,4] = summary(lat_gam$gam)$r.sq
  spdata[f,5] = summary(lon_gam$gam)$r.sq
}


#--------------------
#       get linear model results using years (2008-2013) and plot as barplot
#-------------------- 
lm_mig = data.frame("species"="Archilochusalexandri", "season" = "spring", "year" = 1, "lat_slope" = 1, "lat_r2" = 1, "lon_slope" = 1, "lon_r2" = 1)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  species = preds[1,1] #species name
  years = c(2008:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    spring = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday < dates[y,2]),]
    fall = preds[which(preds$year == years[y] & preds$jday > dates[y,2] & preds$jday <= dates[y,4]),]
    
    #get slope & r2 of spring and fall latitudinal migration
    spr_lm = LinearMigration(spring, years[y])
    spr_lm = data.frame("species" = species, "season"= "spring", spr_lm)
    fal_lm = LinearMigration(fall, years[y])
    fal_lm = data.frame("species" = species, "season"= "fall", fal_lm)
    lm_mig = rbind(lm_mig, spr_lm)
    lm_mig = rbind(lm_mig, fal_lm)
  }
}
lm_mig = lm_mig[-1,] #delete first row of dummy data

#plot the variance in estimated migration begin and end for all and for recent years
pdf(file = paste(figpath, "/linearslope_all_species.pdf", sep=""), width = 6, height = 5)

bxp_rate = ggplot(lm_mig, aes(season, abs(lat_slope), fill=season)) + geom_boxplot() + theme_classic() + 
  scale_fill_manual(values=c("cadetblue", "orange"), guide = "none") + 
  ylab("linear slope of seasonal migration") + theme(text = element_text(size=12)) + 
  scale_y_continuous(breaks = seq(0, 0.40, by = 0.10), limits = c(0,0.40)) + theme(text = element_text(size=12)) +
  facet_wrap(~species)

multiplot(bxp_rate, cols = 1)
dev.off()


#--------------------------- 
#       generate figures and table data for migration speed
#--------------------------- boxplots of migration speed for spring vs. fall for each species
rate = data.frame("spr" =1, "fal" = 1, "species" = "none", "year" = 1)
for (f in 1:length(rfiles)){
  sp_rate = read.table(rfiles[f], header=TRUE, sep=" ", fill=TRUE, comment.char="")
#  sp_rate = subset(sp_rate, year>2007) #use only years 2008-2013
  rate = rbind(rate, sp_rate)
  
  #print the mean and standard deviation of speed for each species (note: this includes all years, unless uncomment above line)
  print(sp_rate$species[1])
  print(paste("spring sd:", sd(sp_rate$spr)))
  print(paste("spring mean:", mean(sp_rate$spr)))
  print(paste("fall sd:", sd(sp_rate$fal)))
  print(paste("fall mean:", mean(sp_rate$fal)))
  print("")
  
  spdata[f,6] = mean(sp_rate$spr)
  spdata[f,7] = mean(sp_rate$fal)
}

rate = subset(rate, year > 2007) #subset to better-sampled years
r = melt(rate[,c(1,2,3,4)], id.vars = c("year", "species"))
names(r) = c("year", "species", "season", "rate")

#plot the variance in estimated migration speed for all and for recent years
pdf(file = paste(figpath, "/speed_all_species.pdf", sep=""), width = 15, height = 3)
  
bxp_speed = ggplot(r, aes(season, rate, fill=season)) + geom_boxplot() + theme_bw() + 
    scale_fill_manual(values=c("cadetblue", "orange"), guide="none") + ylab("km/day") + 
    scale_y_continuous(breaks = seq(0, 80, by = 20), limits = c(0,80)) + 
    facet_wrap(~species, nrow=1)
  
multiplot(bxp_speed, cols = 5)
dev.off() 


#--------------------------
#         generate figures and table data for migration dates
# ------------------------ Boxplots of the number of days +/- mean migration date, by species
dates = data.frame("spr_begin" = 1, "mid" = 1, "fal_end" = 1, "species" = "none", "year" = 1)

for (f in 1:length(mfiles)){
  sp_dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
# sp_dates = subset(sp_dates, year>2007)
  
  #Print species table data (note: this includes all years, unless uncomment above line)
  print(sp_dates$species[1])
  print(paste("spring begin median:", median(sp_dates$spr_begin)))
  print(paste("spring begin sd:", sd(sp_dates$spr_begin)))
  print(paste("lat peak median:", median(sp_dates$spr_end)))
  print(paste("lat peak sd:", sd(sp_dates$spr_end)))
  print(paste("fall end median:", median(sp_dates$fal_end)))
  print(paste("fall end sd:", sd(sp_dates$fal_end)))
  print("")
  
  #standardize dates, to get number of days +/- mean
  sp_dates = subset(sp_dates, year > 2007)
  
  spdata[f,8] = round(sd(sp_dates$spr_begin),4)
  spdata[f,9] = round(sd(sp_dates$fal_end), 4)
  
  sp_dates$spr_begin = sp_dates$spr_begin - mean(sp_dates$spr_begin)
  sp_dates$mid = sp_dates$spr_end - mean(sp_dates$spr_end)
  sp_dates$fal_end = sp_dates$fal_end - mean(sp_dates$fal_end)
  dates = rbind(dates, sp_dates[,c(1,7,4,5,6)])

}

dates = dates[-1,]
d = melt(dates, id.vars = c("species", "year"))
names(d) = c("species", "year", "season", "date")
  
#plot the variance in estimated migration begin and end for all and for recent years
pdf(file = paste(figpath, "/migdates_all_species.pdf", sep=""), width = 15, height = 3)
  
bxp_date = ggplot(d, aes(season, date, fill=season)) + geom_boxplot() + theme_bw() + 
  scale_fill_manual(values=c("cadetblue", "olivedrab3", "orange"), guide = "none") + 
  ylab("number of days -/+ mean date") + theme(text = element_text(size=12)) + 
  scale_y_continuous(breaks = seq(-40, 40, by = 20), limits = c(-40,40)) +
  facet_wrap(~species, nrow=1)
  
  multiplot(bxp_date)
  dev.off()


#------------------------------------------ PLOT THE DATA -------------------------------------


#------------------------------------
#       plot the data for species comparisons
#------------------------------------

ggplot(spdata, aes(distance, lat_r2)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Latitude R2 by date") + stat_smooth(method = "lm") + theme_classic()

ggplot(spdata, aes(distance, lon_r2)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Longitude R2 by date") + stat_smooth(method = "lm") + theme_classic()

ggplot(spdata, aes(distance, spr_speed)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Population spring migration speed (km/day)") + 
  stat_smooth(method = "lm", col = "cadetblue", fill = "cadetblue", alpha = 0.2) + 
  theme_classic() #+ geom_text(label=species)

ggplot(spdata, aes(distance, fal_speed)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Population fall migration speed (km/day)") + stat_smooth(method = "lm", col = "orange", fill = "orange", alpha = 0.2) +
  theme_classic() #+ geom_text(label=species)

ggplot(spdata, aes(distance, spr_date)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("sd in spring onset") + stat_smooth(method = "lm", col = "cadetblue", fill = "cadetblue", alpha = 0.2) +
  theme_classic()

ggplot(spdata, aes(distance, fal_date)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("sd in fall arrival") + stat_smooth(method = "lm", col = "orange", fill = "orange", alpha = 0.2) +
  theme_classic()


#---------------------------------
#       plot standard deviation in the daily centroid estimates across years 2008-2013
#---------------------------------
for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  species = preds[1,1] #species name
  years = c(2008:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]

    if (y == 1){
      migpreds = between
    }
    else{
      migpreds = rbind(migpreds, between)
    }
  }
  
  #compare location across the years using mean and sd for 2008:2013
  jdays = sort(unique(migpreds$jday))
  patherr = data.frame("jday"=1,"meanlat"=1, "sdlat"=1, "meanlon"=1, "sdlon"=1)
  outcount = 1
  for (j in min(jdays):max(jdays)){
    tmp = migpreds[which(migpreds$jday == j),]
    meanlat = mean(tmp$lat)
    sdlat = sd(tmp$lat)
    meanlon = mean(tmp$lon)
    sdlon = sd(tmp$lon)
    patherr[outcount,] = c(j, meanlat, sdlat, meanlon, sdlon)
    outcount = outcount + 1
  }
    
  # plot the standard deviation in daily lat and lon across the 10 years, and across 6 most recent years
  pdf(file = paste(dirpath, "/ErrorinDailyLocs", species, ".pdf", sep=""), width = 5, height = 8)
  
  ymax = max(c(patherr$sdlat, patherr$sdlon),na.rm=TRUE) 
  sdlocs = ggplot(patherr, aes(jday, sdlat)) + geom_point(size=1) + theme_classic() + 
    ggtitle(paste(species, "sd in daily locs", min(years), "-", max(years))) +
    scale_y_continuous(breaks = seq(0, ymax, by = 0.5), limits = c(0, ymax)) + 
    scale_x_continuous(breaks = seq(0, 366, by = 25), limits = c(0, 366)) + 
    geom_point(aes(jday, sdlon), col = "indianred", size=1) + ylab("stdev daily lat (black) and lon (red)")

  lonlatday = ggplot(patherr, aes(sdlon, sdlat, col=jday)) + geom_point(size=1) + theme_classic() +
    scale_y_continuous(breaks = seq(0, ymax, by = 0.5), limits = c(0, ymax))  +
    scale_x_continuous(breaks = seq(0, ymax, by = 0.5), limits = c(0, ymax)) 
 
  multiplot(sdlocs, lonlatday, cols = 1)
  dev.off()
}
  
  
#---------------------------------
#       plot all migration routes for a species on a map with elevation raster
#---------------------------------
pdf(file = paste(figpath, "/elev-route_summary_all_species.pdf", sep=""), width = 7, height = 4.5)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds = subset(preds, year > 2007)
  elev = raster("alt_5m_bil/alt.bil")  #elevation layers
  myext = c(-175, -50, 15, 75) #set extent to North America
  species = preds[1,1] #species name
  
  AllMigration(preds, elev, myext, species)
}
dev.off() 


#---------------------------------
#       plot standard error in predicted centroids across years
#---------------------------------
pdf(file=paste(figpath, "/se_corlon-lat_all_species.pdf", sep=""), width = 10, height = 7)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  species = preds[1,1] #species name
  years = c(2004:2013)

  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
  
    if (y == 1){ migpreds = between }
    else{ migpreds = rbind(migpreds, between) }
  }
  
  if (species == "Selasphoruscalliope") {by = 1}
  else {by = 0.5}
  
  ymax = max(c(migpreds$lat_se, migpreds$lon_se))
  latlon = ggplot(migpreds, aes(lon_se, lat_se)) + ggtitle(species) +
    xlab("estimated longitude standard error") + ylab("estimated latitude standard error") +
  geom_point(alpha = 0.5) + theme_classic() + facet_wrap(~year) +
  theme(text = element_text(size=12)) +
  scale_y_continuous(breaks = seq(0, ymax, by = by), limits = c(0, ymax)) +
  scale_x_continuous(breaks = seq(0, ymax, by = by), limits = c(0, ymax))
  multiplot(latlon, cols = 1)
}
dev.off()

#latlon = ggplot(migpreds2, aes(lon_se, lat_se)) + xlab("estimated longitude standard error") + 
#ylab("estimated latitude standard error") + geom_point(alpha=0.5, aes(col=cutoff)) + 
#theme_bw() + facet_grid(year~spname) + theme(text=element_text(size=12)) + guides(colour=FALSE)

#---------------------------------
#       plot standard error in predicted centroids across years, by julian date
#---------------------------------
pdf(file = paste(figpath, "/error_se-latlon_all_species.pdf", sep=""), width = 10, height = 4)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = subset(dates, year > 2007)
  species = preds[1,1] #species name
  years = c(2008:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    
    if (y == 1){ migpreds = between }
    else{ migpreds = rbind(migpreds, between) }
  }

  ymax = max(c(migpreds$lat_se, migpreds$lon_se)) 
  lat = ggplot(migpreds, aes(jday, lat_se, col=as.factor(year))) + geom_point(size=1) + theme_classic() +
  geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
  geom_vline(xintercept = c(dates$fal_end), col = "orange") + ggtitle(species) +
  xlab("Julian Day") + ylab("latitude centroid standard error") +
  scale_y_continuous(breaks = seq(0, ymax, by = 0.25), limits = c(0, ymax))+
  theme(text = element_text(size=12))

  lon = ggplot(migpreds, aes(jday, lon_se, col=as.factor(year))) + geom_point(size=1) + theme_classic() +
  geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
  geom_vline(xintercept = c(dates$fal_end), col = "orange") + ggtitle(species) +
  xlab("Julian Day") + ylab("longitude centroid standard error") +
  scale_y_continuous(breaks = seq(0, ymax, by = 0.25), limits = c(0, ymax)) +
  theme(text = element_text(size=12))

  multiplot(lat, lon, cols = 2)
}
dev.off()


#---------------------------------
#       plot predicted latitude and longitude as distribution across the years for all species
#---------------------------------
# save plots comparing daily lat and long and migration date across the years
pdf(file = paste(figpath, "/AllYears_lon-lat_all_species.pdf", sep=""), width = 8, height = 5)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds = subset(preds, year > 2007)
  dates = subset(dates, year > 2007)
  species = preds[1,1] #species name
  
  yrlylat = ggplot(preds, aes(jday, lat, col=year)) + geom_point(size=1) + theme_classic() +
    geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
    geom_vline(xintercept = c(dates$spr_end), col = "olivedrab3") +
    geom_vline(xintercept = c(dates$fal_end), col = "orange") +
    scale_x_continuous(breaks = seq(0, 365, by = 30)) + 
    theme(text = element_text(size=20)) + ggtitle(species)
  
  yrlylon = ggplot(preds, aes(jday, lon, col=year)) + geom_point(size=1) + theme_classic() +
    geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
    geom_vline(xintercept = c(dates$spr_end), col = "olivedrab3") +
    geom_vline(xintercept = c(dates$fal_end), col = "orange") +
    scale_x_continuous(breaks = seq(0, 365, by = 30)) + 
    theme(text = element_text(size=20))

  multiplot(yrlylat, cols = 1)
  multiplot(yrlylon, cols = 1)
}
dev.off()

#----------------------------------------------------------
#       Makes Figure B3. Observations across the years (2004-2013)
#       For Appendix B
#----------------------------------------------------------

#NOTE!!: For this to work, make sure files and mfiles is in the same species-order!!
for (f in 1:length(files)) {
  
  #read in raw data
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = subset(dates, year > 2007)
  
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                    "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                    "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")
  
  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)
  
  #grab species name for later identification
  species = humdat$SCI_NAME[1]
  species = gsub("\"", "", species, fixed=TRUE)
  years = c(2004:2013)
  
  for (y in 1:length(years)){
    dat = subset(humdat, YEAR==years[y])
    yrobs = data.frame(table(dat$DAY))
    yrobs$year = years[y]
    
    if(y == 1) { obs = yrobs}
    else{ obs = rbind(obs, yrobs)}
  }
    names(obs) = c("jday", "freq")
    obs$jday = as.numeric(obs$jday)
    obs$freq = as.numeric(obs$freq)
  ymax = max(obs$freq) + 25
  
  ggplot(obs, aes(jday, freq)) + geom_point(alpha=0.4) + xlab("Julian day of Year") + ylab("Number of Checklists") + 
    theme_classic() + theme(text = element_text(size=12)) +     
    geom_smooth(se=T, method='gam', formula=y~s(x, k=40), gamma=1.5) +
    scale_x_continuous(breaks = seq(0, 365, by = 50), limits = c(0,365)) + 
    scale_y_continuous(breaks = seq(0, ymax, by = 50)) +
    geom_vline(xintercept = dates[,1], col = "cadetblue", size = 0.5) +
    geom_vline(xintercept = dates[,4], col = "orange", size = 0.5) +
    geom_vline(xintercept = dates[,2], col = "olivedrab3", size = 0.5) 

  ggsave(file=paste(figpath, "/B3_occurrences", species, years[y], ".tiff", sep=""), dpi=600, height=3, width=4)
}


#-----------------------------------------------------------
#       Make synthetic panel figure for manuscript  - FIGURE 1
#       Make parts separately, and bring back together 
#         in Illustrator or Inkscape
#-----------------------------------------------------------
#reorder files to match manuscript ordering
files = c(files[4],files[1],files[2],files[3],files[5])
cfiles = c(cfiles[2],cfiles[1],cfiles[4],cfiles[3],cfiles[5])
mfiles = c(mfiles[2],mfiles[1],mfiles[4],mfiles[3],mfiles[5])

for (f in 1:length(files)) {
  
  #read in raw data
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                    "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                    "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")
  
  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)
  
  #grab species name for later identification
  species = humdat$SCI_NAME[1]
  species = gsub("\"", "", species, fixed=TRUE)
   
  #plot the geographic number of checklists for the species, over all the years  
  #find the number of obs in each cell
  t = table(as.factor(humdat$POLYFID))
  
  #Merge the count data for the hexes with all the hexes in the map
  df = data.frame(POLYFID = names(t), count=as.numeric(t))
  df2 = data.frame(POLYFID = unique(hexgrid$POLYFID))
  df3 = merge(df2, df, all.x=TRUE)
  df3$species = species
  
  #combine all the datasets so we can get the colors on the same scale
  if (f == 1) {
    df3.1 = df3
    splist = species
  }
  
  else{
    df3.1 = rbind(df3.1, df3)
    splist = c(splist, species)
  }
}

# Set colors and legend scale by all species (e.g. some will be red, some will be shades of yellow)
  #matches colors with the number of observations
  yltord = colorRampPalette(brewer.pal(9, "YlOrRd"))(length(unique(df3.1$count)))
  cols = data.frame(id=c(NA,sort(unique(df3.1$count))), cols=yltord, stringsAsFactors=FALSE)
  df4 = merge(df3.1, cols, by.x="count", by.y="id")
  #set scale for legend
  vls = sort(unique(round(cols$id/500)*500))
  vls[1] = 1
  cols2 = rev(heat.colors(length(vls)))

#separate back out by species for plotting
for (s in 1:length(splist)){
  df4.1 = subset(df4, species == splist[s])
  df5 = merge(hexgrid, df4.1, by.x="POLYFID", by.y="POLYFID", all.x=TRUE)
  df5$cols = ifelse(is.na(df5$count), "white", df5$cols)  #hexes with no counts are white
  df5 = df5[order(df5$POLYFID),]

  #make a map with hexes colored by the number of times the species was observed in a given hex
  setEPS()
  postscript(file = paste(figpath, "/fig1_col1_", splist[s], ".eps", sep=""), width = 3, height = 3)
  plot(NA, NA, xlim = c(-140,-60), ylim=c(15,55),xlab="", ylab="", axes=FALSE)
    plot(hexgrid, col=df5$cols, border = "white", lwd = 0.25, las=1, add=TRUE)
    mtext(side=2,line=2, splist[s])
    map("worldHires", c("usa", "canada", "mexico"), add=TRUE, cex = 0.25)
  dev.off()
  
  #plot the legend separately
  setEPS()
  postscript(file = paste(figpath, "/fig1_col1_legend.eps", sep=""), width = 3, height = 3)
  plot(NA, NA, xlim = c(0,5), ylim=c(0,5), axes=FALSE, xlab = "", ylab="")
  legend.col(col = cols[,2], lev = sort(unique(df4$count)))
  dev.off()
}

for (f in 1:length(files)) {
  #read in the centroid and migration data (by western flyway), use data for years 2008-2013
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds_sub = preds[which(preds$year > 2007),]
  dates_sub = dates[which(dates$year > 2007),]
  species = preds[1,1]
  years = c(2008:2013)
  
# plot the migration routes in the next figure
preds_sub$month = as.factor(preds_sub$month)
cols3 = data.frame(id=c(sort(unique(preds_sub$month))), cols=tim.colors(length(unique(preds_sub$month))), stringsAsFactors=FALSE)
preds_sub = merge(preds_sub, cols3, by.x="month", by.y="id")
#set color scale
vls = sort(unique(round(cols3$id)))
vls[1] = 1
cols4 = tim.colors(length(vls))

setEPS()
postscript(file = paste(figpath, "/fig1_col2_", species, ".eps", sep=""), width = 3, height = 3)
plot(preds_sub$lon, preds_sub$lat, col=preds_sub$cols, pch=19, cex=0.25, ylab="", xlab="", xlim = c(-140, -60), ylim = c(15, 55),
     cex.lab = 1, cex.axis=1, axes=FALSE)
  map("worldHires", c("usa", "canada", "mexico"), add=TRUE)
  points(preds_sub$lon, preds_sub$lat, col=preds_sub$cols, pch=19, cex=0.25)
dev.off()

#plot legend separately  
setEPS()
postscript(file = paste(figpath, "/fig1_col2_legend.eps", sep=""), width = 3, height = 3)
plot(NA, NA, xlim = c(0,5), ylim=c(0,5), axes=FALSE, xlab = "", ylab="")
  legend("bottomleft", legend=vls, pch=22, pt.bg=cols4, pt.cex=0.75, cex=0.75, bty="n",
       col="black", title="month", x.intersp=1, y.intersp=0.5)  
dev.off()

# plot the latitudinal patterns with estimated dates of migration
setEPS()
postscript(file = paste(figpath, "/fig1_col4_", species, ".eps", sep=""), width = 3, height = 3)
latmin = ((min(preds_sub$lat)%/%5+1)*5)-5
latmax = ((max(preds_sub$lat)%/%5+1)*5) + 5 

par(bty="l")
plot(preds_sub$jday, preds_sub$lat, pch = 19, xlab = "", ylab = "", 
     cex.axis = 1, col = "grey20", cex = 0.25)
  abline(v=dates_sub$spr_begin, col="cadetblue")
  abline(v=dates_sub$spr_end, col = "olivedrab3")
  abline(v=dates_sub$fal_end, col = "orange")
dev.off()

}




#---------------------------------
#       plot predicted latitude with 95% confidence intervals
#---------------------------------
# save plots comparing daily lat and long and migration date across the years

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds = subset(preds, year > 2007)
  dates = subset(dates, year > 2007)
  species = preds[1,1] #species name
  
  #calculate 95% CI
  preds$lat_ucl = preds$lat + 1.96 * preds$lat_se
  preds$lat_lcl = preds$lat - 1.96 * preds$lat_se
  preds$lon_ucl = preds$lon + 1.96 * preds$lon_se
  preds$lon_lcl = preds$lon - 1.96 * preds$lon_se
  
  years = c(2008:2013)
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    spring = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday < dates[y,2]),]
    fall = preds[which(preds$year == years[y] & preds$jday > dates[y,2] & preds$jday <= dates[y,4]),]
    
    if (y == 1){
      migpreds = between
      pred_spr = spring
      pred_fal = fall
    }
    else{
      migpreds = rbind(migpreds, between)
      pred_spr = rbind(pred_spr, spring)
      pred_fal = rbind(pred_fal, fall)
    }
  }
     
  # plot spring and fall separately, color-coded to compare overlap
  seasons = ggplot(pred_spr, aes(lon, lat), col = year, group=year, order.by=jday) + theme_classic() + 
    geom_rect(data=pred_spr, aes(xmin=lon_lcl,ymin=lat_lcl,xmax=lon_ucl,ymax=lat_ucl, group=year), fill="cadetblue", alpha=0.02) +
    geom_path(aes(group=year)) + 
    geom_rect(data=pred_fal, aes(xmin=lon_lcl,ymin=lat_lcl,xmax=lon_ucl,ymax=lat_ucl, group=year), fill="orange", alpha=0.02) +
    geom_path(data=pred_fal, aes(lon, lat, group=year)) + 
    theme(text = element_text(size=12)) + xlab("longitude") + ylab("latitude")
  
  pdf(file = paste(figpath, "/fig1_col3_", species, ".pdf", sep=""), width = 3, height = 3)
  multiplot(seasons, cols = 1)
  dev.off()
}



#---------------------------------
#       Figure B1 for appendix, total eBird effort 2004-2013
#---------------------------------

#find the number of obs in each cell
t = table(as.factor(effort$POLYFID))

#Merge the count data for the hexes with all the hexes in the map
df = data.frame(POLYFID = names(t), count=as.numeric(t))
df2 = data.frame(POLYFID = unique(hexgrid$POLYFID))
df3 = merge(df2, df, all.x=TRUE)

#matches colors with the number of observations
#   # Set colors and legend scale by all species (e.g. some will be red, some will be shades of yellow)
yltord = colorRampPalette(brewer.pal(9, "YlOrRd"))(length(unique(df3$count)))
cols = data.frame(id=c(NA,sort(unique(df3$count))), cols=yltord, stringsAsFactors=FALSE)
df4 = merge(df3, cols, by.x="count", by.y="id")
df5 = merge(hexgrid, df4, by.x="POLYFID", by.y="POLYFID", all.x=TRUE)

#   #set scale for legend
vls = sort(unique(round(cols$id/500)*500))
vls[1] = 1
cols2 = rev(heat.colors(length(vls)))

#hexes with no counts are white
df5$cols = ifelse(is.na(df5$count), "white", df5$cols)
df5 = df5[order(df5$POLYFID),]

#make a map with hexes colored by the number of times the species was observed in a given hex
setEPS()
postscript(file = paste(figpath, "/FigureB1.eps", sep=""), width = 5.5, height = 4)
plot(NA, NA, xlim = c(-170,-50), ylim=c(15,75),xlab="", ylab="", axes=FALSE)
plot(hexgrid, col=df5$cols, border = "white", lwd = 0.25, las=1, add=TRUE)
map("worldHires", c("usa", "canada", "mexico"), add=TRUE, cex = 0.25)
dev.off()

#plot the legend separately
setEPS()
postscript(file = paste(figpath, "/figB1_col1_legend.eps", sep=""), width = 3, height = 3)
plot(NA, NA, xlim = c(0,5), ylim=c(0,5), axes=FALSE, xlab = "", ylab="")
legend.col(col = cols[,2], lev = sort(unique(df4$count)))
dev.off()


#--------------------------------------------------
#   wrt question about number of obs in eastern US
#--------------------------------------------------
for (f in 1:length(files)){
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")

  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                  "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                  "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")

  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)

  #grab species name for later identification
  species = humdat$SCI_NAME[1]

  #subset eastern observations
  east = subset(humdat, LONGITUDE > -103)
  eastwinter = subset(east, MONTH %in% c(11, 12, 1, 2, 3))
  plot(table(east$YEAR), main=species)
  plot(table(eastwinter$YEAR), main=species)
}
  

#----------------------------------------------
#       Reviewer comment: detecting trends
#----------------------------------------------

#aggregate all the dates files
for (f in 1:length(mfiles)){
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  if (f == 1) { d = dates }
  else { d = rbind(d, dates) }
}
d = d[,-2]
d = subset(d, year > 2007)
names(d) = c("spring_begin", "peak_latitude", "autumn_end", "species", "year")

#plot the data
spring = ggplot(d, aes(year, spring_begin, group=species)) + geom_line(aes(linetype=species)) + 
  theme_bw() + ylab("begin spring migration")
breed = ggplot(d, aes(year, peak_latitude, group=species)) + geom_line(aes(linetype=species)) + 
  theme_bw() + ylab("reach peak latitude")
autumn = ggplot(d, aes(year, autumn_end, group=species)) + geom_line(aes(linetype=species)) + 
   theme_bw() + ylab("end autumn migration")

pdf(file = paste(figpath, "/migration_trends.pdf", sep=""), width = 6, height = 7)
  multiplot(spring, breed, autumn, cols=1)
dev.off()


library(plyr)
# Break up d by species, then fit the specified model to each piece and return a list
# SPRING
models <- dlply(d, "species", function(df) 
  lm(spring_begin ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, anova, .print = TRUE)
l_ply(models, summary, .print = TRUE)

# PEAK LAT
models <- dlply(d, "species", function(df) 
  lm(peak_latitude ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, anova, .print = TRUE)

# AUTUMN
models <- dlply(d, "species", function(df) 
  lm(autumn_end ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, anova, .print = TRUE)
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141215_0357"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)

#'@title arrange_ggplot2
#'@description
#'Arranges ggplot2 plot objects in a grid using code from Stephen Turner's website.
#'from http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html
#'use pdf(); arrange(p1,p2,ncol=1); dev.off() to save the plot to a file
#'@param list list of plot objects
#'@param ncol number of columns, can be null
#'@param nrow number of rows, can be null
#'@param as.table boolean, determines order in grid
#'@export

arrange_ggplot2 <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
  library(ggplot2)
  library(grid)
  vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
  
  dots <- list(...)
  n <- length(dots)
  if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
  if(is.null(nrow)) { nrow = ceiling(n/ncol)}
  if(is.null(ncol)) { ncol = ceiling(n/nrow)}
  ## NOTE see n2mfrow in grDevices for possible alternative
  grid.newpage()
  pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
  ii.p <- 1
  for(ii.row in seq(1, nrow)){
    ii.table.row <- ii.row	
    if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
    for(ii.col in seq(1, ncol)){
      ii.table <- ii.p
      if(ii.p > n) break
      print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
      ii.p <- ii.p + 1
    }
  }
}

#'@title vertical_dotchart
#'@description
#'Produces a vertical dot chart, with a metric variable giving the length of a horizontal 
#'line segment and a dot colored by a grouping variable.  Each row in the data frame becomes a 
#'row in the dotchart.  The y variable is a label for each row, and rows can be grouped
#'by a grouping variable.  The plot can be sorted in descending order of the x metric variable,
#'or grouped by the grouping variable and then sorted.   
#'
#'@param df Data frame to be plotted
#'@param x_var Name of the metric variable to be plotted, as a string
#'@param x_label Name of the metric variable as a plot legend string
#'@param y_var Name of the categorical variable labeling each row in the data frame
#'@param y_label Name of the categorical variable, as a plot legend string
#'@param y_group_var Name of a categorical variable which groups the rows
#'@param legend_title Title of the legend for groups, defaults to "Experiment Group"
#'@param sort.by.xvar Boolean flag to sort rows by the metric variable, defaults to TRUE
#'@param group.by.ygroup Boolean flag to sort groups of rows by the grouping variable, defaults to TRUE
#'@return ggplot2 object
#'@export

vertical_dotchart <- function(df, 
                              x_var = xvar, 
                              x_label = xlabel, 
                              y_var = yvar, 
                              y_label = "Experiment", 
                              y_group_var = NULL, 
                              legend_title = "Experiment Group",
                              sort.by.xvar = TRUE, 
                              group.by.ygroup = TRUE) {
  
  require(ggplot2)
  require(ggthemes)

  # prevent a conflict if the user doesn't set the flag but leaves off a grouping variable
  if(is.null(y_group_var)) {
    group.by.ygroup = FALSE
  }
  
  if(sort.by.xvar == TRUE) {
      df$yvar_sorted <- reorder(df[[y_var]], df[[x_var]])
      plt <- ggplot(df, aes_string(x = x_var, y = "yvar_sorted")) 
    } else {
      plt <- ggplot(df, aes_string(x = x_var, y = y_var))
    }

  plt <- plt + ylab(y_label)
  plt <- plt + xlab(x_label)
  
  if(!is.null(y_group_var)) {
    plt <- plt + geom_segment(aes_string(yend = yvar_sorted), xend = 0, color = "grey50")
    plt <- plt + geom_point(size = 3, aes_string(color = y_group_var)) + labs(color = legend_title)
  } else {
    plt <- plt + geom_segment(aes_string(yend = y_var), xend = 0, color = "grey50")
    plt <- plt + geom_point(size = 3)
  }

  plt <- plt + theme_pander()
  plt <- plt + theme(panel.grid.major.x = element_blank(),
                     panel.grid.minor.x = element_blank(),
                     strip.background = element_blank(), strip.text = element_blank())
  if(group.by.ygroup == TRUE) {
    form <- as.formula(paste(y_group_var, "~", ".", sep = " "))
    plt <- plt + facet_grid(form, scales = "free_y", space = "free_y")
  }
  
  plt
}







#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141215_0357"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup", "Insert", "Delete", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.3
  pdf(outFileName, family = "Times", width = 9, height = 3.5)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(6.5,3.5,0,0) + 0.1)
  boxplot(selection, ylim=range(-0.1, 1.0), las=2,
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=TRUE, add.comment=TRUE, 
                               add.row.margin=TRUE, add.col.margin=TRUE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000", halign='right')
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = 1, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1, spacer_rows=2) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 1 + spacer_rows
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#' This R script will process all R mardown files (those with in_ext file extention,
#' .rmd by default) in the current working directory. Files with a status of
#' 'processed' will be converted to markdown (with out_ext file extention, '.markdown'
#' by default). It will change the published parameter to 'true' and change the
#' status parameter to 'publish'.
#' 
#' @param path_site path to the local root storing the site files
#' @param dir_rmd directory containing R Markdown files (inputs)
#' @param dir_md directory containing markdown files (outputs)
#' @param url_images where to store/get images created from plots directory +"/" (relative to path_site)
#' @param out_ext the file extention to use for processed files.
#' @param in_ext the file extention of input files to process.
#' @param recursive should rmd files in subdirectories be processed.
#' @return nothing.
#' @author Jason Bryer <jason@bryer.org> edited by Andy South
rmd2md <- function( path_site = getwd(),
                    dir_rmd = "_rmd",
                    dir_md = "_posts",                              
                    #dir_images = "figures",
                    url_images = "figures/",
                    out_ext='.md', 
                    in_ext='.rmd', 
                    recursive=FALSE) {
  
  require(knitr, quietly=TRUE, warn.conflicts=FALSE)

  #andy change to avoid path problems when running without sh on windows 
  files <- list.files(path=file.path(path_site,dir_rmd), pattern=in_ext, ignore.case=TRUE, recursive=recursive)
  
  for(f in files) {
    message(paste("Processing ", f, sep=''))
    content <- readLines(file.path(path_site,dir_rmd,f))
    frontMatter <- which(substr(content, 1, 3) == '---')
    if(length(frontMatter) >= 2 & 1 %in% frontMatter) {
      statusLine <- which(substr(content, 1, 7) == 'status:')
      publishedLine <- which(substr(content, 1, 10) == 'published:')
      if(statusLine > frontMatter[1] & statusLine < frontMatter[2]) {
        status <- unlist(strsplit(content[statusLine], ':'))[2]
        status <- sub('[[:space:]]+$', '', status)
        status <- sub('^[[:space:]]+', '', status)
        if(tolower(status) == 'process') {
          #This is a bit of a hack but if a line has zero length (i.e. a
          #black line), it will be removed in the resulting markdown file.
          #This will ensure that all line returns are retained.
          content[nchar(content) == 0] <- ' '
          message(paste('Processing ', f, sep=''))
          content[statusLine] <- 'status: publish'
          content[publishedLine] <- 'published: true'
          
          #andy change to path
          outFile <- file.path(path_site, dir_md, paste0(substr(f, 1, (nchar(f)-(nchar(in_ext)))), out_ext))
                   
          #render_markdown(strict=TRUE)
          #render_markdown(strict=FALSE) #code didn't render properly on blog
          
          #andy change to render for jekyll
          render_jekyll(highlight = "pygments")
          #render_jekyll(highlight = "prettify") #for javascript
          
          opts_knit$set(out.format='markdown') 
                    
          # andy BEWARE don't set base.dir!! it caused me problems
          # "base.dir is never used when composing the URL of the figures; it is 
          # only used to save the figures to a different directory. 
          # The URL of an image is always base.url + fig.path"
          # https://groups.google.com/forum/#!topic/knitr/18aXpOmsumQ
                    
          opts_knit$set(base.url = "/")
          opts_chunk$set(fig.path = url_images)                     
          
          #andy I could try to make figures bigger
          #but that might make not work so well on mobile
          #opts_chunk$set(fig.width  = 8.5,
          #               fig.height = 5.25)
          
          try(knit(text=content, output=outFile), silent=FALSE)
          
        } else {
          warning(paste("Not processing ", f, ", status is '", status, 
                        "'. Set status to 'process' to convert.", sep=''))
        }
      } else {
        warning("Status not found in front matter.")
      }
    } else {
      warning("No front matter found. Will not process this file.")
    }
  }
  invisible()
}REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	;--                 [objects images shapes sounds strings]
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   30]
		%PlanetaZluta      [600     1300   100    250   30]
		%PlanetaTermiti    [600     1300   100    290   30]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 300 30]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 0.5 * length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141215_0357"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")


createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)


menu <- function(){
	print( "------------------------------------------------------" )
	print( "-------------------------MENU-------------------------" )
	print( "------------------------------------------------------" )
	print( "-------ESCOLHA O ALGORITMO QUE DESEJA EXECUTAR--------" )
	print( "-------[1] - DENFIS+COG-------------------------------" )
	print( "-------[2] - HyFIS+FIRST.MAX--------------------------" )
	print( "-------[3] - HyFIS+LAST.MAX---------------------------" )
	print( "-------[4] - WM+FIRST.MAX-----------------------------" )
	print( "-------[5] - WM+LAST.MAX------------------------------" )
	print( "-------[6] - WM+COG-----------------------------------" )
	print( "-------[7] - GFS.LT.RS+COG----------------------------" )
	print( "-------[8] - GFS.MOGUL+COG----------------------------" )
	print( "-------[9] - PLOTAR VARIAVEIS LINGUISTICAS------------" )
	print( "-------[10] - EXECUTAR TODOS OS ALGORITMOS------------" )
	print( "-------[11] - COMPARAR OS RESULTADOS REAIS X PREDITOS-" )
	print( "-------[0] - SAIR-------------------------------------" )
	print( "------------------------------------------------------" )
}
runall <- function(){
	performance <- c(1:4)
	source("traffic-WM+FIRST.MAX.r")
	performance[1] <- MSE
	performance[5] <- RMSE
	source("traffic-WM+LAST.MAX.r")
	performance[2] <- MSE
	performance[6] <- RMSE
	source("traffic-HyFIS+FIRST.MAX.r")
	performance[3] <- MSE
	performance[7] <- RMSE
	source("traffic-HyFIS+LAST.MAX.r")
	performance[4] <- MSE
	performance[8] <- RMSE
	print( "-------------------RESULTADOS-------------------------" )
	print( "-------[1] - WM+FIRST.MAX---------MSE: " )
	print(performance[1])
	print( "-------[2] - WM+LAST.MAX----MSE: " )
	print(performance[2])
	print( "-------[3] - HyFIS+FIRST.MAX------MSE: " )
	print(performance[3])
	print( "-------[4] - HyFIS+LAST.MAX-MSE: " )
	print(performance[4])
	print( "-------[1] - WM+FIRST.MAX---------RMSE: " )
	print(performance[5])
	print( "-------[2] - WM+LAST.MAX----RMSE: " )
	print(performance[6])
	print( "-------[3] - HyFIS+FIRST.MAX------RMSE: " )
	print(performance[7])
	print( "-------[4] - HyFIS+LAST.MAX-RMSE: " )
	print(performance[8])
}

clear <- function() {
	elements <- ls() [! ls() %in% c("menu","n","runall", "clear") ]
	rm(list=elements)
}

comparisson <- function(){
    result.test <- cbind(traffic.class , res.test)
    x2 <- seq(from = 1, to = nrow(result.test))
    plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
    lines(x2, result.test[, 2], col="blue", type = "l")
}

readinteger <- function()
{ 
    n <- readline(prompt="Oque deseja? ")
        if(!grepl("^[0-9]+$",n))
        {
            return(readinteger())
        }

    return(as.integer(n))
}

menu()

n <- readinteger()
while(TRUE){
	if(is.na(n)){break}  # breaks when hit enter
    if(n == 0) break;
	if(n != 6) clear()
	if(n == 1) 	{     clear(); source("traffic-DENFIS+COG.r")		}
	else if(n == 2) { clear(); source("traffic-HyFIS+FIRST.MAX.r") }
	else if(n == 3) { clear(); source("traffic-HyFIS+LAST.MAX.r")  }
	else if(n == 4) { clear(); source("traffic-WM+FIRST.MAX.r")    }
	else if(n == 5) { clear(); source("traffic-WM+LAST.MAX.r")     }
	else if(n == 6) { clear(); source("traffic-WM+COG.r")			}
	else if(n == 7) { clear(); source("traffic-LT+COG.r")			}
	else if(n == 8) { clear(); source("traffic-MOGUL+COG.r")		}
	else if(n == 9) plotMF(object.cls)
	else if(n == 10) runall()
    else if(n == 11) comparisson()
	menu()	
        n <- readinteger()
}







menu <- function(){
	print( "------------------------------------------------------" )
	print( "-------------------------MENU-------------------------" )
	print( "------------------------------------------------------" )
	print( "-------ESCOLHA O ALGORITMO QUE DESEJA EXECUTAR--------" )
	print( "-------[1] - DENFIS+COG-------------------------------" )
	print( "-------[2] - HyFIS+FIRST.MAX--------------------------" )
	print( "-------[3] - HyFIS+LAST.MAX---------------------------" )
	print( "-------[4] - WM+FIRST.MAX-----------------------------" )
	print( "-------[5] - WM+LAST.MAX------------------------------" )
	print( "-------[6] - WM+COG-----------------------------------" )
	print( "-------[7] - GFS.LT.RS+COG----------------------------" )
	print( "-------[8] - GFS.MOGUL+COG----------------------------" )
	print( "-------[9] - PLOTAR VARIAVEIS LINGUISTICAS------------" )
	print( "-------[10] - EXECUTAR TODOS OS ALGORITMOS------------" )
	print( "-------[11] - COMPARAR OS ALGORITMOS------------------" )
	print( "-------[0] - SAIR-------------------------------------" )
	print( "------------------------------------------------------" )
}
runall <- function(){
	performance <- c(1:4)
	source("traffic-WM+FIRST.MAX.r")
	performance[1] <- MSE
	performance[5] <- RMSE
	source("traffic-WM+LAST.MAX.r")
	performance[2] <- MSE
	performance[6] <- RMSE
	source("traffic-HyFIS+FIRST.MAX.r")
	performance[3] <- MSE
	performance[7] <- RMSE
	source("traffic-HyFIS+LAST.MAX.r")
	performance[4] <- MSE
	performance[8] <- RMSE
	print( "-------------------RESULTADOS-------------------------" )
	print( "-------[1] - WM+FIRST.MAX---------MSE: " )
	print(performance[1])
	print( "-------[2] - WM+LAST.MAX----MSE: " )
	print(performance[2])
	print( "-------[3] - HyFIS+FIRST.MAX------MSE: " )
	print(performance[3])
	print( "-------[4] - HyFIS+LAST.MAX-MSE: " )
	print(performance[4])
	print( "-------[1] - WM+FIRST.MAX---------RMSE: " )
	print(performance[5])
	print( "-------[2] - WM+LAST.MAX----RMSE: " )
	print(performance[6])
	print( "-------[3] - HyFIS+FIRST.MAX------RMSE: " )
	print(performance[7])
	print( "-------[4] - HyFIS+LAST.MAX-RMSE: " )
	print(performance[8])
}

clear <- function() {
	elements <- ls() [! ls() %in% c("menu","n","runall", "clear") ]
	rm(list=elements)
}

comparisson <- function(){
    result.test <- cbind(traffic.class , res.test)
    x2 <- seq(from = 1, to = nrow(result.test))
    plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
    lines(x2, result.test[, 2], col="blue", type = "l")
}

readinteger <- function()
{ 
    n <- readline(prompt="Oque deseja? ")
        if(!grepl("^[0-9]+$",n))
        {
            return(readinteger())
        }

    return(as.integer(n))
}

menu()

n <- readinteger()
while(TRUE){
	if(is.na(n)){break}  # breaks when hit enter
    if(n == 0) break;
	if(n != 6) clear()
	if(n == 1) 	{     clear(); source("traffic-DENFIS+COG.r")		}
	else if(n == 2) { clear(); source("traffic-HyFIS+FIRST.MAX.r") }
	else if(n == 3) { clear(); source("traffic-HyFIS+LAST.MAX.r")  }
	else if(n == 4) { clear(); source("traffic-WM+FIRST.MAX.r")    }
	else if(n == 5) { clear(); source("traffic-WM+LAST.MAX.r")     }
	else if(n == 6) { clear(); source("traffic-WM+COG.r")			}
	else if(n == 7) { clear(); source("traffic-LT+COG.r")			}
	else if(n == 8) { clear(); source("traffic-MOGUL+COG.r")		}
	else if(n == 9) plotMF(object.cls)
	else if(n == 10) runall()
    else if(n == 11) comparisson()
	menu()	
        n <- readinteger()
}







menu <- function(){
	print( "------------------------------------------------------" )
	print( "-------------------------MENU-------------------------" )
	print( "------------------------------------------------------" )
	print( "-------ESCOLHA O ALGORITMO QUE DESEJA EXECUTAR--------" )
	print( "-------[1] - DENFIS+COG-------------------------------" )
	print( "-------[2] - HyFIS+FIRST.MAX--------------------------" )
	print( "-------[3] - HyFIS+LAST.MAX---------------------------" )
	print( "-------[4] - WM+FIRST.MAX-----------------------------" )
	print( "-------[5] - WM+LAST.MAX------------------------------" )
	print( "-------[6] - WM+COG-----------------------------------" )
	print( "-------[7] - GFS.LT.RS+COG----------------------------" )
	print( "-------[8] - GFS.MOGUL+COG----------------------------" )
	print( "-------[9] - PLOTAR VARIAVEIS LINGUISTICAS------------" )
	print( "-------[10] - EXECUTAR TODOS OS ALGORITMOS------------" )
	print( "-------[11] - COMPARAR OS ALGORITMOS------------------" )
	print( "-------[0] - SAIR-------------------------------------" )
	print( "------------------------------------------------------" )
}
runall <- function(){
	performance <- c(1:4)
	source("traffic-WM+FIRST.MAX.r")
	performance[1] <- MSE
	performance[5] <- RMSE
	source("traffic-WM+LAST.MAX.r")
	performance[2] <- MSE
	performance[6] <- RMSE
	source("traffic-HyFIS+FIRST.MAX.r")
	performance[3] <- MSE
	performance[7] <- RMSE
	source("traffic-HyFIS+LAST.MAX.r")
	performance[4] <- MSE
	performance[8] <- RMSE
	print( "-------------------RESULTADOS-------------------------" )
	print( "-------[1] - WM+FIRST.MAX---------MSE: " )
	print(performance[1])
	print( "-------[2] - WM+LAST.MAX----MSE: " )
	print(performance[2])
	print( "-------[3] - HyFIS+FIRST.MAX------MSE: " )
	print(performance[3])
	print( "-------[4] - HyFIS+LAST.MAX-MSE: " )
	print(performance[4])
	print( "-------[1] - WM+FIRST.MAX---------RMSE: " )
	print(performance[5])
	print( "-------[2] - WM+LAST.MAX----RMSE: " )
	print(performance[6])
	print( "-------[3] - HyFIS+FIRST.MAX------RMSE: " )
	print(performance[7])
	print( "-------[4] - HyFIS+LAST.MAX-RMSE: " )
	print(performance[8])
}

clear <- function() {
	elements <- ls() [! ls() %in% c("menu","n","runall", "clear") ]
	rm(list=elements)
}

comparisson <- function(){
    result.test <- cbind(traffic.class , res.test)
    x2 <- seq(from = 1, to = nrow(result.test))
    plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
    lines(x2, result.test[, 2], col="blue", type = "l")
}

readinteger <- function()
{ 
    n <- readline(prompt="Oque deseja? ")
        if(!grepl("^[0-9]+$",n))
        {
            return(readinteger())
        }

    return(as.integer(n))
}

menu()

n <- readinteger()
while(TRUE){
	if(is.na(n)){break}  # breaks when hit enter
    if(n == 0) break;
	if(n != 6) clear()
	if(n == 1) 	{     rm(list=ls(all=TRUE)); source("traffic-DENFIS+COG.r")		}
	else if(n == 2) { rm(list=ls(all=TRUE)); source("traffic-HyFIS+FIRST.MAX.r") }
	else if(n == 3) { rm(list=ls(all=TRUE)); source("traffic-HyFIS+LAST.MAX.r")  }
	else if(n == 4) { rm(list=ls(all=TRUE)); source("traffic-WM+FIRST.MAX.r")    }
	else if(n == 5) { rm(list=ls(all=TRUE)); source("traffic-WM+LAST.MAX.r")     }
	else if(n == 6) { rm(list=ls(all=TRUE)); source("traffic-WM+COG.r")			}
	else if(n == 7) { rm(list=ls(all=TRUE)); source("traffic-LT+COG.r")			}
	else if(n == 8) { rm(list=ls(all=TRUE)); source("traffic-MOGUL+COG.r")		}
	else if(n == 9) plotMF(object.cls)
	else if(n == 10) runall()
    else if(n == 11) comparisson()
	menu()	
        n <- readinteger()
}






## Display the FRBS model
summary(object.cls)

## Plot the membership functions
#plotMF(object.cls)

traffic.class.denorm <- denorm.data(traffic.class, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- denorm.data(res.test, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- round(res.test.denorm)

print("Comparando os valores estimados com os reais")
print(cbind(res.test.denorm, traffic.class.denorm))

## Calculo do erro

y.pred <- res.test
y.real <- traffic.class 
bench <- cbind(y.pred, y.real)
colnames(bench) <- c("pred. val.", "real. val.")
residuals <- (y.real - y.pred)
MSE <- mean(residuals^2)
RMSE <- sqrt(mean(residuals^2))
SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100
err <- c(MSE, RMSE, SMAPE)
names(err) <- c("MSE", "RMSE", "SMAPE")
print("WM: Avaliacao do erro: ")
print(err) 



## Display the FRBS model
summary(object.cls)

## Plot the membership functions
#plotMF(object.cls)

traffic.class.denorm <- denorm.data(traffic.class, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- denorm.data(res.test, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- round(res.test.denorm)

print("Comparando os valores estimados com os reais")
print(cbind(res.test.denorm, traffic.class.denorm))

## Calculo do erro

y.pred <- res.test
y.real <- traffic.class 
bench <- cbind(y.pred, y.real)
colnames(bench) <- c("pred. val.", "real. val.")
residuals <- (y.real - y.pred)
MSE <- mean(residuals^2)
RMSE <- sqrt(mean(residuals^2))
SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100
err <- c(MSE, RMSE, SMAPE)
names(err) <- c("MSE", "RMSE", "SMAPE")
print("WM: Avaliacao do erro: ")
print(err) 


result.test <- cbind(traffic.class , res.test)
x2 <- seq(from = 1, to = nrow(result.test))
plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
lines(x2, result.test[, 2], col="blue", type = "l")

par(op)
## Display the FRBS model
summary(object.cls)

## Plot the membership functions
#plotMF(object.cls)

traffic.class.denorm <- denorm.data(traffic.class, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- denorm.data(res.test, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- round(res.test.denorm)

print("Comparando os valores estimados com os reais")
print(cbind(res.test.denorm, traffic.class.denorm))

## Calculo do erro

y.pred <- res.test
y.real <- traffic.class 
bench <- cbind(y.pred, y.real)
colnames(bench) <- c("pred. val.", "real. val.")
residuals <- (y.real - y.pred)
MSE <- mean(residuals^2)
RMSE <- sqrt(mean(residuals^2))
SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100
err <- c(MSE, RMSE, SMAPE)
names(err) <- c("MSE", "RMSE", "SMAPE")
print("WM: Avaliacao do erro: ")
print(err) 


result.test <- cbind(traffic.class , res.test)
x2 <- seq(from = 1, to = nrow(result.test))
plot(x2, result.test[, 1], col="red", main = "Mackey Glass: Predicting phase (the Real Data(red) Vs Sim. result(blue))", type = "l", ylab = "MG")
lines(x2, result.test[, 2], col="blue", type = "l")

par(op)REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit compose/deep [[
					stack/top: stack/top - 1
					copy-cell stack/top stack/top - 1
					stack/check-call
				]]
			][
				mark: tail output
				unless head? path [
					emit compose/deep [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-word-set
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-word-set*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-word-set* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native (name)	;@@ make a unique name for function's body frame
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec select objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			emit reduce [to set-word! name 'func]
			insert-lf -2
			append/only output spec
			append/only output body
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame name
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc form load-cache %version.r
				comp-expression
				true
			]
			#build-date [
				change pc mold now
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
if ("silent" %in% ls() && silent) {
  fish <- function (...) {}
} else {
  fish <- cat
}
if ("noask" %in% ls() && noask) {
  dog <- fish
} else {
  dog <- cat
  noask <- FALSE
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  dog("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(noask || readline("Nadaljujem? [da/NE] ") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      if (any(success)) {
        dog("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      }
      cat("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      dog("Datoteke so pobrisane.\n")
    }
  } else {
    dog("Datoteke niso pobrisane.\n")
  }
} else {
  fish("Ne najdem nobene datoteke PDF.\n")
}
fish("Brišem delovno okolje.\n")
rm(list = ls())
if ("silent" %in% ls() && silent) {
  fish <- function (...) {}
} else {
  fish <- cat
}
if ("noask" %in% ls() && noask) {
  dog <- fish
} else {
  dog <- cat
  noask <- FALSE
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  dog("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(noask || readline("Nadaljujem? [da/NE] ") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      dog("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      cat("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      dog("Datoteke so pobrisane.\n")
    }
  } else {
    dog("Datoteke niso pobrisane.\n")
  }
} else {
  fish("Ne najdem nobene datoteke PDF.\n")
}
fish("Brišem delovno okolje.\n")
rm(list = ls())
if ("silent" %in% ls() && silent) {
  dog <- function (...) {}
} else {
  dog <- cat
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  cat("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(readline("Nadaljujem? [da/NE]") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      cat("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      cat("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      cat("Datoteke so pobrisane.\n")
    }
  } else {
    cat("Datoteke niso pobrisane.\n")
  }
} else {
  dog("Ne najdem nobene datoteke PDF.\n")
}
dog("Brišem delovno okolje.\n")
rm(list = ls())
# Pobrišemo PDF-je in počistimo delovno okolje
silent <- TRUE
source("clearpdf.r", encoding = "UTF-8")

# 2. faza: Obdelava, uvoz in čiščenje podatkov
source("uvoz/uvoz.r", encoding = "UTF-8")

# 3. faza: Analiza in vizualizacija podatkov
source("vizualizacija/vizualizacija.r", encoding = "UTF-8")

# 4. faza: Napredna analiza podatkov
source("analiza/analiza.r", encoding = "UTF-8")

cat("Končano.\n")if ("silent" %in% ls() && silent) {
  dog <- function (...) {}
} else {
  dog <- cat
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  dog("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(readline("Nadaljujem? [da/NE]") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      dog("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      dog("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      dog("Datoteke so pobrisane.\n")
    }
  } else {
    dog("Datoteke niso pobrisane.\n")
  }
} else {
  dog("Ne najdem nobene datoteke PDF.\n")
}
dog("Brišem delovno okolje.\n")
rm(list = ls())

#' @title random_split_dataset
#' @description 
#' Randomly splits a data frame into a training and test set, with a given fraction of rows in the 
#' test data set.    
#' 
#' @param df data frame to split
#' @param test_fraction 
#' @return list List with "train" and "test" elements
#' @export

random_split_dataset <- function(df, test_fraction) {
  require("caret")
  
  shuffled_df <- df[sample(nrow(df)),]
  indexes = sample(1:nrow(shuffled_df), size=test_fraction*nrow(shuffled_df))
  test = shuffled_df[indexes,]
  train = shuffled_df[-indexes,]
  ret <- list("train" = train, "test" = test)
  ret
}

#' @title get_data_path
#' @description
#' Utility function to help analysis be portable across dev environments and EC2 or
#' StarCluster execution environments.  If passed a "basedir", it uses that as the 
#' basis of a fully qualified path.  If not, it infers a basedir by first checking
#' for environment variable "R_DATA_BASEDIR".  If this does not exist, it then checks
#' for the existence of a variable "data_basedir" in the environment (perhaps from an .rprofile).
#' If this doesn't exist, it uses getwd() as the basedir.  It then appends the "suffix" if 
#' provided, and returns the canonical form of the directory path for the operating system.  
#' 
#' @param string basedir (defaults to NULL)
#' @param string suffix (defaults to NULL)
#' @param string filename
#' @param args  List of command line arguments (to be processed by commandArgs())
#' @export

get_data_path <- function(basedir = "", suffix = "", filename = "", args = "") {
  
  if(basedir != "") {
    p <- c(basedir)
  } else if(args != "") {
    p <- args[1]  
  } else if(Sys.getenv("R_DATA_BASEDIR") != "") {
    p <- c(Sys.getenv("R_DATA_BASEDIR"))
  } else if(exists("data_directory") == TRUE) {
    p <- c(data_directory)
  } else {
    p <- c(getwd())
  }
  

  final <- paste(p, suffix, filename, sep="/", collapse="")
  final
}


#' @title list_files_for_data_path
#' @description 
#' Lists files for a directory, perhaps given a full base directory specified in the 
#' user's environment or in an environment variable.  The goal is to allow the same
#' code to be easily run in multiple desktop environments, by multiple developers
#' who may have different disk directory layouts, and then move that code to servers 
#' and compute clusters, simply by changing one variable which points at the "base" 
#' directory in which files might be found.  
#' 
#' If the "basedir" argument is given, either through an absolute path, or more 
#' likely by passing the command line arguments from a script or an environment/startup variable, 
#' then this basedir is prepended to the "directory" variable.  This full absolute path
#' is then used as the starting point to construct a list of files whose names match the 
#' specified pattern.  This list is constructed using the normal base R function list.files(), 
#' and its return value is passed back to the user, so this function is a drop-in replacement.  
#' 
#' @param character Absolute path to a base directory for searching for directories and files
#' @param character Relative directory or directory path within which files should be searched
#' @param character Pattern for searching for files.  
#' @return A character vector containing file names in the specified directories that match the pattern, or "" if none matched.
#' @export


list_files_for_data_path <- function(basedir = "", directory = "", pattern = "") {
  if(basedir != "") {
    p <- c(basedir)
  } else if(Sys.getenv("R_DATA_BASEDIR") != "") {
    p <- c(Sys.getenv("R_DATA_BASEDIR"))
  } else if(exists("data_directory") == TRUE) {
    p <- c(data_directory)
  } else {
    p <- c(getwd())
  } 
  final <- paste(p, directory, sep="/", collapse="")
  list.files(path = final, pattern=pattern, full.names=TRUE)
}



plotPTraces <- function(pMat, ...)
{
  input_list <- as.list(list(...))
  pMat <- do.call("rbind", pMat)
  n.traces <- min(dim(pMat)[2], 4)
  
  if("log" %in% names(input_list)){
    logY <- input_list$log
    input_list$log <- NULL
  }else{
    logY <- NULL
  }  
  if("main" %in% names(input_list)){
    main <- input_list$main
    input_list$main <- NULL
  }else{
    main <- "Hyperparameter Traces"
  }
  if("xlab" %in% names(input_list)){
    xlab <- input_list$xlab
    input_list$xlab <- NULL
  }else{
    xlab <- "Samples"
  } 
  if("ylab" %in% names(input_list)){
    ylabs <- input_list$ylab
    input_list$ylab <- NULL
  }else{
    if(n.traces == 2)
    {
      ylabs <- c(expression(mu[phi]), expression(sigma[phi]))
    }else{
      ylabs <- c(expression(sigma[epsilon]), expression(mu[phi]), expression(sigma[phi]), "K")
    }
  }
  if("type" %in% names(input_list)){
    type <- input_list$type
    input_list$type <- NULL
  }else{
    type <- "l"
  }
  
  par(oma=c(1,1,2,1), mgp=c(2,1,0), mar = c(3,4,2,1), mfrow=c(2, ceiling(n.traces/2) ))
  for(i in 1:n.traces)
  {
    if(!is.null(logY) & min(pMat[, i]) > 0)
    {
      do.call(plot, c(input_list, list(x=pMat[, i]), list(xlab=xlab), list(ylab=ylabs[i]), list(type=type), list(log=logY)) )
    }else{
      do.call(plot, c(input_list, list(x=pMat[, i]), list(xlab=xlab), list(ylab=ylabs[i]), list(type=type)) )
    }
    #plot(pMat[, i], xlab=xlab, ylab=ylabs[i], type=type)
  }
  title(main=main, outer=T)
}

plotExpectedPhiTrace <- function(phiMat, ...)
{
  input_list <- as.list(list(...))
  
  if("main" %in% names(input_list)){
    main <- input_list$main
    input_list$main <- NULL
  }else{
    main <- expression(paste("Trace E[", phi, "]", sep=""))
  }
  if("xlab" %in% names(input_list)){
    xlab <- input_list$xlab
    input_list$xlab <- NULL
  }else{
    xlab <- "Iteration"
  }
  if("ylab" %in% names(input_list)){
    ylab <- input_list$ylab
    input_list$ylab <- NULL
  }else{
    ylab <- expression(paste("E[", phi, "]", sep=""))
  }
  if("type" %in% names(input_list)){
    type <- input_list$type
    input_list$type <- NULL
  }else{
    type <- "l"
  }
  phiMat <- do.call("cbind", phiMat)
  phiMat <- colMeans(phiMat)
  
  
  do.call( plot, c(input_list, list(x=phiMat), list(xlab=xlab), list(ylab=ylab), list(main=main), list(type=type)) )
  abline(h=1, col="red")
}

plotCUB <- function(reu13.df.obs, bMat, phi.bin, n.use.samples=2000, rescale=F,
                     main="CUB", model.label=c("True Model"), model.lty=1, ...)
{
  ### Arrange data.
  aa.names <- names(reu13.df.obs)
  #phi.bin <- phi.bin * phi.scale
  phi.bin.lim <- range(phi.bin)#range(c(phi.bin, phiMat))
  
  lbound <- max(0, length(bMat)-n.use.samples)
  ubound <- length(bMat)
  b.mat <- do.call(cbind, bMat[lbound:ubound]) 
  Eb <- rowMeans(b.mat)
  Eb <- convert.bVec.to.b(Eb, aa.names)
  
  ### Compute.
  ret.phi.bin <- prop.bin.roc(reu13.df.obs, phi.bin)
  
  if(model=="nse"){
    if("delta_a12" %in% names(list(...))) delta_a12 <- list(...)$delta_a12
    if("a_2" %in% names(list(...))) a_2 <- list(...)$a_2
    prediction <- prop.model.nse(Eb, reu13.df.obs, phi.bin.lim, delta_a12=delta_a12, a_2=a_2)
  }
  else{  prediction <- prop.model.roc(Eb, phi.bin.lim) }
  
  ### Fix xlim at log10 scale. 
  lim.bin <- range(log10(ret.phi.bin[[1]]$center))
  lim.model <- range(log10(prediction[[1]]$center))
  xlim <- c(lim.bin[1] - (lim.bin[2] - lim.bin[1]) / 4,
            max(lim.bin[2], lim.model[2]))
  
  
  mat <- matrix(c(rep(1, 4), 2:21, rep(22, 4)),
                nrow = 7, ncol = 4, byrow = TRUE)
  mat <- cbind(rep(23, 7), mat, rep(24, 7))
  nf <- layout(mat, c(3, rep(8, 4), 2), c(3, 8, 8, 8, 8, 8, 3), respect = FALSE)
  ### Plot title.
  par(mar = c(0, 0, 0, 0))
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.6, main)
  text(0.5, 0.4, date(), cex = 0.6)
  
  ### Plot results.
  for(i.aa in 1:length(aa.names))
  {
    tmp.obs <- ret.phi.bin[[i.aa]]
    tmp.roc <- prediction[[i.aa]]
    
    plotbin(tmp.obs, tmp.roc, main = "", xlab = "", ylab = "",
            lty = model.lty, axes = FALSE, xlim = xlim)
    box()
    main.aa <- oneLetterAAtoThreeLetterAA(aa.names[i.aa])
    text(0, 1, main.aa, cex = 1.5)
    if(i.aa %in% c(1, 5, 9, 13, 17)){
      axis(2)
    }
    if(i.aa %in% 16:19){
      axis(1)
    }
    if(i.aa %in% 1:4){
      axis(3)
    }
    if(i.aa %in% c(4, 8, 12,16)){
      axis(4)
    }
    axis(1, tck = 0.02, labels = FALSE)
    axis(2, tck = 0.02, labels = FALSE)
    axis(3, tck = 0.02, labels = FALSE)
    axis(4, tck = 0.02, labels = FALSE)
  }
  
  ## adding a histogram of phi values to plot
  hist.values <- hist(log10(phi.bin), plot=FALSE, nclass=30)
  plot(hist.values, axes = FALSE, main="", xlab = "", ylab = "")
  box()
  axis(1)

  ### Add label.
#  plot(NULL, NULL, axes = FALSE, main = "", xlab = "", ylab = "",
#        xlim = c(0, 1), ylim = c(0, 1))
#  legend(0.1, 0.8, model.label, lty = model.lty, box.lty = 0)
  
  ### Plot xlab.
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.5, "Production Rate (log10)")
  
  ### Plot ylab.
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.5, "Propotion", srt = 90)
}


plotBMatrixPosterior <- function(bMat, names.aa, interval, param = c("logmu", "deltaeta", "deltat"), main="AA parameter posterior", nclass=100, center=F)
{
  bmat <- convert.bVec.to.b(bMat[[1]], names.aa)
  bmat <- convert.b.to.bVec(bmat)
  names.b <- names(bmat)
  #id.intercept <- grep("Intercept", names.b)
  id.intercept <- grep("log", names.b)
  id.slope <- 1:length(names.b)
  id.slope <- id.slope[-id.intercept]
  
  
  id.plot <- rep(0, length(names.b))
  if(param[1] == "logmu"){
    xlab <- expression(paste("log ( ", mu, " )"))
    id.plot[id.intercept] <- id.intercept
  } else if(param[1] == "deltat"){
    xlab <- expression(paste(Delta, "t"))
    id.plot[id.slope] <- id.slope
  } else if(param[1] == "deltaeta"){
    xlab <- expression(paste(Delta, eta))
    id.plot[id.slope] <- id.slope
  }

  nf <- layout(matrix(c(rep(1, 4), 2:21), nrow = 6, ncol = 4, byrow = TRUE),
               rep(1, 4), c(2, 8, 8, 8, 8, 8), respect = FALSE)  
  #   nf <- layout(matrix(c(rep(1, 5), 2:21), nrow = 5, ncol = 5, byrow = TRUE),
  #                rep(1, 5), c(2, 8, 8, 8, 8), respect = FALSE)
  
  ### Plot title.
  par(mar = c(0, 0, 0, 0))
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.6, main)
  text(0.5, 0.4, date(), cex = 0.6)
  par(mar = c(5.1, 4.1, 4.1, 2.1))
  
  
  ### Plot by aa.
  postMeans <- NULL
  totalncodons <- 1
  for(i.aa in names.aa){
    #id.tmp <- grepl(paste(i.aa,".",sep=""), names.b, fixed=T) & id.plot
    id.tmp <- grepl(paste(i.aa, i.aa, sep="."), names.b, fixed=T) & id.plot
    trace <- lapply(1:length(bMat), function(i){ bMat[[i]][id.tmp] })
    trace <- do.call("rbind", trace)
    if(length(trace) == 0) next
    ncodons <- sum(id.tmp)
    
    ## find x and y limits
    ymax <- vector(mode = "numeric", length = ncodons)
    for(i in 1:ncodons) {
      ymax[i] <- max(hist(trace[interval, i], plot=F, nclass=nclass)$counts)
    }
    if(center){
      if(ncodons > 1){means <- colMeans(trace[interval,])}else{means <- mean(trace[interval,])}
      trace <- trace - mean(means)
    }
    if(ncodons > 1){means <- colMeans(trace[interval,])}else{means <- mean(trace[interval,])}
    postMeans <- c(postMeans, means)
    
    xlim <- range(trace[interval, ])
    ylim <- c(0, max(ymax))
    
    # create empty plot
    main.aa <- oneLetterAAtoThreeLetterAA(i.aa)
    plot(NULL, NULL, xlim = xlim, ylim = ylim,
         xlab = xlab, ylab = "Frequency", main = main.aa)
    plot.order <- order(apply(trace, 2, sd), decreasing = TRUE)
       
    ## Fill plots
    for(i.codon in plot.order){
      hist(trace[interval, i.codon], add=T, nclass=nclass, col=.CF.PT$color[i.codon], lty=0)
    }
    stddev <- format(sd(trace[interval, ]), digits = 3)
    text(x=(xlim[2]+xlim[1])/2, y=ylim[2]-0.1*ylim[2], label=paste("sd =", stddev))
  }

  dens <- density(postMeans)
  xlim <- range(dens$x)
  ylim <- range(dens$y)
  plot(dens, xlim = xlim, ylim = ylim+c(0, 0.2*ylim[2]),
       xlab = xlab, ylab = "Density", main = "Posterior mean distribution")
  stddev <- format(sd(postMeans), digits = 3)
  text(x=(xlim[2]+xlim[1])/2, y=ylim[2]+0.1*ylim[2], label=paste("sd =", stddev))
}

plotTraces <- function(bMat, names.aa, param = c("logmu", "deltaeta", "deltat"), main="AA parameter trace")
{  
  
  bmat <- convert.bVec.to.b(bMat[[1]], names.aa)
  bmat <- convert.b.to.bVec(bmat)
  names.b <- names(bmat)
  id.intercept <- grep("log", names.b)
  id.slope <- 1:length(names.b)
  id.slope <- id.slope[-id.intercept]
  
  
  id.plot <- rep(0, length(names.b))
  if(param[1] == "logmu"){
    ylab <- expression(paste("log ( ", mu, " )"))
    id.plot[id.intercept] <- id.intercept
  } else if(param[1] == "deltat"){
    ylab <- expression(paste(Delta, "t"))
    id.plot[id.slope] <- id.slope
  } else if(param[1] == "deltaeta"){
    ylab <- expression(paste(Delta, eta))
    id.plot[id.slope] <- id.slope
  }
  
  x <- 1:length(bMat)
  xlim <- range(x)
  
  ### Trace plot.
  nf <- layout(matrix(c(rep(1, 4), 2:21), nrow = 6, ncol = 4, byrow = TRUE),
               rep(1, 4), c(2, 8, 8, 8, 8, 8), respect = FALSE)  
#   nf <- layout(matrix(c(rep(1, 5), 2:21), nrow = 5, ncol = 5, byrow = TRUE),
#                rep(1, 5), c(2, 8, 8, 8, 8), respect = FALSE)
  
  ### Plot title.
  par(mar = c(0, 0, 0, 0))
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.6, main)
  text(0.5, 0.4, date(), cex = 0.6)
  par(mar = c(5.1, 4.1, 4.1, 2.1))
  
  ### Plot by aa.
  for(i.aa in names.aa){
    id.tmp <- grepl(paste(i.aa, i.aa, sep="."), names.b, fixed=T) & id.plot
    trace <- lapply(1:length(bMat), function(i){ bMat[[i]][id.tmp] })
    trace <- do.call("rbind", trace)
    if(length(trace) == 0) next
    ylim <- range(trace, na.rm=T)
    
    main.aa <- oneLetterAAtoThreeLetterAA(i.aa)
    plot(NULL, NULL, xlim = xlim, ylim = ylim,
         xlab = "Samples", ylab = ylab, main = main.aa)
    plot.order <- order(apply(trace, 2, sd), decreasing = TRUE)
    for(i.codon in plot.order){
      lines(x = x, y = trace[, i.codon], col = .CF.PT$color[i.codon])
    } 
  }
}

oneLetterAAtoThreeLetterAA <- function(letter)
{
  letters <- list(A="Ala", R="Arg", N="Asn", D="Asp", C="Cys", Q="Gln", E="Glu", 
                  G="Gly", H="His", I="Ile", L="Leu", K="Lys", F="Phe", P="Pro", 
                  S=expression("Ser"[4]), Z=expression("Ser"[2]), T="Thr", Y="Tyr", V="Val", M="Met", W="Trp")
  return(letters[[letter]])
}
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = 1, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # determine position index of rows
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  
  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c + 1 } 

  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = 1, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#Topic Model script
#Much of this initial workflow is from Jockers Text Analysis for R 
#and Shawn Graham's Ferguson Grand Jury corpus topic model at https://github.com/shawngraham/ferguson
library(mallet)
library(wordcloud)
library(dplyr)
library(tm)
library(Hmisc)

# import the OCR'd ICC decisions from the text folder
# each decision is here its own text file
#decisions <- mallet.read.dir("text") 

#Better is to use load.r file to provide cleaner texts via get_real_words function, etc

mallet.instances <- mallet.import(decisions$id, decisions$text, "icc.txt", token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")

#' create topic trainer object
n.topics <- 100
topic.model <- MalletLDA(n.topics)

#' load documents
topic.model$loadDocuments(mallet.instances)

## Get the vocabulary, and some statistics about word frequencies.
## These may be useful in further curating the stopword list.
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
#Get additional words for stoplist
#stopwords<- arrange(word.freqs, words, term.freq)
#rank(stopwords)



## Optimize hyperparameters every 20 iterations,
## after 50 burn-in iterations.
topic.model$setAlphaOptimization(20, 50)

## Now train a model. Note that hyperparameter optimization is on, by default.
## We can specify the number of iterations. Here we'll use a large-ish round number.
topic.model$train(400)

## NEW: run through a few iterations where we pick the best topic for each token,
## rather than sampling from the posterior distribution.
topic.model$maximize(40)

#' Get the probability of topics in documents and the probability of words in topics.
#' By default, these functions return raw word counts. Here we want probabilities,
#' so we normalize, and add "smoothing" so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=T, normalized=T)
topic.words <- mallet.topic.words(topic.model, smoothed=T, normalized=T)  ##adap jockers wordcloud script to use this variable

#' from http://www.cs.princeton.edu/~mimno/R/clustertrees.R
#' transpose and normalize the doc topics
topic.docs <- t(doc.topics)
topic.docs <- topic.docs / rowSums(topic.docs)

#Get shorter versions of the topics
topics.labels <- rep("", n.topics)
for (topic in 1:n.topics) topics.labels[topic] <- paste(mallet.top.words(topic.model, topic.words[topic,], num.top.words=7)$words, collapse=" ")


#output some of the topic model raw data
write.csv(topic.docs, "out/icc-topic-docs.csv") 
write.csv(topics.labels, "out/icc-topic-labels.csv") 

# create data.frame with columns as ids and rows as topics
topic_docs <- data.frame(topic.docs)
plotdocs <- names(topic_docs) 
names(topic_docs) <- decisions$id

## cluster based on shared words
plot(hclust(dist(topic.words)), labels=topics.labels)

#' Calculate similarity matrix
#' Shows which documents are similar to each other
#' by their proportions of topics. Based on Matt Jockers' method

library(cluster)
topic_df_dist <- as.matrix(daisy(t(topic_docs), metric = "euclidean", stand = TRUE))
# Change row values to zero if less than row minimum plus row standard deviation
# keep only closely related documents and avoid a dense spagetti diagram
# that's difficult to interpret (hat-tip: http://stackoverflow.com/a/16047196/1036500)
topic_df_dist[ sweep(topic_df_dist, 1, (apply(topic_df_dist,1,min) + apply(topic_df_dist,1,sd) )) > 0 ] <- 0



#Shawn Graham's topics as wordclouds with some of Jockers print to pdf code
jpeg(filename="out/images/icc-topic-%03d.jpeg")
for(i in 1:40){
  topic.top.words <- mallet.top.words(topic.model,
                                      topic.words[i,], 15)
  print(wordcloud(topic.top.words$words,
                  topic.top.words$weights,
                  c(4,.8), rot.per=0,
                  random.order=F))
  
}
dev.off()

#create some plots of topics across the range of decisions
library(ggplot2)
library(tidyr)
jpeg(filename="out/images/icc-topics-across-docs-%03d.jpeg")
n.decisions <- length(raw)
cols <- 1:n.decisions
doc_topics <- data.frame(doc.topics, row.names = decisions$id, stringsAsFactors = FALSE)
doc_topics$docs <- cols

topic.cols <- names(doc_topics)

for(i in 1:40){
print(ggplot(doc_topics) + geom_smooth(aes_string(x="docs", y=(topic.cols[i]))) + ggtitle(c("Topic " + as.character(i))))

}  
dev.off()

print(ggplot(doc_topics, aes(x=docs, y=X30), title = c("Topic " + "30")) + geom_smooth()

      #Create a term document matrix to plot word similarities
      library(tm)
      library(igraph)
corpus<- Corpus(VectorSource(decisions$text))
icc.tdm <- TermDocumentMatrix(corpus)
clean.tdm <- removeSparseTerms(icc.tdm, .995)     
plot(clean.tdm, terms = findFreqTerms(tdm, lowfreq = 6)[1:25], corThreshold = 0.5)

#Topic Model script
#Much of this initial workflow is from Jockers Text Analysis for R 
#and Shawn Graham's Ferguson Grand Jury corpus topic model at https://github.com/shawngraham/ferguson
library(mallet)
library(wordcloud)
library(dplyr)
library(tm)
library(Hmisc)

# import the OCR'd ICC decisions from the text folder
# each decision is here its own text file
#decisions <- mallet.read.dir("text") 

#Better is to use load.r file to provide cleaner texts via get_real_words function, etc

mallet.instances <- mallet.import(decisions$id, decisions$text, "icc.txt", token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")

#' create topic trainer object
n.topics <- 100
topic.model <- MalletLDA(n.topics)

#' load documents
topic.model$loadDocuments(mallet.instances)

## Get the vocabulary, and some statistics about word frequencies.
## These may be useful in further curating the stopword list.
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
#Get additional words for stoplist
#stopwords<- arrange(word.freqs, words, term.freq)
#rank(stopwords)



## Optimize hyperparameters every 20 iterations,
## after 50 burn-in iterations.
topic.model$setAlphaOptimization(20, 50)

## Now train a model. Note that hyperparameter optimization is on, by default.
## We can specify the number of iterations. Here we'll use a large-ish round number.
topic.model$train(400)

## NEW: run through a few iterations where we pick the best topic for each token,
## rather than sampling from the posterior distribution.
topic.model$maximize(40)

#' Get the probability of topics in documents and the probability of words in topics.
#' By default, these functions return raw word counts. Here we want probabilities,
#' so we normalize, and add "smoothing" so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=T, normalized=T)
topic.words <- mallet.topic.words(topic.model, smoothed=T, normalized=T)  ##adap jockers wordcloud script to use this variable

#' from http://www.cs.princeton.edu/~mimno/R/clustertrees.R
#' transpose and normalize the doc topics
topic.docs <- t(doc.topics)
topic.docs <- topic.docs / rowSums(topic.docs)

#Get shorter versions of the topics
topics.labels <- rep("", n.topics)
for (topic in 1:n.topics) topics.labels[topic] <- paste(mallet.top.words(topic.model, topic.words[topic,], num.top.words=7)$words, collapse=" ")


#output some of the topic model raw data
write.csv(topic.docs, "out/icc-topic-docs.csv") 
write.csv(topics.labels, "out/icc-topic-labels.csv") 

# create data.frame with columns as ids and rows as topics
topic_docs <- data.frame(topic.docs)
plotdocs <- names(topic_docs) 
names(topic_docs) <- decisions$id

## cluster based on shared words
plot(hclust(dist(topic.words)), labels=topics.labels)

#' Calculate similarity matrix
#' Shows which documents are similar to each other
#' by their proportions of topics. Based on Matt Jockers' method

library(cluster)
topic_df_dist <- as.matrix(daisy(t(topic_docs), metric = "euclidean", stand = TRUE))
# Change row values to zero if less than row minimum plus row standard deviation
# keep only closely related documents and avoid a dense spagetti diagram
# that's difficult to interpret (hat-tip: http://stackoverflow.com/a/16047196/1036500)
topic_df_dist[ sweep(topic_df_dist, 1, (apply(topic_df_dist,1,min) + apply(topic_df_dist,1,sd) )) > 0 ] <- 0

#' Use kmeans to identify groups of similar authors

km <- kmeans(topic_df_dist, n.topics)
# get names for each cluster
allnames <- vector("list", length = n.topics)
for(i in 1:n.topics){
  allnames[[i]] <- names(km$cluster[km$cluster == i])
}

#Shawn Graham's topics as wordclouds with some of Jockers print to pdf code
pdf(file="icc-topics.pdf")
for(i in 1:40){
  topic.top.words <- mallet.top.words(topic.model,
                                      topic.words[i,], 15)
  print(wordcloud(topic.top.words$words,
                  topic.top.words$weights,
                  c(4,.8), rot.per=0,
                  random.order=F))
  
}
dev.off()

#create some plots of topics across the range of decisions
library(ggplot2)
library(tidyr)
pdf(file="icc-topics-across-docs.pdf")
n.decisions <- length(raw)
cols <- 1:n.decisions
doc_topics <- data.frame(doc.topics, row.names = decisions$id, stringsAsFactors = FALSE)
doc_topics$docs <- cols

topic.cols <- names(doc_topics)

for(i in 1:100){
print(ggplot(doc_topics) + geom_smooth(aes_string(x="docs", y=(topic.cols[i]))))

}  
dev.off()

ggplot(doc_topics, aes(x=docs, y=X30)) + geom_smooth(span = 20)
library(dplyr)
library(tidyr)
library(ggplot2)

gap_dat <- read.delim("06_gap-merged-with-continent.tsv")
gap_dat %>% str
# 'data.frame':  3312 obs. of  6 variables:
# $ country  : Factor w/ 187 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
# $ continent: Factor w/ 6 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...

## During data exploration, I learned that most countries have data every five
## years, e.g. 1952, 1957, 1962, and so on. Let's just make that official.
gap_dat <- gap_dat %>%
  filter(year %% 5 == 2)
gap_dat %>% str # 'data.frame':	2012 obs. of  6 variables:

## number of distinct values for year
(n_years <- n_distinct(gap_dat$year)) # 12

## Does every country contribute data for all years?
country_freq <- gap_dat %>%
  group_by(country) %>%
  tally

ggplot(country_freq, aes(x = n)) + geom_bar(binwidth = 1)
country_freq$n %>% table

## Most countries do contribute data for 12 years
## Who contributes less?
country_freq %>%
  filter(n < 12) %>%
  arrange(n)

## The only thing I see here that I want to fix is to rescue China, which has
## data for 11 of 12 years. Otherwise, I will let these countries go.
keepers <- c(with(country_freq, as.character(country[n == 12])),
             "China") %>% sort
keepers %>% length # 142 countries

## filter gap_dat
gap_dat <- gap_dat %>%
  filter(country %in% keepers) %>%
  droplevels %>%
  arrange(country, year)
gap_dat %>% str
# 'data.frame':  1703 obs. of  6 variables:
# $ country  : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
# $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...

## BEGIN: Fill in missing data for China

## which year is the problem?
(china <- gap_dat %>%
   filter(country == "China"))      # 1952 is missing

## what does the data look like?
china_tidy <- china %>%
  gather(key = "variable", value = "value",
         pop, lifeExp, gdpPercap)
ggplot(china_tidy, aes(x = year, y = value)) +
  facet_wrap(~ variable, scales="free_y") +
  geom_point() + geom_line() +
  scale_x_continuous(breaks = seq(1950, 2011, 15))

## extremely low, low tech imputation for 1952
china_gdp_fit <- lm(gdpPercap ~ year, gap_dat,
                    subset = country == 'China' & year <= 1982)
summary(china_gdp_fit)
(china_gdp_1952 <- predict(china_gdp_fit, data.frame(year = 1952)))
## 400.4486

china_pop_fit <- lm(pop ~ year, gap_dat, subset = country == 'China')
summary(china_pop_fit)
(china_pop_1952 <- predict(china_pop_fit, data.frame(year = 1952)))
## 556263528

china_lifeExp_1952 <- 44 # fiction, but no simple linear fit seems appropriate

gap_dat <- rbind(gap_dat,
                 data.frame(country = 'China', year = 1952,
                            pop = china_pop_1952, continent = 'Asia',
                            lifeExp = china_lifeExp_1952,
                            gdpPercap = china_gdp_1952))
gap_dat <- gap_dat %>%
  arrange(country, year)
gap_dat %>%
  filter(country == "China")
str(gap_dat)
# 'data.frame':  1704 obs. of  6 variables:
# $ country  : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : num  1952 1957 1962 1967 1972 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
# $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...

## revisit the data
china_tidy <- gap_dat %>%
  filter(country == "China") %>%
  gather(key = "variable", value = "value",
         pop, lifeExp, gdpPercap)
ggplot(china_tidy, aes(x = year, y = value)) +
  facet_wrap(~ variable, scales="free_y") +
  geom_point() + geom_line() +
  scale_x_continuous(breaks = seq(1950, 2011, 15))

## END: Fill in missing data for China

write.table(gap_dat,
            "07_gap-every-five-years.tsv",
            quote = FALSE, sep = "\t", row.names = FALSE)
library(plyr)  ## revalue()
library(dplyr)
library(ggplot2)

## bring in lightly cleaned datasets extracted from excel spreadsheets

pop_dat <- read.delim("01_pop.tsv")
pop_dat %>% str
# 'data.frame':  14105 obs. of  3 variables:
# $ country: Factor w/ 253 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year   : int  1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 ...
# $ pop    : num  8150368 8284473 8425333 8573217 8728408 ...
## 2014: only difference with 2010 is pop is numeric now, was integer
pop_dat %>% head
pop_dat %>% tail

le_dat <- read.delim("02_lifeExp.tsv")
le_dat %>% str
# 'data.frame':  3786 obs. of  4 variables:
# $ country  : Factor w/ 198 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ continent: Factor w/ 7 levels "","Africa","Americas",..: 4 4 4 4 4 4 4 4 4 4 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
## 2014: only difference with 2010 is order of the variables
le_dat %>% head
le_dat %>% tail           

gdp_dat <- read.delim("03_gdpPercap.tsv")
gdp_dat %>% str
# 'data.frame':  10911 obs. of  3 variables:
# $ country  : Factor w/ 229 levels "Afghanistan",..: 1 2 3 4 6 9 10 12 13 14 ...
# $ gdpPercap: num  757 1532 2429 4465 3363 ...
# $ year     : int  1950 1950 1950 1950 1950 1950 1950 1950 1950 1950 ...
## 2014: only difference with 2010 is order of the variables
## 'data.frame':	10911 obs. of  3 variables:
gdp_dat %>% head
le_dat %>% tail

## studying the overlap between countries in the different datasets
country_levels <- function(df) levels(df$country)
union_country <- country_levels(pop_dat) %>%
  union(country_levels(le_dat)) %>%
  union(country_levels(gdp_dat)) %>%
  sort
union_country %>% length # 271 (in 2010 and 2014)
union_country
## problems I see by eye
# Bahamas  Bahamas, The
# Central African Rep.	Central African Republic
# Congo, Dem. Rep.	Congo, Rep.
# Cook Is	    Cook Islands
# Czech Rep.  Czech Republic	Czechoslovakia
# Dominican Rep.	  Dominican Republic
# East Germany	  Germany   West Germany
# Egypt		  Egypt, Arab Rep.
# Eritrea		  Eritrea and Ethiopia	Ethiopia
# Falkland Is (Malvinas)	  Falkland Islands (Malvinas)
# Gambia	 Gambia, The
# Iran	 Iran, Islamic Rep.
# Korea, Dem. Rep.       Korea, Rep.	Korea, United
# Kyrgyz Republic	       Kyrgyzstan
# Lao PDR		       Laos
# Russia		       Russian Federation	USSR
# Serbia		       Serbia and Montenegro	Serbia excluding Kosovo
# Saint Kitts and Nevis  St. Kitts and Nevis
# Saint Lucia St. Lucia
# Saint Vincent and the Grenadines	St. Vincent and the Grenadines
# Syria Syrian Arab Republic
# Venezuela    Venezuela, RB
# Yemen Arab Republic (Former)	Yemen Democratic (Former)	Yemen, Rep.
# RECORDED THAT IN country-pain.txt!
c_dat <- data_frame(country = union_country,
                    pop = country %in% levels(pop_dat$country),
                    le = country %in% levels(le_dat$country),
                    gdp = country %in% levels(gdp_dat$country),
                    total = pop + le + gdp)
c_dat$total %>% table
##  1   2   3 
## 40  53 178

## Can I just ignore countries that appear in 1 or 2 datasets?
c_dat %>%
  filter(total < 3)
## No, I cannot.

## these are the ad hoc fixes I decided to make in 2010
## (country-pain.txt contains a more comprehensive collection of problems)
country_subs <- c("Bahamas, The" = "Bahamas",
                  "Central African Rep." = "Central African Republic",
                  "Cook Is" = "Cook Islands",
                  "Czech Rep." = "Czech Republic",
                  "Dominican Rep." = "Dominican Republic",
                  "Egypt, Arab Rep." = "Egypt",
                  "Gambia, The" = "Gambia",
                  "Iran, Islamic Rep." = "Iran",
                  "Russian Federation" = "Russia",
                  "Syrian Arab Republic" = "Syria",
                  "Venezuela, RB" = "Venezuela")
revalue_country <- function(x) revalue(x, country_subs)
pop_dat <- pop_dat %>%
  mutate(country = revalue_country(country))
le_dat <- le_dat %>%
  mutate(country = revalue_country(country))
gdp_dat <- gdp_dat %>%
  mutate(country = revalue_country(country))

## studying the overlap between countries in the different datasets
union_country <- country_levels(pop_dat) %>%
  union(country_levels(le_dat)) %>%
  union(country_levels(gdp_dat)) %>%
  sort
union_country %>% length # 260 (in 2010 and 2014), down from 271
c_dat <- data_frame(country = union_country,
                    pop = country %in% levels(pop_dat$country),
                    le = country %in% levels(le_dat$country),
                    gdp = country %in% levels(gdp_dat$country),
                    total = pop + le + gdp)
c_dat$total %>% table
## BEFORE revalues    AFTER revalues    
##  1   2   3         1   2   3 
## 40  53 178        28  44 188 

## Can I just ignore countries that appear in 1 or 2 datasets?
c_dat %>%
  filter(total < 3)
## Other than USSR, yes I will ignore countries that appear in 1 or 2 datasets.

pop_russia <- pop_dat %>%
  filter(country %in% c("Russia","USSR"))
(ggplot(pop_russia, aes(x = year, y = pop, color = country)) +
   geom_line())
#xyplot(pop ~ year, type = "l",
#            groups = country[drop = TRUE], auto.key = TRUE)
## huh?
## pop data present for USSR *and* Russia, 1950 - 2008
## USSR pop >> Russia pop, USSR presumably includes Russia??

le_dat %>%
  filter(country %in% c("Russia","USSR"))
gdp_dat %>%
  filter(country %in% c("Russia","USSR"))
## lifeExp and gdpPercap only have data for Russia
## decision: keep Russia, discard USSR

## decision: keep countries found in all 3 datasets

## merge all three datasets!  then enforce countries to keep
gap_dat <- pop_dat %>%
  inner_join(gdp_dat, by = c("country", "year")) %>%
  inner_join(le_dat, by = c("country", "year")) %>%
  droplevels %>%
  arrange(country, year)
gap_dat %>% str
# 'data.frame':  3312 obs. of  6 variables:
# $ country  : Factor w/ 187 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ continent: Factor w/ 7 levels "","Africa","Americas",..: 4 4 4 4 4 4 4 4 4 4 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
## 2014: agrees with merged result in 2010, except for
##   * variable order
##   * pop is numeric now, was integer then
##   * at this point in 2010 cleaning, I had an unused level for the country
##     factor (Tokelau), which has no downstream effects

my_vars <- c('country', 'continent', 'year',
             'lifeExp', 'pop', 'gdpPercap')
gap_dat <- gap_dat[my_vars]

write.table(gap_dat,
            "04_gap-merged.tsv",
            quote = FALSE, sep = "\t", row.names = FALSE)
library(gdata)     # read.xls()
library(dplyr)
library(ggplot2)
library(stringr)   # str_detect()

## extract the life expectancy data

## this is the Excel file downloaded 2009-04-21 from gapminder.org
## Yes, it was painful coming up with all the argument values necessary to
## successfully import this data. See comments at end of file.
le_xls <-
  read.xls("life-expectancy-reference-spreadsheet-20090204-xls-format.xls",
           sheet = "Data and metadata",
           verbose = TRUE, quote = "", method = "tab",
           fileEncoding =  "ISO-8859-1",
           colClasses = c(rep("character", 4), rep("NULL", 5)))
## many instances of this warning:
#Wide character in print at /Users/jenny/resources/R/libraryCRAN/gdata/perl/xls2tab.pl line 270.
le_xls %>% str
# 'data.frame':  52419 obs. of  4 variables:
# $ X.Continent.average.used..see.documentation..                                                    : chr  "\"Asia\"" "\"Asia\"" "\"Asia\"" "\"Asia\"" ...
# $ X.Country.                                                                                       : chr  "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" ...
# $ X.Year.                                                                                          : chr  "\"1800\"" "\"1801\"" "\"1802\"" "\"1803\"" ...
# $ X.Life.expectancy.at.birth..including.Gapminder.model...not.to.be.used.for.statistical.analysis..: chr  "" "" "" "" ...

## rename vars
le_raw <- le_xls %>%
  select(country = contains("country"), continent = contains("continent"),
         year_raw = contains("year"), lifeExp_raw = contains("life.expectancy"))
le_raw %>% str
# 'data.frame':  52419 obs. of  4 variables:
# $ country    : chr  "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" ...
# $ continent  : chr  "\"Asia\"" "\"Asia\"" "\"Asia\"" "\"Asia\"" ...
# $ year_raw   : chr  "\"1800\"" "\"1801\"" "\"1802\"" "\"1803\"" ...
# $ lifeExp_raw: chr  "" "" "" "" ...

## 2014: 52419 obs. of  4 variables:
## 2010 cleaning code comment: # 52416 obs. of  9 variables: <-- huh?
## Note: I did not use gdata::read.xls() in 2010; rather, I exported a text file
## from Excel 'by hand'.
le_raw %>% head
le_raw %>% tail

## get rid of the escaped double quotes
remove_quotes <- function(x) gsub("\"", "", x)
le_raw <- le_raw %>%
  mutate_each(funs(remove_quotes))
le_raw %>% str
# 'data.frame':  52419 obs. of  4 variables:
# $ country    : chr  "Abkhazia" "Abkhazia" "Abkhazia" "Abkhazia" ...
# $ continent  : chr  "Asia" "Asia" "Asia" "Asia" ...
# $ year_raw   : chr  "1800" "1801" "1802" "1803" ...
# $ lifeExp_raw: chr  "" "" "" "" ...

## let's fix year enough to filter on it
n_distinct(le_raw$year_raw) #210
unique(le_raw$year_raw)
## eye-ball-o-metric inspection ...

## must investigate obviously invalid values for year
(needs_a_look <- which(le_raw$year_raw %in% c("", "5")))
if(length(needs_a_look) > 0) {
  le_raw[(min(needs_a_look) - 4):(max(needs_a_look) + 4), ]
## early 1800s, Pakistan
## this will never survive my year filter so just make this go away
## BTW nothing visible in Excel; I can see gaps in row numbers but 'unhide' does
## nothing ... Google tell me to "unset filters" from data menu, which does
## indeed reveal the hidden rows
  le_raw$year_raw[needs_a_look] <- NA_character_
}

le_raw$year_raw %>% n_distinct #209
le_raw$year_raw %>% unique
## nothing obviously crazy remains

## convert year to integer
le_raw <- le_raw %>%
  mutate(year = year_raw %>% as.integer)
le_raw$year %>% n_distinct #209
le_raw$year %>% unique
all.equal(sort(unique(le_raw$year[!is.na(le_raw$year)])), 1800:2007)
## Integers between 1800 and 2007. Yay.

## drop year_raw, in favor of year
le_raw <- le_raw %>%
  mutate(year_raw = NULL)

le_raw$year %>% summary
#  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
#  1800    1852    1904    1904    1955    2007       3
## AHA! In 2010, this did not includee 3 NA's.
## 52419 - 3 = 52416
## Mystery of the rows solved.

## for which years do we have data?
year_freq <- le_raw %>%
  group_by(year) %>%
  tally
table(year_freq$n)
# 3 252
# 1 208
## this solves nothing, because even when year is present, life expectancy often
## is not
## very different structure from population data :(

## change of plan: let's fix lifeExp enough to filter on it
le_raw$lifeExp_raw %>% head(100)
sum(le_raw$lifeExp_raw == "") # 46510
# 'data.frame':  5909 obs. of  5 variables:
# $ country  : chr  "\"Afghanistan\"" "\"Afghanistan\"" "\"Afghanistan\"" "\"Afghanistan\"" ...
# $ continent: chr  "\"Asia\"" "\"Asia\"" "\"Asia\"" "\"Asia\"" ...
# $ year_raw : chr  "\"1800\"" "\"1952\"" "\"1957\"" "\"1962\"" ...
# $ lifeExp  : chr  "\"28.801\"" "\"28.801\"" "\"30.332\"" "\"31.997\"" ...
# $ year     : num  1800 1952 1957 1962 1967 ...

le_raw <- le_raw %>%
  filter(lifeExp_raw != "")
str(le_raw)
# 'data.frame':  5909 obs. of  4 variables:
# $ country    : chr  "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
# $ continent  : chr  "Asia" "Asia" "Asia" "Asia" ...
# $ lifeExp_raw: chr  "28.801" "28.801" "30.332" "31.997" ...
# $ year       : num  1800 1952 1957 1962 1967 ...

## while lifeExp_raw is still character, check to see if it contains only digits
## and the decimal sign
le_seems_ok <- le_raw$lifeExp_raw %>% str_detect("[0-9\\.]")
le_seems_ok %>% table
# TRUE
# 5909
## I am pleasantly shocked

## convert lifeExp to numeric
le_raw <- le_raw %>%
  mutate(lifeExp = lifeExp_raw %>% as.numeric)

le_raw$lifeExp %>% summary
#  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
# 11.60   45.21   61.17   58.02   70.90   82.67

## drop lifeExp_raw, in favor of lifeExp
le_raw <- le_raw %>%
  mutate(lifeExp_raw = NULL)

## is continent ok as is?
n_distinct(le_raw$continent) # 7
unique(le_raw$continent)
# [1] "Asia"     "Europe"   "Africa"   "Americas" ""         "FSU"      "Oceania"

## let's look further into empty continent and FSU
(empty_continent <- le_raw %>%
   filter(continent == "") %>%
   select(country) %>%
   unique)
str(empty_continent) ## 30 countries affected, eg Canada, Haiti
## wait to fix these after merging pop + lifeExp + gdpPercap

(fsu_continent <- le_raw %>%
   filter(continent == "FSU") %>%
   select(country) %>%
   unique)
#                country
# 1              Belarus
# 53          Kazakhstan
# 73              Latvia
# 128          Lithuania
# 181 Russian Federation
# 262            Ukraine
## handle this after merging pop + lifeExp + gdpPercap

## is country ok as is?
n_distinct(le_raw$country) # 198
unique(le_raw$country)
## no obvious problems

## return to year
n_distinct(le_raw$year) #208
unique(le_raw$year)
(p <- ggplot(le_raw, aes(x = year)) + geom_bar(binwidth = 1)) # 1950 -->
p + xlim(c(1945, 2010)) # spikes every five years
p + xlim(c(1950, 1960)) # 1952, 1957, ...
p + xlim(c(2000, 2010)) # ..., 2002, 2007

## keep data from 1950 to 2007
year_min <- 1950
year_max <- 2007
le_raw <- le_raw %>%
  filter(year >= year_min & year <= year_max)
le_raw %>% str
# 'data.frame':  3786 obs. of  4 variables:
# $ country  : chr  "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
# $ continent: chr  "Asia" "Asia" "Asia" "Asia" ...
# $ year     : num  1952 1957 1962 1967 1972 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...

## save for now
write.table(le_raw,
            "02_lifeExp.tsv",
            quote = FALSE, sep = "\t", row.names = FALSE)


## EVERYTHING BELOW HERE IS COMMENTED OUT!
## NOTES ON HOW I WAS ABLE TO WRITE THE ABOVE CODE

## saving this saga for possible later demo and write-up

## initially tried a much simpler read.xls() call
# le_xls <-
#   read.xls("xls/life-expectancy-reference-spreadsheet-20090204-xls-format.xls",
#            verbose = TRUE, sheet = "Data and metadata",
#            stringsAsFactors = FALSE, fileEncoding =  "macintosh")

## technically it was successful but got these warnings:
## many instances of this:
# Wide character in print at /Users/jenny/resources/R/libraryCRAN/gdata/perl/xls2csv.pl line 270.
## and then also this:
# Warning message:
#   In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
#             EOF within quoted string

## the default intermediate file for read.xls() is comma delimited
## in the docs:
## "Caution: In the conversion to csv, strings will be quoted"

## ultimately, I followed more advice in the docs:

# If you have quotes in your data which confuse the process you may wish to use
# read.xls(..., quote = ''). This will cause the quotes to be regarded as data
# and you will have to then handle the quotes yourself after reading the file in

# http://stackoverflow.com/questions/17414776/read-csv-warning-eof-within-quoted-string-prevents-complete-reading-of-file

## initial read.xls() import created quotes within quotes, deriving from the
## extra fields I'm not using

## this created some very strange entries for cells and screwed around with the
## number of rows

# le_xls %>% str
## 41865 obs. of  9 variables:

## these next commands almost hung R/RStudio but I did eventually get the
## command prompt back.
# levels(le_raw$year)
# nlevels(le_raw$year) # 295
# summary(le_raw$year)

## I wrote that object to file for inspection
# write.table(le_raw,
#             "01_le.tsv",
#             sep = "\t", row.names = FALSE)

## and determined that I needed to figure out this file's encoding and deal with
## the embedded quotes problem --> that meant I should switch to tab-delimited
## as the intermediate file format

## so I tried making the intermediate file explicitly and then importing it with
## read.table()

## note: at this point, I was still confused about the encoding because
## TextWrangler had indicated the encoding was Western (Mac OS Roman)

# con <-
#   xls2tab("xls/life-expectancy-reference-spreadsheet-20090204-xls-format.xls",
#           verbose = TRUE, sheet = "Data and metadata",
#           fileEncoding =  "MACROMAN")

## usual warnings about "wide character" and "EOF within quoted string"

# (temp_file <- summary(con)$description)

## here is where I decide that I want to only read the first four
## columns/variables, since it's the other columns/variables causing all the
## problems

# http://stackoverflow.com/questions/2193742/ways-to-read-only-select-columns-from-a-file-into-r-a-happy-medium-between-re
# http://stackoverflow.com/questions/5788117/only-read-limited-number-of-columns-in-r

## trying and failing to learn the number columns programmatically
# max(count.fields(temp_file, sep = "\t"))
## NA ... never seems to work

## experimenting with only reading (or retaining?) the first 4 columns

## around now is where I also figure out the correct encoding: realized a
## curly equals sign or \305 was appearing instead of capital A with a circle on
## top, which I then googled
## the country affected: Åland
## http://www.ic.unicamp.br/~stolfi/EXPORT/www/ISO-8859-1-Encoding.html
## look into how to determine encoding more automatically?
# foo <- read.delim(temp_file, quote = "",
#                   fileEncoding =  "ISO-8859-1",
#                   colClasses = c(rep("character", 4), rep("NULL", 5)))

## lines where you can see evidence of encoding problems when using read.xls()
## ineptly:

## L12068
# " 2002; Andreev"  " and 1984; Johansen"	" 2002)"	" Denmark‚Äôs health transition began in the 1770s when"
# L37785 and beyond
# " Vladimir and Ilie Hristache. 1986. Demografia teritoriala a Rom√¢niei. Bucharest.,
# Europe,Romania,1933,,,,,,
# Europe,Romania,1934,,,,,,
# ...
# Europe,Romania,2007,72.476,UN:WPP,,medium variant projection,,
# FSU,Russian Federation,1800,31.9,Riley file extrapolation,,,,5

## lessons learned going in these circles eventually led to the functional
## read.xls() call used in the live code here
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # determine position index of rows
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + 2 } # optional whiteline => 1 ipv 2?
  
  data_end_r <- data_start_r + n_data_rows
  col_margin_r <- data_end_r + 1  

  if ( add.comment == TRUE ) { comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  
  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_r <- 1 + n_data_cols
  if (add.row.margin == TRUE) { table_end_r + 1 } 

  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = table_start_r, cols = table_start_r:table_end_r, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = table_start_r+1, cols = table_start_r:table_end_r, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # determine position index of rows
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + 2 } # optional whiteline => 1 ipv 2?
  
  data_end_r <- data_start_r + n_data_rows
  col_margin_r <- data_end_r + 1  

  if ( add.comment == TRUE ) { comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }
  
  # determine position index of cols
  
  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  #n_total_cols <- 
  #n_total_rows <- 

  
  
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        list(value = do.call(base::source, source_args)$value,
             preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args)
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        list(value = do.call(base::source, source_args)$value,
             preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
#' This R script will process all R mardown files (those with in_ext file extention,
#' .rmd by default) in the current working directory. Files with a status of
#' 'processed' will be converted to markdown (with out_ext file extention, '.markdown'
#' by default). It will change the published parameter to 'true' and change the
#' status parameter to 'publish'.
#' 
#' @param path_site path to the local root storing the site files
#' @param dir_rmd directory containing R Markdown files (inputs)
#' @param dir_md directory containing markdown files (outputs)
#' @param url_images where to store/get images created from plots directory +"/" (relative to path_site)
#' @param out_ext the file extention to use for processed files.
#' @param in_ext the file extention of input files to process.
#' @param recursive should rmd files in subdirectories be processed.
#' @return nothing.
#' @author Jason Bryer <jason@bryer.org> edited by Andy South
rmd2md <- function( path_site = getwd(),
                    dir_rmd = "_rmd",
                    dir_md = "_posts",                              
                    #dir_images = "figures",
                    url_images = "figures/",
                    out_ext='.md', 
                    in_ext='.rmd', 
                    recursive=FALSE) {
  
  require(knitr, quietly=TRUE, warn.conflicts=FALSE)

  #andy change to avoid path problems when running without sh on windows 
  files <- list.files(path=file.path(path_site,dir_rmd), pattern=in_ext, ignore.case=TRUE, recursive=recursive)
  
  for(f in files) {
    message(paste("Processing ", f, sep=''))
    content <- readLines(file.path(path_site,dir_rmd,f))
    frontMatter <- which(substr(content, 1, 3) == '---')
    if(length(frontMatter) >= 2 & 1 %in% frontMatter) {
      statusLine <- which(substr(content, 1, 7) == 'status:')
      publishedLine <- which(substr(content, 1, 10) == 'published:')
      if(statusLine > frontMatter[1] & statusLine < frontMatter[2]) {
        status <- unlist(strsplit(content[statusLine], ':'))[2]
        status <- sub('[[:space:]]+$', '', status)
        status <- sub('^[[:space:]]+', '', status)
        if(tolower(status) == 'process') {
          #This is a bit of a hack but if a line has zero length (i.e. a
          #black line), it will be removed in the resulting markdown file.
          #This will ensure that all line returns are retained.
          content[nchar(content) == 0] <- ' '
          message(paste('Processing ', f, sep=''))
          content[statusLine] <- 'status: publish'
          content[publishedLine] <- 'published: true'
          
          #andy change to path
          outFile <- file.path(path_site, dir_md, paste0(substr(f, 1, (nchar(f)-(nchar(in_ext)))), out_ext))
                   
          #render_markdown(strict=TRUE)
          #andy chnage to render for jekyll
          render_jekyll(highlight = "pygments")
          
          opts_knit$set(out.format='markdown') 
                    
          # andy BEWARE don't set base.dir!! it caused me problems
          # "base.dir is never used when composing the URL of the figures; it is 
          # only used to save the figures to a different directory. 
          # The URL of an image is always base.url + fig.path"
          # https://groups.google.com/forum/#!topic/knitr/18aXpOmsumQ
                    
          opts_knit$set(base.url = "/")
          opts_chunk$set(fig.path = url_images)                     
          
          try(knit(text=content, output=outFile), silent=FALSE)
          
        } else {
          warning(paste("Not processing ", f, ", status is '", status, 
                        "'. Set status to 'process' to convert.", sep=''))
        }
      } else {
        warning("Status not found in front matter.")
      }
    } else {
      warning("No front matter found. Will not process this file.")
    }
  }
  invisible()
}#load and parse html tables

#load libraries
library(stringr)
library(stringi)
library(XML)
library(dplyr)
library(magrittr)

#function to clean up character vectors- removes punctuation.
get_real_words <- function(word) {
  word[!stringr::str_detect(word, "[^a-z ]")]
}

#Loads all the html tables into one list
table_dir <- "table"
files <- dir(table_dir, "*.html")
tbls <- file.path(table_dir, files) %>%
  lapply(., htmlParse) %>%
  lapply(., readHTMLTable, head = FALSE, stringsAsFactors = FALSE, which = 1) 

#bind the tables together into one large table with 3 columns
all_tbls <- do.call(rbind, tbls)

#Process the text in column to remove non-characters
tbls_words<- gsub("\r", " ", all_tbls$V2)
tbls_words<- gsub("\t", " ", tbls_words) 
tbls_words<- gsub("\n", " ", tbls_words)
tbls_words<- gsub(",", " ", tbls_words)
#Turn into a list -should refactor to do this before then lapply()
tblwords.ls <- list(tbls_words)
#Create lower-case word-token strings with no punctuation
tblwords.ls <- lapply(tbwords.ls, paste, collapse= " ") %>%
  lapply(., tolower) %>%
  lapply(., WordTokenizer) %>%
  lapply(., get_real_words) %>%
  lapply(., unique)
#unlist into character vector
tblword.ch <- unlist(tblwords.ls)

#concatenate new words onto old stoplist (mallet's standard english stopwords with some icc-centric words)
cat(tblword.ch, file= "icc.txt", sep="\n", append = TRUE)
#load old list
stopwords<- scan(file="icc.txt", what= "character", sep="\n")
#Keep only the unique words in the stop list and re-save
stopwords <- unique(stopwords)
cat(stopwords, file="icc.txt", sep="\n", append = FALSE)


#Currently This code isn't necessary #/
#According to Hadley Wickham, creating an empty dataset and populating it is drastically faster in R
"tbl.df <- data.frame((character(length = length(tbls))), stringsAsFactors = FALSE)

#iterate through the list of tables and parse the html structure
i <- 1
for(i in 1:length(tbls)){
  
  i.df <- readHTMLTable(tbls[i], head = FALSE, stringsAsFactors = FALSE)
  tbl.df <- cbind(tbl.df, i.df)

}

readHTMLTable(tbls[1])


stopwords <- unique(tbls)
"
#Parse a sample table, this is the path
doc <-"table/v02toc.html"

#Pull in html files
p <- htmlParse(doc)

 

#iccv02toc.df <- xmlToDataFrame(p, collectNames = FALSE, stringsAsFactors = FALSE, nodes= iccv02toc[4] )

iccv02toc <- readHTMLTable(p, header = FALSE, stringsAsFactors = FALSE)

#Turn the HtmlInternalDocument into a data.frame
iccv02toc.df <- as.data.frame(iccv02toc[4], stringsAsFactors = FALSE)

#Use dplyr to munge the data from 3 columns of information into several columns of information
#First is to move plaintiff tribe into a separate column.
#iccv02toc.df$table1.V2 <- str_replace_all(iccv02toc.df$table1.V2, "[\t]", "")

v02tocfinal.df <- 
  iccv02toc.df %>%
  mutate(tribe = str_match(table1.V2, "(.*?)\r\n")[,2]) %>%
  
  View()


v02tocfinal.df <- mutate(v02tocfinal.df, page1 = str_extract(v02tocfinal.df$table1.V3, ".*\r\n"))



str(iccv02toc)
write.csv(iccv02toc[4], file = "out/iccv02toc.csv")
#load and parse html tables

#load libraries
library(stringr)
library(stringi)
library(XML)
library(dplyr)
library(magrittr)

#function to clean up character vectors- removes punctuation.
get_real_words <- function(word) {
  word[!stringr::str_detect(word, "[^a-z ]")]
}

#Loads all the html tables into one list
table_dir <- "table"
files <- dir(table_dir, "*.html")
tbls <- file.path(table_dir, files) %>%
  lapply(., htmlParse) %>%
  lapply(., readHTMLTable, head = FALSE, stringsAsFactors = FALSE, which = 1) 

all_tbls <- do.call(rbind, tbls)

tbls_words<- gsub("\r", " ", all_tbls$V2)
tbls_words<- gsub("\t", " ", tbls_words) 
tbls_words<- gsub("\n", " ", tbls_words)
tbls_words<- gsub(",", " ", tbls_words)
tblwords.ls <- list(tbls_words)
tblwords.ls <- lapply(tblwords.ls, paste, collapse= " ") %>%
  lapply(., tolower) %>%
  lapply(., WordTokenizer) %>%
  lapply(., get_real_words) %>%
  lapply(., unique)
stopwords<- strsplit(" ", tbls_words)
stopwords <- unique(tblswords[1])


tbls %>%
  lapply(``[[`) %>%

#Currently This code isn't necessary #/
#According to Hadley Wickham, creating an empty dataset and populating it is drastically faster in R
"tbl.df <- data.frame((character(length = length(tbls))), stringsAsFactors = FALSE)

#iterate through the list of tables and parse the html structure
i <- 1
for(i in 1:length(tbls)){
  
  i.df <- readHTMLTable(tbls[i], head = FALSE, stringsAsFactors = FALSE)
  tbl.df <- cbind(tbl.df, i.df)

}

readHTMLTable(tbls[1])


stopwords <- unique(tbls)
"
#Parse a sample table, this is the path
doc <-"table/v02toc.html"

#Pull in html files
p <- htmlParse(doc)

 

#iccv02toc.df <- xmlToDataFrame(p, collectNames = FALSE, stringsAsFactors = FALSE, nodes= iccv02toc[4] )

iccv02toc <- readHTMLTable(p, header = FALSE, stringsAsFactors = FALSE)

#Turn the HtmlInternalDocument into a data.frame
iccv02toc.df <- as.data.frame(iccv02toc[4], stringsAsFactors = FALSE)

#Use dplyr to munge the data from 3 columns of information into several columns of information
#First is to move plaintiff tribe into a separate column.
#iccv02toc.df$table1.V2 <- str_replace_all(iccv02toc.df$table1.V2, "[\t]", "")

v02tocfinal.df <- 
  iccv02toc.df %>%
  mutate(tribe = str_match(table1.V2, "(.*?)\r\n")[,2]) %>%
  
  View()


v02tocfinal.df <- mutate(v02tocfinal.df, page1 = str_extract(v02tocfinal.df$table1.V3, ".*\r\n"))



str(iccv02toc)
write.csv(iccv02toc[4], file = "out/iccv02toc.csv")
adios.read.init.method <- function(adios.read.method, comm = pbdMPI::.SPMD.CT$comm,
                                  params){
    .Call(R_adios_read_init_method, as.character(adios.read.method),
          comm.c2f(comm), as.character(params))
}

adios.read.open <- function(adios.filename, adios.read.method,
                            comm = pbdMPI::.SPMD.CT$comm, adios.lockmode,
                            adios.timeout.sec){  
    .Call(R_adios_read_open, as.character(adios.filename),
          as.character(adios.read.method), comm.c2f(comm),
          as.character(adios.lockmode),as.numeric(adios.timeout.sec))
}

adios.read.close <- function(adios.file.ptr){
    invisible(.Call(R_adios_read_close, adios.file.ptr))
}

adios.read.finalize.method<- function(adios.read.method){
    invisible(.Call(R_adios_read_finalize_method,
                    as.character(adios.read.method)))
}

adios.inq.var <- function(adios.file.ptr, adios.varname){
    .Call(R_adios_inq_var, adios.file.ptr, as.character(adios.varname))
}

custom.inq.var.ndim <- function(adios.varinfo){
    .Call(R_custom_inq_var_ndim, adios.varinfo)
}

custom.inq.var.dims <- function(adios.varinfo){
    .Call(R_custom_inq_var_dims, adios.varinfo)
}

adios.inq.var.blockinfo <- function(adios.file.ptr, adios.varinfo){
    .Call(R_adios_inq_var_blockinfo,adios.file.ptr, adios.varinfo)
}

adios.selection.boundingbox <- function(adios.ndim, adios.start, adios.count){
    .Call(R_adios_selection_bounding_box, as.integer(adios.ndim),
          as.integer(adios.start), as.integer(adios.count))
}

adios.schedule.read <- function(adios.varinfo, adios.start, adios.count,
                                adios.file.ptr, adios.selection, adios.varname,
                                adios.from.steps, adios.nsteps){
    .Call(R_adios_schedule_read, adios.varinfo, as.integer(adios.start),
          as.integer(adios.count), adios.file.ptr, adios.selection,
          as.character(adios.varname), as.integer(adios.from.steps),
          as.integer(adios.nsteps))
}

custom.data.access <- function(adios.data, adios.selection, adios.varinfo){
    .Call(R_custom_data_access, adios.data, adios.selection,adios.varinfo)
}

adios.perform.reads <- function(adios.file.ptr, adios.blocking){
    .Call(R_adios_perform_reads,adios.file.ptr, as.integer(adios.blocking))
}

adios.advance.step <- function(adios.file.ptr, adios.last, adios.timeout.sec){
    invisible(.Call(R_adios_advance_step,adios.file.ptr,
                    as.integer(adios.last), as.numeric(adios.timeout.sec)))
}

adios.errno <- function(){
    .Call(R_adios_errno)
}


REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit compose/deep [[
					stack/top: stack/top - 1
					copy-cell stack/top stack/top - 1
					stack/check-call
				]]
			][
				mark: tail output
				unless head? path [
					emit compose/deep [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-word-set
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-word-set*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-word-set* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native (name)	;@@ make a unique name for function's body frame
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec first back find objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			emit reduce [to set-word! name 'func]
			insert-lf -2
			append/only output spec
			append/only output body
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame name
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc rejoin [load-cache %version.r ", " now]
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
parse_documentation = function (module) {
    module_path = module_path(module)
    parsed = list(env = module,
                  blocks = roxygen2:::parse_file(module_path, module))
    roclet = roxygen2:::rd_roclet()
    rdfiles = roxygen2:::roc_process(roclet, parsed, dirname(module_path))

    # Due to aliases, documentation entries may have more than one name.
    # Duplicate the relevant documentation entries to get around this.
    # Unfortunately this makes the relevant code ~7x longer.
    aliases = lapply(rdfiles, function (rd) unique(rd[[1]]$alias$value))
    doc_for_name = function (name, aliases)
        sapply(aliases, function (.) rdfiles[[name]], simplify = FALSE)
    docs = mapply(doc_for_name, names(aliases), aliases, SIMPLIFY = FALSE)
    formatted = lapply(unlist(docs, recursive = FALSE, use.names = FALSE),
                       roxygen2:::format.rd_file, wrap = FALSE)
    setNames(formatted, unlist(lapply(docs, names)))
}

#' Display module documentation
#'
#' \code{module_help} displays help on a module’s objects and functions in much
#' the same way \code{\link[utils]{help}} does for package contents.
#'
#' @param topic fully-qualified name of the object or function to get help for,
#'  in the format \code{module$function}
#' @param help_type character string specifying the output format; currently,
#'  only \code{'text'} is supported
#' @note Help is only available if \code{\link{import}} loaded the help stored
#' in the module file(s). By default, this happens only in interactive sessions.
#' @rdname help
#' @export
#' @examples
#' \dontrun{
#' mod = import('mod')
#' module_help(mod$func)
#' }
module_help = function (topic, help_type = getOption('help_type', 'text')) {
    if (help_type != 'text')
        warning('Only help_type == ', sQuote('text'), ' supported for now.')

    topic = substitute(topic)

    if (! is_module_help_topic(topic, parent.frame()))
        stop(sQuote(deparse(topic)), ' is not a valid module help topic',
             call. = FALSE)

    module = get(as.character(topic[[2]]), parent.frame())
    module_name = module_name(module)
    object = as.character(topic[[3]])

    doc = attr(module, 'doc')[[object]]
    if (is.null(doc))
        stop('No documentation available for ', sQuote(object),
             ' in module ', sQuote(module_name), call. = FALSE)

    rd = tools::parse_Rd(textConnection(doc))

    # Taken from utils:::print.help_files_with_topic
    temp = tools::Rd2txt(rd, out = tempfile('Rtxt'), package = module_name)

    # Patch header line.
    doc_text = readLines(temp)
    doc_text[1] = sub('package:', ' module:', doc_text[1])
    writeLines(doc_text, temp)

    file.show(temp,
              title = gettextf('R Help on %s', sQuote(as.character(topic))),
              delete.file = TRUE)
}

is_module_help_topic = function (topic, parent) {
    # For nested modules, `topic` looks like this: `a$b$c…`. We need to retrieve
    # the first part of this (`a`) and check whether it’s a module.

    leftmost_name = function (expr) {
        if (is.name(expr))
            expr
        else if (! is.call(expr) || expr[[1]] != '$')
            NULL
        else
            leftmost_name(expr[[2]])
    }

    top_module = leftmost_name(topic)

    ! is.null(top_module) &&
        exists(as.character(top_module), parent) &&
        ! is.null(module_name(get(as.character(top_module), parent)))
}

#' @usage
#' ?module$function
#' @inheritParams utils::`?`
#' @rdname help
#' @export
#' @examples
#' \dontrun{
#' ?mod$func
#' }
`?` = function (e1, e2) {
    topic = substitute(e1)
    if (missing(e2) && is_module_help_topic(topic, parent.frame()))
        eval(call('module_help', topic), envir = parent.frame())
    else
        eval(`[[<-`(match.call(), 1, utils::`?`), envir = parent.frame())
}

#' @usage
#' help(module$function)
#' @inheritParams utils::help
#' @export
#' @examples
#' \dontrun{
#' help(mod$func)
#' }
help = function (topic, ...) {
    topic = substitute(topic)
    delegate = if (! missing(topic) &&
                   is_module_help_topic(topic, parent.frame()))
        module_help
    else
        utils::help
    eval(`[[<-`(match.call(), 1, delegate), envir = parent.frame())
}
# Diffuse_fraction_of_solar_radiation.R
#
# Pieter Beck (psabeck@gmail.com)
# 09-12-2013
# 
# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation
#
#
# Changelog:
#   VERS  | DATE  		 | CHANGES				| BY
#   ------|------------|----------------|---- 
#		1.0.0	|	09-12-2013 | Wrote script		| PB

#Id is diffuse radiation
#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)
#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation 
#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)


#kt is the clearness index
#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)
#reaching the surface.
#it is defined as kt = I / (Io cos solarzen).
#DSWRF = Downward short wave radiation flux 


IdoverI.calc <- function(kt,solarzen){
  #calculate the fraction of diffuse radiation in global radiation
  #using the Reindl* method (Helbig 2009)
  #
  # Args: 
  #  kt: The clearness index (sensu Liu and Jordan 1960)
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #   the fraction of diffuse radiation (Id) in global radiation (I)
  #  
  IdoverI = kt*NA

    Under.78 <- which(kt < 0.78 & kt >0.3)
    solar.elev <- pi/2 - solarzen[Under.78] 
    IdoverI[Under.78] <- 1.4 - 1.749*kt[Under.78] + 0.177*sin(solar.elev)
    
    Under.3 <- which(kt <= 0.3)
    IdoverI[Under.3] <- 0.1020 - 0.248*kt[Under.3]
    
    Over.78 <- which(kt >= 0.78)
    IdoverI[Over.78] <- 0.147
  
  return(IdoverI)
}

SpSd.calc <- function(Rsurface,R_extra_terr,solarzen){
  #calculate direct (Sp) and diffuse (Sd) radiation from global radiation
  #and horizontal extraterrestrial radiation 
  #
  # Args: 
  #  Rsurface: incoming shortwave radiation at the surface
  #  R_extra_terr: horizontal extraterrestrial radiation 
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #  A two-column matrix giving incoming direct [,1], and diffuse [,2] radiationd at the surface
  # 
  if (solarzen > 2*pi){cat("STOP STOP STOP provide solarzenith in radiance to SpSd.calc\n");browser()}
  kt <- Rsurface/R_extra_terr
  #the formula in Lanini 2010 p1 is
  #kt <- Rsurface/(Io*cos(solarzen))
  #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation
  #and thus is adjusted for latitude/solarzen before comparison with Rsurface
  #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation
  IdoverI <- IdoverI.calc(kt,solarzen)
  IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1
  SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)
  return(SpSd)
}

solarzen.calc <- function(coords,datetimePOSIXct){
  #calculate solar zenith based on lat, lon & time of day
  #
  # Args: 
  #  coords: coordinates
  #  datetimePOSIXct: a POSIXct object giving date and time
  #
  # Returns:
  #  solar zenith angle
  #
  require(maptools)
  solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)
  solarelv <- solarelv[,2]
  #convert to radians
  solarelv <- pi*solarelv/180
  #convert to solar zenith (0 when sun is overhead) in radians
  solarzen <- pi/2 - solarelv
  #set below-horizon zeniths to pi/2
  solarzen[solarzen > pi/2] <- pi/2
  cat("in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\n
      while 0 represents directly over-head\n")
  return(solarzen)  
}

R_extra_terr.calc<-function(thisdate,lat.in.deg){
  #calculate hourly extraterrestrial irradiance in W/m2 using sirad package
  #
  # Args: 
  #  thisdate: string object giving date, e.g. "2011-12-31"
  #  lat.in.deg: lattitude in degrees
  #
  # Returns:
  #  hourly extraterrestrial radiation
  #
  # Example:
  #  R_extra_terr.calc(thisdate=c("2012-01-19","2012-01-19"),lat.in.deg=c(-69))
  #
  require(sirad)
  JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear("2011-01-01")
  lat.in.rad <- lat.in.deg*pi/180
  R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]
  #extrat[[1]] uses MJ/(day m^2) units
  #extrat[[2]] uses MJ/(hr m^2) units
  #convert output to W/m2
  conv.fac.daily <- (1000000/ 86400)
  conv.fac.hourly <- (1000000/ 86400)*24
  R_extra_terr[[1]] <- conv.fac.daily *  R_extra_terr[[1]]
  R_extra_terr[[2]] <- conv.fac.hourly *  R_extra_terr[[2]]
  #set negative hourly extrat irrad to 0
  #R_exta_terr <- R_exta_terr[[2]]
  R_extra_terr[[2]][R_extra_terr[[2]]<0]<-0
  R_extra_terr <- R_extra_terr[[2]]
  R_extra_terr <- matrix(R_extra_terr,ncol=24)
  cat("calculated 24hrs of extraterrestrial irradiance for\n"
      ,nrow(R_extra_terr)," latitude-date combinations\n")
  #output is hourly starting at solar midning
  return(R_extra_terr)
}

shift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){
  # Shift a vector over by n spots
  #
  #Args: 
  #  vec: vector to be shifted
  #  n: number of spots to shift the vector over
  #
  #  Wrap adds the entry at the beginning to the end
  # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs
  #
  # Returns:
  #  the vector vec, shifted over n sots
  # 
  # Source:
  #  http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions
  #
  if(length(vec)<abs(n)) { 
    #stop("Length of vector must be greater than the magnitude of n \n") 
  }
  if(n==0) { 
    return(vec) 
  } else if(length(vec)==n) { 
    # return empty
    length(vec) <- 0
    return(vec)
  } else if(n>0) {
    returnvec <- vec[seq(n+1,length(vec) )]
    if(wrap) {
      returnvec <- c(returnvec,vec[seq(n)])
    } else if(pad) {
      returnvec <- c(returnvec,rep(NA,n))
    }
  } else if(n<0) {
    returnvec <- vec[seq(1,length(vec)-abs(n))]
    if(wrap) {
      returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )
    } else if(pad) {
      returnvec <- c( rep(NA,abs(n)), returnvec )
    }
    
  }
  return(returnvec)
}

shift_to_UTC <- function(hourly_tser,original.zone){
  #shift an hourly vector starting at midnight to start at midnight UTC
  #
  #Args: 
  #  hourly_tser: an hourly vector starting at midnight local time
  #  original.zone: the local time zone
  #
  # Returns:
  #  an hourly vector, starting at midnight UTC
  # 
  # Example:
  #  shift_to_UTC(hourly_tser=1:24,original.zone="America/Mexico_City")
  require(timeDate)
  tt1<-timeDate("2010-01-01 00:00:00",zone=original.zone)
  tt2<-timeDate("2010-01-01 00:00:00",zone="UTC")
  shift.by <- as.numeric(tt2-tt1)
  cat("the 24 hour series will be shifted earlier hrs by ",shift.by," hours to match UTC\n")
  if (is.matrix(hourly_tser)){
    shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))
    }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}
  return(shifted_tser)
}

R_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){
  #given a date, latitude, and time zone, calculate extraterrestrial radiation
  #for that latitude
  #
  #Args:
  #  thisdate: date
  #  lat.in.deg: latitude in degrees
  #  original.zone: timezone
  #
  # Returns:
  #  Extraterrestrial radiation for the given latitude and day, in 6 hour steps
  #
  if(length(thisdate)!=length(lat.in.deg)){
    cat("Please provide thisdate and lat.in.deg of equal length\n");browser()}
  #get the 24 R_extra_terr values for this lat & date
  R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)
  #determine by how many hours the series need to be shifted
  R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)
  #convert the R_extra_terr values from 24 hour to epoch
  epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}
  R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))
  cat("all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\n")
  rm(R_extra_terr_24,R_extra_terr_24UTC)
  return(R_extra_terr_epochUTC)
}

# Diffuse_fraction_of_solar_radiation.R
#
# Pieter Beck (psabeck@gmail.com)
# 09-12-2013
# 
# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation
#
#
# Changelog:
#   VERS  | DATE  		 | CHANGES				| BY
#   ------|------------|----------------|---- 
#		1.0.0	|	09-12-2013 | Wrote script		| PB

#Id is diffuse radiation
#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)
#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation 
#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)


#kt is the clearness index
#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)
#reaching the surface.
#it is defined as kt = I / (Io cos solarzen).
#DSWRF = Downward short wave radiation flux 


IdoverI.calc <- function(kt,solarzen){
  #calculate the fraction of diffuse radiation in global radiation
  #using the Reindl* method (Helbig 2009)
  #
  # Args: 
  #  kt: The clearness index (sensu Liu and Jordan 1960)
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #   the fraction of diffuse radiation (Id) in global radiation (I)
  #  
  IdoverI = kt*NA

    Under.78 <- which(kt < 0.78 & kt >0.3)
    solar.elev <- pi/2 - solarzen[Under.78] 
    IdoverI[Under.78] <- 1.4 - 1.749*kt[Under.78] + 0.177*sin(solar.elev)
    
    Under.3 <- which(kt <= 0.3)
    IdoverI[Under.3] <- 0.1020 - 0.248*kt[Under.3]
    
    Over.78 <- which(kt >= 0.78)
    IdoverI[Over.78] <- 0.147
  
  return(IdoverI)
}

SpSd.calc <- function(Rsurface,R_extra_terr,solarzen){
  #calculate direct (Sp) and diffuse (Sd) radiation from global radiation
  #and horizontal extraterrestrial radiation 
  #
  # Args: 
  #  Rsurface: incoming shortwave radiation at the surface
  #  R_extra_terr: horizontal extraterrestrial radiation 
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #  A two-column matrix giving incoming direct [,1], and diffuse [,2] radiationd at the surface
  # 
  if (solarzen > 2*pi){cat("STOP STOP STOP provide solarzenith in radiance to SpSd.calc\n");browser()}
  kt <- Rsurface/R_extra_terr
  #the formula in Lanini 2010 p1 is
  #kt <- Rsurface/(Io*cos(solarzen))
  #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation
  #and thus is adjusted for latitude/solarzen before comparison with Rsurface
  #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation
  IdoverI <- IdoverI.calc(kt,solarzen)
  IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1
  SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)
  return(SpSd)
}

solarzen.calc <- function(coords,datetimePOSIXct){
  #calculate solar zenith based on lat, lon & time of day
  #
  # Args: 
  #  coords: coordinates
  #  datetimePOSIXct: a POSIXct object giving date and time
  #
  # Returns:
  #  solar zenith angle
  #
  require(maptools)
  solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)
  solarelv <- solarelv[,2]
  #convert to radians
  solarelv <- pi*solarelv/180
  #convert to solar zenith (0 when sun is overhead) in radians
  solarzen <- pi/2 - solarelv
  #set below-horizon zeniths to pi/2
  solarzen[solarzen > pi/2] <- pi/2
  cat("in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\n
      while 0 represents directly over-head\n")
  return(solarzen)  
}

R_extra_terr.calc<-function(thisdate,lat.in.deg){
  #calculate hourly extraterrestrial irradiance in W/m2 using sirad package
  #
  # Args: 
  #  thisdate: string object giving date, e.g. "2011-12-31"
  #  lat.in.deg: lattitude in degrees
  #
  # Returns:
  #  hourly extraterrestrial radiation
  #
  # Example:
  #  R_extra_terr.calc(thisdate=c("2012-01-19","2012-01-19"),lat.in.deg=c(-69))
  #
  require(sirad)
  JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear("2011-01-01")
  lat.in.rad <- lat.in.deg*pi/180
  R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]
  #extrat[[1]] uses MJ/(day m^2) units
  #extrat[[2]] uses MJ/(hr m^2) units
  #convert output to W/m2
  conv.fac.daily <- (1000000/ 86400)
  conv.fac.hourly <- (1000000/ 86400)*24
  R_extra_terr[[1]] <- conv.fac.daily *  R_extra_terr[[1]]
  R_extra_terr[[2]] <- conv.fac.hourly *  R_extra_terr[[2]]
  #set negative hourly extrat irrad to 0
  #R_exta_terr <- R_exta_terr[[2]]
  R_extra_terr[[2]][R_extra_terr[[2]]<0]<-0
  R_extra_terr <- R_extra_terr[[2]]
  R_extra_terr <- matrix(R_extra_terr,ncol=24)
  cat("calculated 24hrs of extraterrestrial irradiance for\n"
      ,nrow(R_extra_terr)," latitude-date combinations\n")
  #output is hourly starting at solar midning
  return(R_extra_terr)
}

shift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){
  # Shift a vector over by n spots
  #
  #Args: 
  #  vec: vector to be shifted
  #  n: number of spots to shift the vector over
  #
  #  Wrap adds the entry at the beginning to the end
  # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs
  #
  # Returns:
  #  the vector vec, shifted over n sots
  # 
  # Source:
  #  http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions
  #
  if(length(vec)<abs(n)) { 
    #stop("Length of vector must be greater than the magnitude of n \n") 
  }
  if(n==0) { 
    return(vec) 
  } else if(length(vec)==n) { 
    # return empty
    length(vec) <- 0
    return(vec)
  } else if(n>0) {
    returnvec <- vec[seq(n+1,length(vec) )]
    if(wrap) {
      returnvec <- c(returnvec,vec[seq(n)])
    } else if(pad) {
      returnvec <- c(returnvec,rep(NA,n))
    }
  } else if(n<0) {
    returnvec <- vec[seq(1,length(vec)-abs(n))]
    if(wrap) {
      returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )
    } else if(pad) {
      returnvec <- c( rep(NA,abs(n)), returnvec )
    }
    
  }
  return(returnvec)
}

shift_to_UTC <- function(hourly_tser,original.zone){
  #shift an hourly vector starting at midnight to start at midnight UTC
  #
  #Args: 
  #  hourly_tser: an hourly vector starting at midnight local time
  #  original.zone: the local time zone
  #
  # Returns:
  #  an hourly vector, starting at midnight UTC
  # 
  # Example:
  #  shift_to_UTC(hourly_tser=1:24,original.zone="America/Mexico_City")
  require(timeDate)
  tt1<-timeDate("2010-01-01 00:00:00",zone=original.zone)
  tt2<-timeDate("2010-01-01 00:00:00",zone="UTC")
  shift.by <- as.numeric(tt2-tt1)
  cat("the 24 hour series will be shifted earlier hrs by ",shift.by," hours to match UTC\n")
  if (is.matrix(hourly_tser)){
    shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))
    }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}
  return(shifted_tser)
}

R_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){
  #given a date, latitude, and time zone, calculate extraterrestrial radiation
  #for that latitude
  #
  #Args:
  #  thisdate: date
  #  lat.in.deg: latitude in degrees
  #  original.zone: timezone
  #
  # Returns:
  #  Extraterrestrial radiation for the given latitude and day, in 6 hour steps
  #
  if(length(thisdate)!=length(lat.in.deg)){
    cat("Please provide thisdate and lat.in.deg of equal length\n");browser()}
  #get the 24 R_extra_terr values for this lat & date
  R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)
  #determine by how many hours the series need to be shifted
  R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)
  #convert the R_extra_terr values from 24 hour to epoch
  epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}
  R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))
  cat("all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\n")
  rm(R_extra_terr_24,R_extra_terr_24UTC)
  return(R_extra_terr_epochUTC)
}

# Diffuse_fraction_of_solar_radiation.R
#
# Pieter Beck (psabeck@gmail.com)
# 09-12-2013
# 
# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation
#
#
# Changelog:
#   VERS  | DATE  		 | CHANGES				| BY
#   ------|------------|----------------|---- 
#		1.0.0	|	09-12-2013 | Wrote script		| PB

#Id is diffuse radiation
#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)
#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation 
#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)


#kt is the clearness index
#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)
#reaching the surface.
#it is defined as kt = I / (Io cos solarzen).
#DSWRF = Downward short wave radiation flux 


IdoverI.calc <- function(kt,solarzen){
  #calculate the fraction of diffuse radiation in global radiation
  #using the Reindl* method (Helbig 2009)
  #
  # Args: 
  #  kt: The clearness index (sensu Liu and Jordan 1960)
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #   the fraction of diffuse radiation (Id) in global radiation (I)
  #  
  IdoverI = kt*NA

    Under.78 <- which(kt < 0.78 & kt >0.3)
    solar.elev <- pi/2 - solarzen[Under.78] 
    IdoverI[Under.78] <- 1.4 - 1.749*kt[Under.78] + 0.177*sin(solar.elev)
    
    Under.3 <- which(kt <= 0.3)
    IdoverI[Under.3] <- 0.1020 - 0.248*kt[Under.3]
    
    Over.78 <- which(kt >= 0.78)
    IdoverI[Over.78] <- 0.147
  
  return(IdoverI)
}

SpSd.calc <- function(Rsurface,R_extra_terr,solarzen){
  #calculate direct (Sp) and diffuse (Sd) radiation from global radiation
  #and horizontal extraterrestrial radiation 
  #
  # Args: 
  #  Rsurface: incoming shortwave radiation at the surface
  #  R_extra_terr: horizontal extraterrestrial radiation 
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #  A two-column matrix giving incoming direct [,1], and diffuse [,2] radiationd at the surface
  # 
  if (solarzen > 2*pi){cat("STOP STOP STOP provide solarzenith in radiance to SpSd.calc\n");browser()}
  kt <- Rsurface/R_extra_terr
  #the formula in Lanini 2010 p1 is
  #kt <- Rsurface/(Io*cos(solarzen))
  #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation
  #and thus is adjusted for latitude/solarzen before comparison with Rsurface
  #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation
  IdoverI <- IdoverI.calc(kt,solarzen)
  IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1
  SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)
  return(SpSd)
}

solarzen.calc <- function(coords,datetimePOSIXct){
  #calculate solar zenith based on lat, lon & time of day
  #
  # Args: 
  #  coords: coordinates
  #  datetimePOSIXct: a POSIXct object giving date and time
  #
  # Returns:
  #  solar zenith angle
  #
  require(maptools)
  solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)
  solarelv <- solarelv[,2]
  #convert to radians
  solarelv <- pi*solarelv/180
  #convert to solar zenith (0 when sun is overhead) in radians
  solarzen <- pi/2 - solarelv
  #set below-horizon zeniths to pi/2
  solarzen[solarzen > pi/2] <- pi/2
  cat("in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\n
      while 0 represents directly over-head\n")
  return(solarzen)  
}

R_extra_terr.calc<-function(thisdate,lat.in.deg){
  #calculate hourly extraterrestrial irradiance in W/m2 using sirad package
  #
  # Args: 
  #  thisdate: string object giving date, e.g. "2011-12-31"
  #  lat.in.deg: lattitude in degrees
  #
  # Returns:
  #  hourly extraterrestrial radiation
  #
  # Example:
  #  R_extra_terr.calc(thisdate=c("2012-01-19","2012-01-19"),lat.in.deg=c(-69))
  #
  require(sirad)
  JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear("2011-01-01")
  lat.in.rad <- lat.in.deg*pi/180
  R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]
  #extrat[[1]] uses MJ/(day m^2) units
  #extrat[[2]] uses MJ/(hr m^2) units
  #convert output to W/m2
  conv.fac.daily <- (1000000/ 86400)
  conv.fac.hourly <- (1000000/ 86400)*24
  R_extra_terr[[1]] <- conv.fac.daily *  R_extra_terr[[1]]
  R_extra_terr[[2]] <- conv.fac.hourly *  R_extra_terr[[2]]
  #set negative hourly extrat irrad to 0
  #R_exta_terr <- R_exta_terr[[2]]
  R_extra_terr[[2]][R_extra_terr[[2]]<0]<-0
  R_extra_terr <- R_extra_terr[[2]]
  R_extra_terr <- matrix(R_extra_terr,ncol=24)
  cat("calculated 24hrs of extraterrestrial irradiance for\n"
      ,nrow(R_extra_terr)," latitude-date combinations\n")
  #output is hourly starting at solar midning
  return(R_extra_terr)
}

shift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){
  # Shift a vector over by n spots
  #
  #Args: 
  #  vec: vector to be shifted
  #  n: number of spots to shift the vector over
  #
  #  Wrap adds the entry at the beginning to the end
  # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs
  #
  # Returns:
  #  the vector vec, shifted over n sots
  # 
  # Source:
  #  http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions
  #
  if(length(vec)<abs(n)) { 
    #stop("Length of vector must be greater than the magnitude of n \n") 
  }
  if(n==0) { 
    return(vec) 
  } else if(length(vec)==n) { 
    # return empty
    length(vec) <- 0
    return(vec)
  } else if(n>0) {
    returnvec <- vec[seq(n+1,length(vec) )]
    if(wrap) {
      returnvec <- c(returnvec,vec[seq(n)])
    } else if(pad) {
      returnvec <- c(returnvec,rep(NA,n))
    }
  } else if(n<0) {
    returnvec <- vec[seq(1,length(vec)-abs(n))]
    if(wrap) {
      returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )
    } else if(pad) {
      returnvec <- c( rep(NA,abs(n)), returnvec )
    }
    
  }
  return(returnvec)
}

shift_to_UTC <- function(hourly_tser,original.zone){
  #shift an hourly vector starting at midnight to start at midnight UTC
  #
  #Args: 
  #  hourly_tser: an hourly vector starting at midnight local time
  #  original.zone: the local time zone
  #
  # Returns:
  #  an hourly vector, starting at midnight UTC
  # 
  # Example:
  #  shift_to_UTC(hourly_tser=1:24,original.zone="America/Mexico_City")
  require(timeDate)
  tt1<-timeDate("2010-01-01 00:00:00",zone=original.zone)
  tt2<-timeDate("2010-01-01 00:00:00",zone="UTC")
  shift.by <- as.numeric(tt2-tt1)
  cat("the 24 hour series will be shifted earlier hrs by ",shift.by," hours to match UTC\n")
  if (is.matrix(hourly_tser)){
    shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))
    }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}
  return(shifted_tser)
}

R_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){
  #given a date, latitude, and time zone, calculate extraterrestrial radiation
  #for that latitude
  #
  #Args:
  #  thisdate: date
  #  lat.in.deg: latitude in degrees
  #  original.zone: timezone
  #
  # Returns:
  #  Extraterrestrial radiation for the given latitude and day, in 6 hour steps
  #
  if(length(thisdate)!=length(lat.in.deg)){
    cat("Please provide thisdate and lat.in.deg of equal length\n");browser()}
  #get the 24 R_extra_terr values for this lat & date
  R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)
  #determine by how many hours the series need to be shifted
  R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)
  #convert the R_extra_terr values from 24 hour to epoch
  epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}
  R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))
  cat("all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\n")
  rm(R_extra_terr_24,R_extra_terr_24UTC)
  return(R_extra_terr_epochUTC)
}

`%||%` <- function(x, y) if (is.null(x)) y else x

#' Merge two lists and overwrite latter entries with former entries
#' if names are the same.
#'
#' For example, \code{list_merge(list(a = 1, b = 2), list(b = 3, c = 4))}
#' will be \code{list(a = 1, b = 3, c = 4)}.
#' @param list1 list
#' @param list2 list
#' @return the merged list.
#' @examples
#' stopifnot(identical(syberiaStages:::list_merge(list(a = 1, b = 2), list(b = 3, c = 4)),
#'                     list(a = 1, b = 3, c = 4)))
#' stopifnot(identical(syberiaStages:::list_merge(NULL, list(a = 1)), list(a = 1)))
# TODO: (RK) This is a duplicate of the function in mungebits -- is there
# any way to pull them out into one place? Maybe Ramd?
list_merge <- function(list1, list2) {
  list1 <- list1 %||% list()
  # Pre-allocate memory to make this slightly faster.
  list1[Filter(function(x) nchar(x) > 0, names(list2) %||% c())] <- NULL
  for (i in seq_along(list2)) {
    name <- names(list2)[i]
    if (!identical(name, NULL) && !identical(name, "")) list1[[name]] <- list2[[i]]
    else list1 <- append(list1, list(list2[[i]]))
  }
  list1
}

#' Parse functions out of a custom resource.
#'
#' @param functions character. The names of functions to parse out.
#' @param provided_env environment. The environment the resource was loaded from.
#' @param type character. The keyword for the resource.
#' @param resource_type character. The type of the resource (e.g., "classifier",
#'   "adapter", etc.). This will be used to generate error messages.
#' @param strict logical. Whether or not to error if the functions are not found.
#' @return a list containing keys same as the \code{functions} argument.
#'    and predict functions.
parse_custom_functions <- function(functions, provided_env, type,
                                   resource_type = 'classifier', strict = TRUE) {
  provided_fns <- setNames(vector('list', length(functions)), functions)
  for (function_type in names(provided_fns)) {
    fn <- Filter(
      function(x) is.function(provided_env[[x]]),
      grep(function_type, ls(provided_env), value = TRUE)
    )
    # TODO: (RK) Refactor this to be more careful about idempotent resources.
    error <- function(snip = 'a') paste0("The custom ", resource_type, " in ",
      "lib/", resource_type, "s/", type, ".R should define ", snip, " '",
      testthat::colourise(function_type, 'green'), "' function.")
    if (length(fn) == 0 && identical(strict, TRUE)) stop(error(), call. = FALSE)
    else if (length(fn) > 1)
      stop(error('only one'), " Instead, you defined ", length(fn), ", namely: ",
           paste0(fn, collapse = ', '), call. = FALSE)
    else if (length(fn) == 1)
      provided_fns[[function_type]] <- provided_env[[fn]]
  }
  provided_fns
}

# Helper function to serialize a tundraContainer of xgboost model object
#
# TODO: (RK) Refactor this function out of the package.
serialize_xgb_object <- function(object) {
	file_save <- tempfile()
  on.exit(unlink(file_save), add = TRUE)
  xgboost::xgb.save(object$output$model, file_save)
  stopifnot(!is.na(as.integer(file.info(file_save)$size)))
  object$output$model <- NULL
  con <- file(file_save, 'rb')
  on.exit(close(con), add = TRUE)
  invisible(structure(
    class = 'special_serialized_object', 
    list(
      deserialize = function(x) {
        file_load <- tempfile()
        on.exit(unlink(file_load), add = TRUE)
        con <- file(file_load, 'wb')
        on.exit(tryCatch(if (isOpen(con)) close(con), 
          error = function(.) message("Connection is already closed")), 
          add = TRUE)
        writeBin(x$xgb.bin, con, useBytes = TRUE)
        # Do NOT remove the following line of code!!
        # Close out the connection before reading the binary.
        close(con)
        x$container$output$model <- xgboost::xgb.load(file_load)
        invisible(x$container)
      }, 
      object = list(
       container = object, 
       xgb.bin = readBin(con, raw(), n = file.info(file_save)$size)
      )
    )
  ))
}
library(pbdMPI, quiet = TRUE)
library(pbdDMAT, quiet = TRUE)
library(pbdADIOS, quiet = TRUE)
library(raster, quiet=TRUE)
library(ggplot2, quiet=TRUE)
library(grid, quiet=TRUE)

## begin function definitions
adios.init <- function(method="ADIOS_READ_METHOD_BP", par="verbose=3")
{
    invisible(adios.read.init.method("ADIOS_READ_METHOD_BP",
                                     params="verbose=3"))
}

adios.open <- function(file, timeout=1, method="ADIOS_READ_METHOD_BP",
                       lockmode="ADIOS_LOCKMODE_NONE")
{
    ## timeout default is 1 sec
    pt <- adios.read.open(file, adios.timeout=timeout, "ADIOS_READ_METHOD_BP",
                          adios.lockmode="ADIOS_LOCKMODE_NONE")
    if(comm.rank() == 0) bpls <- system(paste("bpls", file), intern=TRUE)
    else bpls <- NULL
    bpls <- bcast(bpls)
    list(pt=pt, bpls=bpls)
}

raster_plot <- function(x, nrow, ncol, basename="raster", sequence=1, swidth=3)
{
    x <- data.frame(rasterToPoints(raster(matrix(x, nrow, ncol),
                                          xmn=0, xmx=ncol, ymn=0, ymx=nrow)))
    names(x) <- c("x", "y", basename)
    png(paste(basename, "_", formatC(sequence, width=swidth, flag=0), "_",
              comm.rank(), ".png", sep=""))
    print(ggplot(x, aes_string(x="x", y="y", fill=basename)) + geom_raster() +
          theme_minimal() + theme(axis.text.x=element_blank(),
                                  axis.ticks.x=element_blank(),
                                  axis.title.x=element_blank(),
                                  legend.position="none",
                                  plot.margin=unit(c(0,0,0,0),"cm")
                                  )
          )
    dev.off()
}
## end function definitions

init.grid()
adios.init()

## specify and open file for reading
dir.data <- "/lustre/atlas/scratch/ost/stf006/heat"
file <- paste(dir.data, "heat.bp", sep="/")
file.ptr <- adios.open(file)

## select variable to read
variable <- "T"

## get variable dimensions
varinfo = adios.inq.var(file.ptr$pt, variable)
block <- adios.inq.var.blockinfo(file.ptr$pt, varinfo)
ndim <- custom.inq.var.ndim(varinfo)
dims <- custom.inq.var.dims(varinfo)

## get dimensions and split
source("/ccs/home/ost/adios/partition.r")
g.dim <- dims
split <- c(TRUE, FALSE)
my.data.partition <- data.partition(seq(0, 0, along.with=g.dim), g.dim, split)
my.dim <- my.count <- my.data.partition$my.dim
my.start <- my.data.partition$my.start
my.grid <- my.data.partition$my.grid

## partition across first dimension (expects at least 2d)
slice_size0 <- as.integer(dims[1] %/% comm.size())
slice_size <- slice_size0
if(comm.rank() == (comm.size() - 1))
    slice_size <- as.integer(slice_size + (dims[1] %% comm.size()))
start <- c(as.integer(comm.rank() * slice_size0), rep(0, ndim - 1))
count <- c(slice_size, as.integer(dims[2:ndim]))

errno <- 0 # Default value 0
steps <- 0
retval <- 0
bufsize <- 10
buffer <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a0 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a1 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a2 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
rhs <- cbind(rep(1, bufsize), poly(1:bufsize, degree=2))

while(errno != -21) { ## This is hard-coded for now. -21=err_end_of_stream
    steps = steps + 1 ## Double check with Norbert. Should it start with 1 or 2

    ## set reading bounding box
    adios.selection  <- adios.selection.boundingbox(ndim, my.start, my.count)
    comm.print("Selection.boundingbox complete ...")
    
    ## schedule the read
    adios.data <- adios.schedule.read(varinfo, my.start, my.count, file.ptr$pt,
                                      adios.selection, variable, 0, 1)
    comm.print("Schedule read complete ...")
    
    ## perform the read
    adios.perform.reads(file.ptr$pt, 1)
    comm.print("Perform read complete ...")

    data_chunk <- custom.data.access(adios.data, adios.selection, varinfo)
    comm.print("Data access complete ...")

    ## print a few to verify
    comm.cat("first 5:", head(data_chunk, 5),"\n")
    comm.cat("last 5:", tail(data_chunk, 5),"\n")

    ## shape into matrix with first dim as rows
    ## local reshape dimensions
    my.ncol <- prod(my.dim[2])
    my.nrow <- my.dim[1]
    ldim <- c(my.nrow, my.ncol)

    ## global reshape dimensions
    g.ncol <- prod(g.dim[2])
    g.nrow <- g.dim[1]
    gdim <- c(g.nrow, g.ncol)
    
    ## now glue into a ddmatrix
    ##  x <- matrix(data_chunk, nrow=my.nrow, ncol=my.ncol, byrow=FALSE)
    ##  X <- new("ddmatrix", Data=x, dim=gdim, ldim=ldim, bldim=ldim, ICTXT=2)

    ## Fit a quadratic to a moving window of 10 steps
    ## Actually don't need the ddmatrix for this and can go straight
    ## from data_chunk into buffer matrix
    buffer <- rbind(buffer[-1, ], data_chunk)

    ## plot the original local matrix (swapping row to col - C to R)
    raster_plot(data_chunk, my.ncol, my.nrow, "T", steps)
    
    if(steps >= bufsize)
        {
            fit <- lm.fit(rhs, buffer)$coefficients
            raster_plot(fit[1, ], my.ncol, my.nrow, "a0", steps)
            raster_plot(fit[2, ], my.ncol, my.nrow, "a1", steps)
            raster_plot(fit[3, ], my.ncol, my.nrow, "a2", steps)
        }
    
    ## All these work fine!
    ##    X <- as.blockcyclic(X, bldim=c(4, 4))
    ##    X.pc <- prcomp(X)
    ##    comm.print(X.pc)
    
    s <- sum(data_chunk)
    n <- length(data_chunk)
    sa <- allreduce(s)
    na <- allreduce(n)
    comm.cat(comm.rank(), "mean =", sa/na, "lmean =", s/n, "ln =", n, "\n",
             quiet=TRUE, all.rank=TRUE)

    ##
    ## Here, write out the results of the analysis
    ## For testing purposes, write the data.chunk back.
    ##
    
    ## try to get more data
    adios.advance.step(file.ptr$pt, 0, adios.timeout.sec=1)
    comm.print(paste("Done advance.step", steps, "..."))
     
    ## check errors
    errno <- adios.errno()
    comm.cat("Error Num",errno, "\n")

    ## if error is timeout (or EOF)
    if(errno == -22){ #-22 = err_step_notready
        comm.cat(comm.rank(), "Timeout waiting for more data. Quitting ...\n")
        break
    }
if(steps > 20) break
} # While end 

comm.print("Broke out of loop ...")
adios.read.close(file.ptr$pt)
comm.print("File closed")
adios.read.finalize.method("ADIOS_READ_METHOD_BP")
comm.print("Finalized adios ...")
finalize() # pbdMPI finalize

Kernel <- setRefClass("Kernel",
                fields = c("connection_info", "zmqctx", "sockets", "executor"),
                methods= list(

hb_reply = function() {
    data <- receive.socket(sockets$hb, unserialize = FALSE)
    send.socket(sockets$hb, data, serialize = FALSE)
},

#'<brief desc>
#'
#'<full description>
#' @param msg_lst <what param does>
#' @export
sign_msg = function(msg_lst) {
    concat <- unlist(msg_lst)
    return(hmac(connection_info$key, concat, "sha256"))
},
#'<brief desc>
#'
#'<full description>
#' @param parts <what param does>
#' @import rjson
#' @export
wire_to_msg = function(parts) {
    i <- 1
    #print(parts)
    while (any(parts[[i]] != charToRaw("<IDS|MSG>"))) {
        i <- i + 1
    }
    signature <- rawToChar(parts[[i + 1]])
    expected_signature <- sign_msg(parts[(i + 2):(i + 5)])
    stopifnot(identical(signature, expected_signature))
    header <- fromJSON(rawToChar(parts[[i + 2]]))
    parent_header <- fromJSON(rawToChar(parts[[i + 3]]))
    metadata <- fromJSON(rawToChar(parts[[i + 4]]))
    content <- fromJSON(rawToChar(parts[[i + 5]]))
    if (i > 1) {
        identities <- parts[1:(i - 1)]
    } else {
        identities <- NULL
    }
    return(list(header = header, parent_header = parent_header, metadata = metadata, 
        content = content, identities = identities))
},
#'<brief desc>
#'
#'<full description>
#' @param msg <what param does>
#' @export
msg_to_wire = function(msg) {
    #print(msg)
    bodyparts <- list(charToRaw(toJSON(msg$header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$parent_header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$metadata, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$content, auto_unbox=TRUE))
                     )
    signature <- sign_msg(bodyparts)
    return(c(msg$identities, list(charToRaw("<IDS|MSG>")), list(charToRaw(signature)), bodyparts))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @export
new_reply = function(msg_type, parent_msg) {
    header <- list(msg_id = UUIDgenerate(), username = parent_msg$header$username, 
        session = parent_msg$header$session, msg_type = msg_type)
    return(list(header = header, parent_header = parent_msg$header, identities = parent_msg$identities, 
        metadata = namedlist()  # Ensure this is {} in JSON, not []
        ))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @param  socket <what param does>
#' @param  content <what param does>
#' @export
send_response = function(msg_type, parent_msg, socket_name, content) {
    msg <- new_reply(msg_type, parent_msg)
    msg$content <- content
    socket <- sockets[socket_name][[1]]
    send.multipart(socket, msg_to_wire(msg))
},
#'<brief desc>
#'
#'<full description>
#' @param  <what param does>
#' @export
handle_shell = function() {
    parts <- receive.multipart(sockets$shell)
    msg <- wire_to_msg(parts)
    if (msg$header$msg_type == "execute_request") {
        executor$execute(msg)
    } else if (msg$header$msg_type == "kernel_info_request") {
        kernel_info(msg)
    } else if (msg$header$msg_type == "history_request") {
        history(msg)
    } else {
        print(c("Got unhandled msg_type:", msg$header$msg_type))
    }
},

history = function(request) {
  send_response("history_reply", request, 'shell', list(history=list()))
},

kernel_info = function(request) {
  send_response("kernel_info_reply", request, 'shell',
                list(protocol_version=c(4, 0), language="R",
                     language_info=list(name="R", codemirror_mode="r",
                                pygments_lexer="r", mimetype="text/x-r-source",
                                file_extension=".r"
                                )
                    )
                )
},

handle_control = function() {
  parts = receive.multipart(sockets$control)
  msg = wire_to_msg(parts)
  if (msg$header$msg_type == "shutdown_request") {
    shutdown(msg)
  } else {
    print(c("Unhandled control message, msg_type:", msg$header$msg_type))
  }
},

shutdown = function(request) {
  send_response('shutdown_reply', request, 'control',
                list(restart=request$content$restart))
  stop("Shut down by frontend.")
},

initialize = function(connection_file) {
    connection_info <<- fromJSON(connection_file)
    print(connection_info)
    url <- paste(connection_info$transport, "://", connection_info$ip, sep = "")
    url_with_port <- function(port_name) {
        return(paste(url, ":", connection_info[port_name], sep = ""))
    }

    # ZMQ Socket setup
    zmqctx <<- init.context()
    sockets <<- list(
        hb = init.socket(zmqctx, "ZMQ_REP"),
        iopub = init.socket(zmqctx, "ZMQ_PUB"),
        control = init.socket(zmqctx, "ZMQ_ROUTER"),
        stdin = init.socket(zmqctx, "ZMQ_ROUTER"),
        shell = init.socket(zmqctx, "ZMQ_ROUTER")
    )
    bind.socket(sockets$hb, url_with_port("hb_port"))
    bind.socket(sockets$iopub, url_with_port("iopub_port"))
    bind.socket(sockets$control, url_with_port("control_port"))
    bind.socket(sockets$stdin, url_with_port("stdin_port"))
    bind.socket(sockets$shell, url_with_port("shell_port"))

    executor <<- Executor$new(kernel=.self)
},

run = function() {
    while (1) {
        events <- poll.socket(list(sockets$hb, sockets$shell, sockets$control),
                              list("read", "read", "read"), timeout = -1L)
        if (events[[1]]$read) {
            # heartbeat
            hb_reply()
        }
        if (events[[2]]$read) {
            # Shell socket
            handle_shell()
        }

        if (events[[3]]$read) {  # Control socket
            handle_control()
        }
    }
})
)

#'Initialise and run the kernel
#'
#'@param connection_file The path to the IPython connection file, written by the frontend
#'@export 
main <- function(connection_file="") {
    if (connection_file == "") {
        # On Windows, passing the connection file in as a string literal fails,
        # because the \U in C:\Users looks like a unicode escape. So, we have to
        # pass it as a separate command line argument.
        connection_file = commandArgs(T)[1]
    }
    kernel <- Kernel$new(connection_file=connection_file)
    kernel$run()
}

#'Install the kernelspec to tell IPython (>= 3) about IRkernel
#'
#'@export
installspec <- function() {
    srcdir = system.file("kernelspec", package="IRkernel")
    cmd = paste("ipython kernelspec install --replace --name ir", srcdir, sep=" ")
    system(cmd, wait=TRUE)
}
mapBMatNames <- function(in.names, aa.names, model = "roc", as.delta.eta = T){
  ### Make a copy
  out.names <- in.names

  ### Get number of coefs and their names.
  ncoef <- get.my.ncoef(model, assign.Env = FALSE)
  coefnames <- get.my.coefnames(model, assign.Env = FALSE, as.delta.eta)

  ### Get synonymous codons.
  if("Z" %in% aa.names){
    synonymous.codon <- .CF.GV$synonymous.codon.split
  } else{
    synonymous.codon <- .CF.GV$synonymous.codon
  }

  ### Drop the last reference codon.
  synonymous.codon <- lapply(synonymous.codon, function(x) x[-length(x)])

  if(model == "roc" || model == "nsef"){
    codon.count <- lapply(synonymous.codon, length)
    id.intercept <- grep("Intercept", in.names)
    id.slope <- 1:length(in.names)
    id.slope <- id.slope[-id.intercept]

    start <- 1
    for(aa in aa.names){
      ncodons <- codon.count[[aa]] * ncoef
      if(ncodons == 0) next # for M and W
      aa.codon.names <- paste(aa, synonymous.codon[[aa]], sep = ".")
      out.names[start:(start+ncodons-1)] <- rep(aa.codon.names, ncoef)
      start <- start + ncodons
    }

    ### Paste by amino acids, synonymous codons, and coefficient names.
    out.names[id.intercept] <- paste(out.names[id.intercept],
                                     coefnames[1], sep = ".")
    out.names[id.slope] <- paste(out.names[id.slope],
                                 coefnames[2], sep = ".")
  }

  ### Return.
  return(out.names)
} # End of mapBMatNames().
# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>%
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
REBOL [
	Title:   "Red source files preprocessor"
	Author:  "Nenad Rakocevic"
	File: 	 %includes.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2013 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

change-dir %..
do %system/utils/encap-fs.r

write %build/bin/sources.r set-cache [
	%version.r
	%usage.txt
	%boot.red
	%compiler.r
	%lexer.r
	%environment/ [
		%actions.red
		%datatypes.red
		%functions.red
		%lexer.red
		%natives.red
		%operators.red
		%routines.red
		%scalars.red
		%system.red
		%console/ [
			%console.red
			%help.red
			%input.red
		]
	]
	%runtime/ [
		%actions.reds
		%allocator.reds
		%debug-tools.reds
		%interpreter.reds
		%macros.reds
		%natives.reds
		%parse.reds
		%random.reds
		%red.reds
		%stack.reds
		%stack.reds
		%tools.reds
		%unicode.reds
		%simple-io.reds
		%datatypes/ [
			%action.reds
			%block.reds
			%bitset.reds
			%char.reds
			%common.reds
			%context.reds
			%datatype.reds
			%file.reds
			%float.reds
			%function.reds
			%get-path.reds
			%get-word.reds
			%integer.reds
			%issue.reds
			%lit-path.reds
			%lit-word.reds
			%logic.reds
			%native.reds
			%none.reds
			%op.reds
			%object.reds
			%paren.reds
			%path.reds
			%point.reds
			%refinement.reds
			%routine.reds
			%set-path.reds
			%set-word.reds
			%string.reds
			%structures.reds
			%symbol.reds
			%unset.reds
			%url.reds
			%word.reds
		]
		%platform/ [
			%android.reds
			%darwin.reds
			%linux.reds
			%POSIX.reds
			%syllable.reds
			%win32.reds
		]
	]
	%utils/ [
		%extractor.r
	]
	%system/ [
		%compiler.r
		%config.r
		%emitter.r
		%linker.r
		%loader.r
		%runtime/ [
			%android.reds
			%common.reds
			%darwin.reds
			%debug.reds
			%freebsd.reds
			%libc.reds
			%lib-names.reds
			%lib-natives.reds
			%linux.reds
			%linux-sigaction.reds
			%POSIX.reds
			%POSIX-signals.reds
			%start.reds
			%syllable.reds
			%system.reds
			%utils.reds
			%win32.reds
			%win32-driver.reds
		]
		%formats/ [
			%ELF.r
			%Mach-O.r
			%PE.r
		]
		%targets/ [
			%ARM.r
			%IA-32.r
			%target-class.r
		]
		%utils/ [
			%IEEE-754.r
			%int-to-bin.r
			%r2-forward.r
			%secure-clean-path.r
			%virtual-struct.r
			%profiler.r
		]
	]
]

change-dir %build/
MGRAST_preprocessing <<- function(
                                  data_in,     # name of the input file (tab delimited text with the raw counts) or R matrix
                                  data_type             ="file",  # c(file, r_matrix)
                                  output_object         ="default", # output R object (matrix)
                                  output_file           ="default", # output flat file                       
                                  removeSg              = TRUE, # boolean to remove singleton counts
                                  removeSg_valueMin     = 2, # lowest retained value (lower converted to 0)
                                  removeSg_rowMin       = 4, # lowest retained row sum (lower, row is removed)
                                  log_transform         = FALSE,
                                  norm_method           = "DESeq_blind", #c("standardize", "quantile", "DESeq_blind", "DESeq_per_condition", "DESeq_pooled", "DESeq_pooled_CR", "none"), # USE blind if not replicates -- use pooled to get DESeq default
                                  pseudo_count          = 1, # has to be integer for DESeq
                                  DESeq_metadata_table  = NA, # only used if method is other than "blind"
                                  DESeq_metadata_column = 1, # only used if method is other than "blind"
                                  DESeq_metadata_type   = "file",           # c( "file", "r_matrix" )
                                  #DESeq_method          = "blind",  # c( "pooled", "pooled-CR", "per-condition", "blind" ) # blind, treat everything as one group
                                  DESeq_sharingMode     = "maximum",  # c( "maximum", "fit-only", "gene-est-only" ) # maximum is the most conservative choice
                                  DESeq_fitType         = "local",          # c( "parametric", "local" )
                                  DESeq_image           = TRUE, # create dispersion vs mean plot indicate DESeq regression
                                  scale_0_to_1          = FALSE,
                                  produce_boxplots      = FALSE,
                                  boxplot_height_in     = "default", # 11,
                                  boxplot_width_in      = "default", #"8.5,
                                  boxplot_res_dpi       = 300,
                                  create_log            = TRUE,
                                  debug                 = FALSE                                  
                                  )

  {
    
    # check for necessary packages, install if they are not there
    #require(matR) || install.packages("matR", repo="http://mcs.anl.gov/~braithwaite/R", type="source")
    #chooseCRANmirror()
    setRepositories(ind=1:8)
    source("http://bioconductor.org/biocLite.R")
    #require(preprocessCore) || install.packages("preprocessCore")
    #require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance
    require(preprocessCore) || biocLite("preprocessCore")
    require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance
    # (DESeq): www.ncbi.nlm.nih.gov/pubmed/20979621
    library(preprocessCore)
    library(DESeq)
    ###### MAIN
    
    # get the name of the data object if an object is used -- use the filename if input is filename string
    if ( identical( data_type, "file") ){
      input_name <- data_in
    }else if( identical( data_type, "r_matrix") ){
      input_name <- deparse(substitute(data_in))
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }    

    # Generate names for the output file and object
    if ( identical( output_object, "default") ){
      output_object <- paste( input_name, ".", norm_method, ".PREPROCESSED" , sep="", collapse="")
    }
    if ( identical( output_file, "default") ){
      output_file <- paste( input_name, ".", norm_method, ".PREPROCESSED.txt" , sep="", collapse="")
    }

    # Input the data
    if ( identical( data_type, "file") ){
      input_data <- data.matrix(read.table(data_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote=""))
    }else if( identical( data_type, "r_matrix") ){
      input_data <- data.matrix(data_in)
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }
    
    # sort the data (COLUMNWISE) by id
    sample_names <- order(colnames(input_data))
    input_data <- input_data[,sample_names]
    
    # make a copy of the input data that is not processed
    input_data.og <- input_data
 
    # non optional, convert "na's" to 0
    input_data[is.na(input_data)] <- 0
    
    # remove singletons
    if(removeSg==TRUE){
      input_data <- remove.singletons(x=input_data, lim.entry=removeSg_valueMin, lim.row=removeSg_rowMin, debug=debug)
    }
    
    # log transform log(x+1)2
    if ( log_transform==TRUE ){
      input_data <- log_data(input_data)
    }

    regression_message <- "DESeq regression:      NA"
    # Normalize -- stadardize or quantile norm (depends on user selection)
    switch(
           norm_method,
           
           standardize={
             input_data <- standardize_data(input_data)
           },

           quantile={
             input_data <- quantile_norm_data(input_data)
           },

           DESeq_blind={
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="blind", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_per_condition={
             stop( cat("The DESeq_per_condition option does not work as it should. DESeq authors advise using the pooled method (DESeq_pooled here) instead.\n
You can accomplish a normalization equivalent to per-condition if you break your data into one matrix per-condition and use the pooled option.
Given that the method athors advise using the pooled methods anyways, I don't plan to fix this unless it is requested. For future reference, it
works up through estimateDispersions(), but fails on varianceStabilizingTransformation().  I can't find examples - and would not be able to debug
quickly"
                       ))
             #if( is.na(DESeq_metadata_table) ){ stop("To DESeq_norm_by_group you must specify a DESeq_metadata_table") }
             #regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             #regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             #input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
             #                              DESeq_metadata_table, DESeq_metadata_column, sample_names,
             #                              DESeq_method="per-condition", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)    
           },
           
           DESeq_pooled={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled you must specify a DESeq_metadata_table") }
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_pooled_CR={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled_CR you must specify a DESeq_metadata_table") }             
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled-CR", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)  
           },
             
           none={
             input_data <- input_data
           },
           {
             stop( paste( norm_method, " is not a valid option for method", sep="", collapse=""))
           }
           )
    
    # scale normalized data [max..min] to [0..1] over the entire dataset 
    if ( scale_0_to_1==TRUE ){
      input_data <- scale_data(input_data)
    }
    
    # create object, with specified name, that contains the preprocessed data
    do.call("<<-",list(output_object, input_data))
 
    # write flat file, with specified name, that contains the preprocessed data
    write.table(input_data, file=output_file, sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")
    
    # produce boxplots
    boxplot_message <- "output boxplot:        NA"
    if ( produce_boxplots==TRUE ) {
      boxplots_file <- paste(input_name, ".boxplots.png", "\n", sep="", collapse="")
      
      if( identical(boxplot_height_in, "default") ){ boxplot_height_in <- 11 }
      if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- round(ncol(input_data)/14) }

      png(
          filename = boxplots_file,
          height = boxplot_height_in,
          width = boxplot_width_in,
          res = boxplot_res_dpi,
          units = 'in'
          )
      plot.new()
      split.screen(c(2,1))
      screen(1)
      graphics::boxplot(input_data.og, main=(paste(input_name," RAW", sep="", collapse="")), las=2, cex.axis=0.5)
      screen(2)
      graphics::boxplot(input_data, main=(paste(input_name," PREPROCESSED (", norm_method, " norm)", sep="", collapse="")),las=2, cex.axis=0.5)
      dev.off()
      boxplot_message <- paste("output boxplot:       ", boxplots_file, "\n", sep="", collapse="")
    }


    # message to send to the user after completion, given names for object and flat file outputs
    #writeLines( paste("Data have been preprocessed. Proprocessed, see ", log_file, " for details", sep="", collapse=""))

    
    if ( create_log==TRUE ){
      # name log file
      log_file <- paste( output_file, ".log", sep="", collapse="")
      # write log
      writeLines(
                 paste(
                       "##############################################################\n",
                       "###################### INPUT PARAMETERS ######################\n",
                       "data_in:               ", data_in, "\n",
                       "data_type:             ", data_type, "\n",
                       "output_object:         ", output_object, "\n",
                       "output_file:           ", output_file, "\n",
                       "removeSg:              ", as.character(removeSg),
                       "removeSg_valueMin:     ", removeSg_valueMin, "\n",
                       "removeSg_rowMin:       ", removeSg_rowMin, "\n",
                       "log_transform          ", as.character(log_transform), "\n",
                       "norm_method:           ", norm_method, "\n",
                       "DESeq_metadata_table:  ", as.character(DESeq_metadata_table), "\n",
                       "DESeq_metadata_column: ", DESeq_metadata_column, "\n",
                       "DESeq_metadata_type:   ", DESeq_metadata_type, "\n",
                       #"DESeq_method:          ", DESeq_method, "\n",
                       "DESeq_sharingMode:     ", DESeq_sharingMode, "\n",
                       "DESeq_fitType:         ", DESeq_fitType, "\n",
                       "scale_0_to_1:          ", as.character(scale_0_to_1), "\n",
                       "produce_boxplots:      ", as.character(produce_boxplots), "\n",
                       "boxplot_height_in:     ", boxplot_height_in, "\n",
                       "boxplot_width_in:      ", boxplot_width_in, "\n",
                       "debug as.character:    ", as.character(debug), "\n",
                       "####################### OUTPUT SUMMARY #######################\n",
                       "output object:         ", output_object, "\n",
                       "otuput file:           ", output_file, "\n",
                       boxplot_message, "\n",
                       regression_message, "\n",
                       "##############################################################",
                       sep="", collapse=""
                       ),
                 con=log_file
                 )
    }


    
  }




######################################################################
######################################################################
### SUBS
######################################################################
######################################################################
    
######################################################################
### Load metadata (for groupings)    
######################################################################
load_metadata <- function(group_table, group_column, sample_names){
  metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                               read.table(
                                          file=group_table,row.names=1,header=TRUE,sep="\t",
                                          colClasses = "character", check.names=FALSE,
                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                          )
                               )
      
  #metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]
  group_names <- metadata_matrix[ order(sample_names), group_column,drop=FALSE ]
  return(group_names)
}
######################################################################

######################################################################
### Sub to remove singletons
######################################################################
remove.singletons <- function (x, lim.entry, lim.row, debug) {
  x <- as.matrix (x)
  x [is.na (x)] <- 0
  x [x < lim.entry] <- 0 # less than limit changed to 0
  #x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # THIS DOES NOT WORK - KEEPS ORIGINAL MATRIX
  x <- x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # row sum equal to or greater than limit is retained
  if (debug==TRUE){write.table(x, file="sg_removed.txt", sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")}
  x  
}
######################################################################

# theMatrixWithoutRow5 = theMatrix[-5,]
# t1 <- t1[-(4:6),-(7:9)]
# mm2 <- mm[mm[,1]!=2,] # delete row if first column is 2
# data[rowSums(is.na(data)) != ncol(data),] # remove rows with any NAs

######################################################################
### Sub to log transform (base two of x+1)
######################################################################
log_data <- function(x, pseudo_count){
  x <- log2(x + pseudo_count)
  x
}
######################################################################

######################################################################
### sub to perform quantile normalization
######################################################################
quantile_norm_data <- function (x, ...){
  data_names <- dimnames(x)
  x <- normalize.quantiles(x)
  dimnames(x) <- data_names
  x
}
######################################################################

######################################################################
### sub to perform standardization
######################################################################
standardize_data <- function (x, ...){
  mu <- matrix(apply(x, 2, mean), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  sigm <- apply(x, 2, sd)
  sigm <- matrix(ifelse(sigm == 0, 1, sigm), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  x <- (x - mu)/sigm
  x
}
######################################################################

######################################################################
### sub to perform DESeq normalization
######################################################################
DESeq_norm_data <- function (x, regression_filename, pseudo_count,
                             DESeq_metadata_table, DESeq_metadata_column, sample_names,
                             DESeq_method, DESeq_sharingMode, DESeq_fitType, DESeq_image, debug, ...){
  # much of the code in this function is adapted/borrowed from two sources
  # Orignal DESeq publication www.ncbi.nlm.nih.gov/pubmed/20979621
  #     also see vignette("DESeq")
  # and Paul J. McMurdie's example analysis in a later paper http://www.ncbi.nlm.nih.gov/pubmed/24699258
  #     with supporing material # http://joey711.github.io/waste-not-supplemental/simulation-cluster-accuracy/simulation-cluster-accuracy-server.html
  if(debug==TRUE)(print("made it here DESeq (1)"))

  # check that pseudo counts are integer - must for DESeq
  if ( all.equal(pseudo_count, as.integer(pseudo_count)) != TRUE ){
    stop(paste("DESeq requires an integer pseudo_count, (", pseudo_count, ") is not an integer" ))
  }

  
  # import metadata matrix (from object or file)
  #if(!is.na(DESeq_metadata_table)){
  #  my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
  #}

  # create metdata for the "blind" case -- all samples treated as if they are in the same group
  if( identical(DESeq_method,"blind") ){
    my_conditions <- as.factor(rep(1,ncol(x)))
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }else{
    my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
    metadata_factors <- as.factor(my_metadata)
    if(debug==TRUE){my_metadata.test<<-my_metadata}
    my_conditions <- metadata_factors
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }

  if(debug==TRUE)(print("made it here DESeq (2)"))
  
  # add pseudocount to prevent workflow from crashing on NaNs - DESeq will crash on non integer counts
  x = x + pseudo_count 
 
  # create dataset object
  if(debug==TRUE){my_conditions.test<<-my_conditions}
  my_dataset <- newCountDataSet( x, my_conditions )
  if(debug==TRUE){my_dataset.test1 <<- my_dataset}
  if(debug==TRUE)(print("made it here DESeq (3)"))
  
  # estimate the size factors
  my_dataset <- estimateSizeFactors(my_dataset)

  if(debug==TRUE)(print("made it here DESeq (4)"))
  if(debug==TRUE){my_dataset.test2 <<- my_dataset}
  
  # estimate dispersions
  # reproduce this: deseq_varstab(physeq, method = "blind", sharingMode = "maximum", fitType = "local")
  #      see https://stat.ethz.ch/pipermail/bioconductor/2012-April/044901.html
  # with DESeq code directly
  # my_dataset <- estimateDispersions(my_dataset, method = "blind", sharingMode = "maximum", fitType="local")
  # but this is what they did in the supplemental material for the DESeq paper (I think) -- and in figure 1 of McMurdie et al.
  #my_dataset <- estimateDispersions(my_dataset, method = "pooled", sharingMode = "fit-only", fitType="local") ### THIS WORKS
  # This is what they suggest in the DESeq vignette for multiple replicats

  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)

  # in the case of per-condition, creates an envrionment called fitInfo
  # ls(my_dataset.test4@fitInfo)

                                        #  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
  
  if(debug==TRUE){my_dataset.test3 <<- my_dataset}

  if(debug==TRUE)(print("made it here DESeq (5)"))
  
  # Determine which column(s) have the dispersion estimates
  dispcol = grep("disp\\_", colnames(fData(my_dataset)))

  # Enforce that there are no infinite values in the dispersion estimates
  #if (any(!is.finite(fData(my_dataset)[, dispcol]))) {
  #  fData(cds)[which(!is.finite(fData(my_dataset)[, dispcol])), dispcol] <- 0
  #}

  if(debug==TRUE)(print("made it here DESeq (6)"))
  
  # apply variance stabilization normalization
  #if ( identical(DESeq_method, "per-condition") ){

  # produce a plot of the regression
  if(DESeq_image==TRUE){
    png(
        filename = regression_filename,
        height = 8.5,
        width = 11,
        res = 300,
        units = 'in'
        )
        #plot.new()    
    plotDispEsts( my_dataset )
    dev.off()
  }

if(debug==TRUE)(print("made it here DESeq (7)"))
  

  
  my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  # ls(my_dataset.test4@fitInfo)
  # my_dataset.test4@fitInfo$Kirsten$fittedDispEsts

  if(debug==TRUE){my_dataset.test4 <<- my_dataset.normed}

  #}else{
   # my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  #}
    








  
  
  # return matrix of normed values
  x <- exprs(my_dataset.normed)
  x

}
######################################################################

######################################################################
### sub to scale dataset values from [min..max] to [0..1]
######################################################################
scale_data <- function(x){
  shift <- min(x, na.rm = TRUE)
  scale <- max(x, na.rm = TRUE) - shift
  if (scale != 0) x <- (x - shift)/scale
  x
}
######################################################################


MGRAST_preprocessing <<- function(
                                  data_in,     # name of the input file (tab delimited text with the raw counts) or R matrix
                                  data_type             ="file",  # c(file, r_matrix)
                                  output_object         ="default", # output R object (matrix)
                                  output_file           ="default", # output flat file                       
                                  removeSg              = TRUE, # boolean to remove singleton counts
                                  removeSg_valueMin     = 2, # lowest retained value (lower converted to 0)
                                  removeSg_rowMin       = 4, # lowest retained row sum (lower, row is removed)
                                  log_transform         = FALSE,
                                  norm_method           = "DESeq_blind", #c("standardize", "quantile", "DESeq_blind", "DESeq_per_condition", "DESeq_pooled", "DESeq_pooled_CR", "none"), # USE blind if not replicates -- use pooled to get DESeq default
                                  pseudo_count          = 1, # has to be integer for DESeq
                                  DESeq_metadata_table  = NA, # only used if method is other than "blind"
                                  DESeq_metadata_column = 1, # only used if method is other than "blind"
                                  DESeq_metadata_type   = "file",           # c( "file", "r_matrix" )
                                  #DESeq_method          = "blind",  # c( "pooled", "pooled-CR", "per-condition", "blind" ) # blind, treat everything as one group
                                  DESeq_sharingMode     = "maximum",  # c( "maximum", "fit-only", "gene-est-only" ) # maximum is the most conservative choice
                                  DESeq_fitType         = "local",          # c( "parametric", "local" )
                                  DESeq_image           = TRUE, # create dispersion vs mean plot indicate DESeq regression
                                  scale_0_to_1          = FALSE,
                                  produce_boxplots      = FALSE,
                                  boxplot_height_in     = "default", # 11,
                                  boxplot_width_in      = "default", #"8.5,
                                  boxplot_res_dpi       = 300,
                                  create_log            = TRUE,
                                  debug                 = FALSE                                  
                                  )

  {
    
    # check for necessary packages, install if they are not there
    #require(matR) || install.packages("matR", repo="http://mcs.anl.gov/~braithwaite/R", type="source")
    #chooseCRANmirror()
    #setRepositories(ind=1:2)
    source("http://bioconductor.org/biocLite.R")
    require(preprocessCore) || install.packages("preprocessCore")
    #source("http://bioconductor.org/biocLite.R")
    #require(DESeq) || biocLite("DESeq")
    
    require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance 

                                        # (DESeq): www.ncbi.nlm.nih.gov/pubmed/20979621

    #library(preprocessCore)
    #library(DESeq)
    ###### MAIN
    
    # get the name of the data object if an object is used -- use the filename if input is filename string
    if ( identical( data_type, "file") ){
      input_name <- data_in
    }else if( identical( data_type, "r_matrix") ){
      input_name <- deparse(substitute(data_in))
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }    

    # Generate names for the output file and object
    if ( identical( output_object, "default") ){
      output_object <- paste( input_name, ".", norm_method, ".PREPROCESSED" , sep="", collapse="")
    }
    if ( identical( output_file, "default") ){
      output_file <- paste( input_name, ".", norm_method, ".PREPROCESSED.txt" , sep="", collapse="")
    }

    # Input the data
    if ( identical( data_type, "file") ){
      input_data <- data.matrix(read.table(data_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote=""))
    }else if( identical( data_type, "r_matrix") ){
      input_data <- data.matrix(data_in)
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }
    
    # sort the data (COLUMNWISE) by id
    sample_names <- order(colnames(input_data))
    input_data <- input_data[,sample_names]
    
    # make a copy of the input data that is not processed
    input_data.og <- input_data
 
    # non optional, convert "na's" to 0
    input_data[is.na(input_data)] <- 0
    
    # remove singletons
    if(removeSg==TRUE){
      input_data <- remove.singletons(x=input_data, lim.entry=removeSg_valueMin, lim.row=removeSg_rowMin, debug=debug)
    }
    
    # log transform log(x+1)2
    if ( log_transform==TRUE ){
      input_data <- log_data(input_data)
    }

    regression_message <- "DESeq regression:      NA"
    # Normalize -- stadardize or quantile norm (depends on user selection)
    switch(
           norm_method,
           
           standardize={
             input_data <- standardize_data(input_data)
           },

           quantile={
             input_data <- quantile_norm_data(input_data)
           },

           DESeq_blind={
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="blind", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_per_condition={
             stop( cat("The DESeq_per_condition option does not work as it should. DESeq authors advise using the pooled method (DESeq_pooled here) instead.\n
You can accomplish a normalization equivalent to per-condition if you break your data into one matrix per-condition and use the pooled option.
Given that the method athors advise using the pooled methods anyways, I don't plan to fix this unless it is requested. For future reference, it
works up through estimateDispersions(), but fails on varianceStabilizingTransformation().  I can't find examples - and would not be able to debug
quickly"
                       ))
             #if( is.na(DESeq_metadata_table) ){ stop("To DESeq_norm_by_group you must specify a DESeq_metadata_table") }
             #regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             #regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             #input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
             #                              DESeq_metadata_table, DESeq_metadata_column, sample_names,
             #                              DESeq_method="per-condition", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)    
           },
           
           DESeq_pooled={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled you must specify a DESeq_metadata_table") }
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_pooled_CR={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled_CR you must specify a DESeq_metadata_table") }             
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled-CR", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)  
           },
             
           none={
             input_data <- input_data
           },
           {
             stop( paste( norm_method, " is not a valid option for method", sep="", collapse=""))
           }
           )
    
    # scale normalized data [max..min] to [0..1] over the entire dataset 
    if ( scale_0_to_1==TRUE ){
      input_data <- scale_data(input_data)
    }
    
    # create object, with specified name, that contains the preprocessed data
    do.call("<<-",list(output_object, input_data))
 
    # write flat file, with specified name, that contains the preprocessed data
    write.table(input_data, file=output_file, sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")
    
    # produce boxplots
    boxplot_message <- "output boxplot:        NA"
    if ( produce_boxplots==TRUE ) {
      boxplots_file <- paste(input_name, ".boxplots.png", "\n", sep="", collapse="")
      
      if( identical(boxplot_height_in, "default") ){ boxplot_height_in <- 11 }
      if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- round(ncol(input_data)/14) }

      png(
          filename = boxplots_file,
          height = boxplot_height_in,
          width = boxplot_width_in,
          res = boxplot_res_dpi,
          units = 'in'
          )
      plot.new()
      split.screen(c(2,1))
      screen(1)
      graphics::boxplot(input_data.og, main=(paste(input_name," RAW", sep="", collapse="")), las=2, cex.axis=0.5)
      screen(2)
      graphics::boxplot(input_data, main=(paste(input_name," PREPROCESSED (", norm_method, " norm)", sep="", collapse="")),las=2, cex.axis=0.5)
      dev.off()
      boxplot_message <- paste("output boxplot:       ", boxplots_file, "\n", sep="", collapse="")
    }


    # message to send to the user after completion, given names for object and flat file outputs
    #writeLines( paste("Data have been preprocessed. Proprocessed, see ", log_file, " for details", sep="", collapse=""))

    
    if ( create_log==TRUE ){
      # name log file
      log_file <- paste( output_file, ".log", sep="", collapse="")
      # write log
      writeLines(
                 paste(
                       "##############################################################\n",
                       "###################### INPUT PARAMETERS ######################\n",
                       "data_in:               ", data_in, "\n",
                       "data_type:             ", data_type, "\n",
                       "output_object:         ", output_object, "\n",
                       "output_file:           ", output_file, "\n",
                       "removeSg:              ", as.character(removeSg),
                       "removeSg_valueMin:     ", removeSg_valueMin, "\n",
                       "removeSg_rowMin:       ", removeSg_rowMin, "\n",
                       "log_transform          ", as.character(log_transform), "\n",
                       "norm_method:           ", norm_method, "\n",
                       "DESeq_metadata_table:  ", as.character(DESeq_metadata_table), "\n",
                       "DESeq_metadata_column: ", DESeq_metadata_column, "\n",
                       "DESeq_metadata_type:   ", DESeq_metadata_type, "\n",
                       #"DESeq_method:          ", DESeq_method, "\n",
                       "DESeq_sharingMode:     ", DESeq_sharingMode, "\n",
                       "DESeq_fitType:         ", DESeq_fitType, "\n",
                       "scale_0_to_1:          ", as.character(scale_0_to_1), "\n",
                       "produce_boxplots:      ", as.character(produce_boxplots), "\n",
                       "boxplot_height_in:     ", boxplot_height_in, "\n",
                       "boxplot_width_in:      ", boxplot_width_in, "\n",
                       "debug as.character:    ", as.character(debug), "\n",
                       "####################### OUTPUT SUMMARY #######################\n",
                       "output object:         ", output_object, "\n",
                       "otuput file:           ", output_file, "\n",
                       boxplot_message, "\n",
                       regression_message, "\n",
                       "##############################################################",
                       sep="", collapse=""
                       ),
                 con=log_file
                 )
    }


    
  }




######################################################################
######################################################################
### SUBS
######################################################################
######################################################################
    
######################################################################
### Load metadata (for groupings)    
######################################################################
load_metadata <- function(group_table, group_column, sample_names){
  metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                               read.table(
                                          file=group_table,row.names=1,header=TRUE,sep="\t",
                                          colClasses = "character", check.names=FALSE,
                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                          )
                               )
      
  #metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]
  group_names <- metadata_matrix[ order(sample_names), group_column,drop=FALSE ]
  return(group_names)
}
######################################################################

######################################################################
### Sub to remove singletons
######################################################################
remove.singletons <- function (x, lim.entry, lim.row, debug) {
  x <- as.matrix (x)
  x [is.na (x)] <- 0
  x [x < lim.entry] <- 0 # less than limit changed to 0
  #x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # THIS DOES NOT WORK - KEEPS ORIGINAL MATRIX
  x <- x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # row sum equal to or greater than limit is retained
  if (debug==TRUE){write.table(x, file="sg_removed.txt", sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")}
  x  
}
######################################################################

# theMatrixWithoutRow5 = theMatrix[-5,]
# t1 <- t1[-(4:6),-(7:9)]
# mm2 <- mm[mm[,1]!=2,] # delete row if first column is 2
# data[rowSums(is.na(data)) != ncol(data),] # remove rows with any NAs

######################################################################
### Sub to log transform (base two of x+1)
######################################################################
log_data <- function(x, pseudo_count){
  x <- log2(x + pseudo_count)
  x
}
######################################################################

######################################################################
### sub to perform quantile normalization
######################################################################
quantile_norm_data <- function (x, ...){
  data_names <- dimnames(x)
  x <- normalize.quantiles(x)
  dimnames(x) <- data_names
  x
}
######################################################################

######################################################################
### sub to perform standardization
######################################################################
standardize_data <- function (x, ...){
  mu <- matrix(apply(x, 2, mean), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  sigm <- apply(x, 2, sd)
  sigm <- matrix(ifelse(sigm == 0, 1, sigm), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  x <- (x - mu)/sigm
  x
}
######################################################################

######################################################################
### sub to perform DESeq normalization
######################################################################
DESeq_norm_data <- function (x, regression_filename, pseudo_count,
                             DESeq_metadata_table, DESeq_metadata_column, sample_names,
                             DESeq_method, DESeq_sharingMode, DESeq_fitType, DESeq_image, debug, ...){
  # much of the code in this function is adapted/borrowed from two sources
  # Orignal DESeq publication www.ncbi.nlm.nih.gov/pubmed/20979621
  #     also see vignette("DESeq")
  # and Paul J. McMurdie's example analysis in a later paper http://www.ncbi.nlm.nih.gov/pubmed/24699258
  #     with supporing material # http://joey711.github.io/waste-not-supplemental/simulation-cluster-accuracy/simulation-cluster-accuracy-server.html
  if(debug==TRUE)(print("made it here DESeq (1)"))

  # check that pseudo counts are integer - must for DESeq
  if ( all.equal(pseudo_count, as.integer(pseudo_count)) != TRUE ){
    stop(paste("DESeq requires an integer pseudo_count, (", pseudo_count, ") is not an integer" ))
  }

  
  # import metadata matrix (from object or file)
  #if(!is.na(DESeq_metadata_table)){
  #  my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
  #}

  # create metdata for the "blind" case -- all samples treated as if they are in the same group
  if( identical(DESeq_method,"blind") ){
    my_conditions <- as.factor(rep(1,ncol(x)))
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }else{
    my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
    metadata_factors <- as.factor(my_metadata)
    if(debug==TRUE){my_metadata.test<<-my_metadata}
    my_conditions <- metadata_factors
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }

  if(debug==TRUE)(print("made it here DESeq (2)"))
  
  # add pseudocount to prevent workflow from crashing on NaNs - DESeq will crash on non integer counts
  x = x + pseudo_count 
 
  # create dataset object
  if(debug==TRUE){my_conditions.test<<-my_conditions}
  my_dataset <- newCountDataSet( x, my_conditions )
  if(debug==TRUE){my_dataset.test1 <<- my_dataset}
  if(debug==TRUE)(print("made it here DESeq (3)"))
  
  # estimate the size factors
  my_dataset <- estimateSizeFactors(my_dataset)

  if(debug==TRUE)(print("made it here DESeq (4)"))
  if(debug==TRUE){my_dataset.test2 <<- my_dataset}
  
  # estimate dispersions
  # reproduce this: deseq_varstab(physeq, method = "blind", sharingMode = "maximum", fitType = "local")
  #      see https://stat.ethz.ch/pipermail/bioconductor/2012-April/044901.html
  # with DESeq code directly
  # my_dataset <- estimateDispersions(my_dataset, method = "blind", sharingMode = "maximum", fitType="local")
  # but this is what they did in the supplemental material for the DESeq paper (I think) -- and in figure 1 of McMurdie et al.
  #my_dataset <- estimateDispersions(my_dataset, method = "pooled", sharingMode = "fit-only", fitType="local") ### THIS WORKS
  # This is what they suggest in the DESeq vignette for multiple replicats

  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)

  # in the case of per-condition, creates an envrionment called fitInfo
  # ls(my_dataset.test4@fitInfo)

                                        #  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
  
  if(debug==TRUE){my_dataset.test3 <<- my_dataset}

  if(debug==TRUE)(print("made it here DESeq (5)"))
  
  # Determine which column(s) have the dispersion estimates
  dispcol = grep("disp\\_", colnames(fData(my_dataset)))

  # Enforce that there are no infinite values in the dispersion estimates
  #if (any(!is.finite(fData(my_dataset)[, dispcol]))) {
  #  fData(cds)[which(!is.finite(fData(my_dataset)[, dispcol])), dispcol] <- 0
  #}

  if(debug==TRUE)(print("made it here DESeq (6)"))
  
  # apply variance stabilization normalization
  #if ( identical(DESeq_method, "per-condition") ){

  # produce a plot of the regression
  if(DESeq_image==TRUE){
    png(
        filename = regression_filename,
        height = 8.5,
        width = 11,
        res = 300,
        units = 'in'
        )
        #plot.new()    
    plotDispEsts( my_dataset )
    dev.off()
  }

if(debug==TRUE)(print("made it here DESeq (7)"))
  

  
  my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  # ls(my_dataset.test4@fitInfo)
  # my_dataset.test4@fitInfo$Kirsten$fittedDispEsts

  if(debug==TRUE){my_dataset.test4 <<- my_dataset.normed}

  #}else{
   # my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  #}
    








  
  
  # return matrix of normed values
  x <- exprs(my_dataset.normed)
  x

}
######################################################################

######################################################################
### sub to scale dataset values from [min..max] to [0..1]
######################################################################
scale_data <- function(x){
  shift <- min(x, na.rm = TRUE)
  scale <- max(x, na.rm = TRUE) - shift
  if (scale != 0) x <- (x - shift)/scale
  x
}
######################################################################


#' Load a bunch of dependencies by filename
#'
#' @name load_dependency
#' @param dep Name of dependency, e.g., relative filename (without .r)
#' @examples
#' \dontrun{
#'   helper <- load_dependency('path/to/helper')
#' }
load_dependency <- function(dep) {
  path <- suppressWarnings(base::normalizePath(file.path(current_directory(), dep)))
  if (!file.exists(path)) {
    new_path <- paste(path, '.r', sep = '')
    if (!file.exists(new_path)) new_path <- paste(path, '.R', sep = '')
    path <- new_path
  }
  if (!file.exists(path))
    stop(paste("Unable to load dependency '", dep, "'", sep = ''))
  fileinfo <- file.info(path)
  mtime <- fileinfo$mtime

  value <- NULL
  
  if (path %in% get_src_cache_names() &&
      mtime == (cache_hit = get_src_cache(path))$mtime)
    value <- cache_hit$value
  else {
    # We fetch "source" from the global environment to allow other packages
    # to inject around sourcing files and be compatible with Ramd.
    value <- base::source(path, local = new.env(parent = parent.env(topenv())))$value
    set_src_cache(list(value = value, mtime = mtime), path)
  }
  invisible(value)
}
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="thresher")
rs <- dbSendQuery(con, 'select T.id as tua_id, T.offsets as tua_offsets, A.text as article_text, A.city_published as city, A.state_published as state, A.date_published as date, A.article_id, A.periodical_code, A.annotators as annotators, TT.name as tua_type from thresher_tua T, thresher_article A, thresher_analysistype TT where T.article_id = A.article_id and T.analysis_type_id = TT.id;')
data <- fetch(rs, n=-1)
write.csv(data, file = "tua_data.csv", fileEncoding = "UTF-8")

# The above creates a file "tua_data.csv" with the data dump.
# It can be loaded back in with:
# data <- read.csv("tua_data.csv", header = TRUE, colClasses = c('character', 'integer', 'character', 'character', 'character', 'character', 'Date', 'integer', 'integer', 'character', 'character'))#Topic Model script
#Much of this initial workflow is from Jockers Text Analysis for R 
#and Shawn Graham's Ferguson Grand Jury corpus topic model at https://github.com/shawngraham/ferguson
library(mallet)
library(wordcloud)
library(dplyr)
library(tm)
library(Hmisc)

# import the OCR'd ICC decisions from the text folder
# each decision is here its own text file
#decisions <- mallet.read.dir("text") 

#Better is to use load.r file to provide cleaner texts via get_real_words function, etc

mallet.instances <- mallet.import(decisions$id, decisions$text, "icc.txt", token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")

#' create topic trainer object
n.topics <- 100
topic.model <- MalletLDA(n.topics)

#' load documents
topic.model$loadDocuments(mallet.instances)

## Get the vocabulary, and some statistics about word frequencies.
## These may be useful in further curating the stopword list.
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
#Get additional words for stoplist
#stopwords<- arrange(word.freqs, words, term.freq)
#rank(stopwords)



## Optimize hyperparameters every 20 iterations,
## after 50 burn-in iterations.
topic.model$setAlphaOptimization(20, 50)

## Now train a model. Note that hyperparameter optimization is on, by default.
## We can specify the number of iterations. Here we'll use a large-ish round number.
topic.model$train(400)

## NEW: run through a few iterations where we pick the best topic for each token,
## rather than sampling from the posterior distribution.
topic.model$maximize(40)

#' Get the probability of topics in documents and the probability of words in topics.
#' By default, these functions return raw word counts. Here we want probabilities,
#' so we normalize, and add "smoothing" so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=T, normalized=T)
topic.words <- mallet.topic.words(topic.model, smoothed=T, normalized=T)  ##adap jockers wordcloud script to use this variable

#' from http://www.cs.princeton.edu/~mimno/R/clustertrees.R
#' transpose and normalize the doc topics
topic.docs <- t(doc.topics)
topic.docs <- topic.docs / rowSums(topic.docs)

#Get shorter versions of the topics
topics.labels <- rep("", n.topics)
for (topic in 1:n.topics) topics.labels[topic] <- paste(mallet.top.words(topic.model, topic.words[topic,], num.top.words=7)$words, collapse=" ")


#output some of the topic model raw data
write.csv(topic.docs, "out/icc-topic-docs.csv") 
write.csv(topics.labels, "out/icc-topic-labels.csv") 

# create data.frame with columns as ids and rows as topics
topic_docs <- data.frame(topic.docs)
plotdocs <- names(topic_docs) 
names(topic_docs) <- decisions$id

## cluster based on shared words
plot(hclust(dist(topic.words)), labels=topics.labels)

#' Calculate similarity matrix
#' Shows which documents are similar to each other
#' by their proportions of topics. Based on Matt Jockers' method

library(cluster)
topic_df_dist <- as.matrix(daisy(t(topic_docs), metric = "euclidean", stand = TRUE))
# Change row values to zero if less than row minimum plus row standard deviation
# keep only closely related documents and avoid a dense spagetti diagram
# that's difficult to interpret (hat-tip: http://stackoverflow.com/a/16047196/1036500)
topic_df_dist[ sweep(topic_df_dist, 1, (apply(topic_df_dist,1,min) + apply(topic_df_dist,1,sd) )) > 0 ] <- 0

#' Use kmeans to identify groups of similar authors

km <- kmeans(topic_df_dist, n.topics)
# get names for each cluster
allnames <- vector("list", length = n.topics)
for(i in 1:n.topics){
  allnames[[i]] <- names(km$cluster[km$cluster == i])
}

#Shawn Graham's topics as wordclouds with some of Jockers print to pdf code
pdf(file="icc-topics.pdf")
for(i in 1:40){
  topic.top.words <- mallet.top.words(topic.model,
                                      topic.words[i,], 15)
  print(wordcloud(topic.top.words$words,
                  topic.top.words$weights,
                  c(4,.8), rot.per=0,
                  random.order=F))
  
}
dev.off()

#create some plots of topics across the range of decisions
library(ggplot2)
library(tidyr)
pdf(file="icc-topics-across-docs.pdf")
cols <- 1:2502
doc_topics <- data.frame(doc.topics, row.names = decisions$id, stringsAsFactors = FALSE)
doc_topics$docs <- cols

topic.cols <- names(doc_topics)

for(i in 1:100){
print(ggplot(doc_topics) + geom_smooth(aes_string(x="docs", y=(topic.cols[i]))))

}  
dev.off()

ggplot(doc_topics, aes(x=docs, y=X30)) + geom_smooth(span = 20)
#load and parse html tables

#load libraries
library(stringr)
library(stringi)
library(XML)
library(dplyr)
library(magrittr)

#Loads all the html tables into one list
table_dir <- "table"
files <- dir(table_dir, "*.html")
tbls <- file.path(table_dir, files) %>%
  lapply(., htmlParse) %>%
  lapply(., readHTMLTable, head = FALSE, stringsAsFactors = FALSE, which = 1) 

all_tbls <- do.call(rbind, tbls)
#   lapply(., )

tbls %>%
  lapply(``[[`) %>%

#Currently This code isn't necessary #/
#According to Hadley Wickham, creating an empty dataset and populating it is drastically faster in R
"tbl.df <- data.frame((character(length = length(tbls))), stringsAsFactors = FALSE)

#iterate through the list of tables and parse the html structure
i <- 1
for(i in 1:length(tbls)){
  
  i.df <- readHTMLTable(tbls[i], head = FALSE, stringsAsFactors = FALSE)
  tbl.df <- cbind(tbl.df, i.df)

}

readHTMLTable(tbls[1])


stopwords <- unique(tbls)
"
#Parse a sample table, this is the path
doc <-"table/v02toc.html"

#Pull in html files
p <- htmlParse(doc)

 

#iccv02toc.df <- xmlToDataFrame(p, collectNames = FALSE, stringsAsFactors = FALSE, nodes= iccv02toc[4] )

iccv02toc <- readHTMLTable(p, header = FALSE, stringsAsFactors = FALSE)

#Turn the HtmlInternalDocument into a data.frame
iccv02toc.df <- as.data.frame(iccv02toc[4], stringsAsFactors = FALSE)

#Use dplyr to munge the data from 3 columns of information into several columns of information
#First is to move plaintiff tribe into a separate column.
#iccv02toc.df$table1.V2 <- str_replace_all(iccv02toc.df$table1.V2, "[\t]", "")

v02tocfinal.df <- 
  iccv02toc.df %>%
  mutate(tribe = str_match(table1.V2, "(.*?)\r\n")[,2]) %>%
  
  View()


v02tocfinal.df <- mutate(v02tocfinal.df, page1 = str_extract(v02tocfinal.df$table1.V3, ".*\r\n"))



str(iccv02toc)
write.csv(iccv02toc[4], file = "out/iccv02toc.csv")
#' @name tundra_container
#' @title tundra_container
#' @export
NULL

#' Tundra container class
#'
#' TODO: Formally define parameter spaces for models
#' 
#' @docType class
#' @name tundraContainer
#' @aliases NULL
#' @export
tundra_container <- setRefClass('tundraContainer',  #define reference classes to access by reference instead of by value
  fields = list(keyword = 'character',
                train_fn = 'function',
                predict_fn = 'function',
                munge_procedure = 'list',  # tundra contains munge_procedure so that it remembers the data-prep steps
                default_args = 'list',
                trained = 'logical',
                input = 'list',
                output = 'ANY',    # output stores the actual output of the train function (e.g. the model object)
                internal = 'list', # for storing info about the model
                hooks = 'list'),
  methods = list(
    initialize = function(keyword = character(0),
                          train_fn = identity, predict_fn = identity,
                          munge_procedure = list(),
                          default_args = list(),
                          internal = list()) {
      keyword <<- keyword
      train_fn <<- train_fn
      predict_fn <<- predict_fn
      munge_procedure <<- munge_procedure
      default_args <<- default_args
      internal <<- internal
      trained <<- FALSE
    },

    train = function(dataframe, train_args = list(), verbose = FALSE, munge = TRUE) {
      if (trained)
        stop("Tundra model '", keyword, "' has already been trained.")

      force(train_args); force(verbose); force(munge) 

      .run_hooks('train_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        triggers <- unlist(lapply(munge_procedure,
                              function(x) inherits(x, 'trigger')))
        
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe

        # Store trained munge_procedure
        munge_procedure <<- attr(dataframe, 'mungepieces')[!triggers]

        # reset mungepieces to NULL after training
        attr(dataframe, 'mungepieces') <- NULL
      }

      run_env <- new.env(parent = old_env <- environment(train_fn))
      on.exit(environment(train_fn) <<- old_env)
      input <<- append(train_args, default_args)
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(train_fn)
      environment(train_fn) <<- run_env
      if (debug_flag) debug(train_fn)

      .run_hooks('train_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <- train_fn(dataframe))           # Apply train function to dataframe

      input <<- run_env$input; output <<- run_env$output
      trained <<- TRUE
      res 
    },

    predict = function(dataframe, predict_args = list(), verbose = FALSE, munge = TRUE) {
      if (!trained)
        stop("Tundra model '", keyword, "' has not been trained yet.")

      force(verbose); force(munge); force(predict_args)

      .run_hooks('predict_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        initial_nrow <- nrow(dataframe)
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe
        if (nrow(dataframe) != initial_nrow)
          warning(paste("Some rows were removed during data preparation.",
                        "Predictions will not match input dataframe."))

      }

      run_env <- new.env(parent = globalenv())
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(predict_fn)
      environment(predict_fn) <<- run_env
      if (debug_flag) debug(predict_fn)

      .run_hooks('predict_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <-
          if (length(formals(predict_fn)) < 2 || missing(predict_args)) {
            predict_fn(dataframe)
          } else { predict_fn(dataframe, predict_args) }
      )
      input <<- run_env$input; output <<- run_env$output
      res
    },
    
    munge = function(dataframe, steps = TRUE) {
      mungebits::munge(dataframe, munge_procedure[steps]) 
    },

    show = function() {
      cat(paste("A tundraContainer of type", sQuote(keyword)), "\n")
    },

    add_hook = function(type, hook_function) {
      stopifnot(is.character(type) && length(type) == 1)
      stopifnot(is.function(hook_function))
      allowed_types <- paste0(as.character(outer(
        c('train', 'predict'), c('pre', 'post'), paste, sep = '_')), '_munge')
      if (!is.element(type, allowed_types)) {
        stop("Tundra container hooks must be one of: ",
             paste(allowed_types, collapse = ", "))
      }

      hooks[[type]] <<- c(hooks[[type]], hook_function)
    },

    .run_hooks = function(type) {
      if (!exists('hooks')) return() # Backwards compatibility
      for (i in seq_along(hooks[[type]])) {
        eval.parent(bquote({
          `*fn*` <- hooks[[.(type)]][[.(i)]]
          environment(`*fn*`) <- environment()
          `*fn*`()
        }))
      }
    }
  )
)

#' @export
summary.tundraContainer <- function(x, ...) summary(x$output$model, ...)
#' @export
print.tundraContainer <-
  function(x, ...) print(paste("A tundraContainer of type", sQuote(x$keyword)), ...)

library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # consider coords (r,c)
  table_start_r <- coords[1]
  table_start_c <- coords[2]
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  data_start_c <- table_start_c
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 
  
  # if caption, start the table one row lower
  if (add.caption) { data_start_r <- data_start_r + 2 } # optional whiteline => 1 ipv 2?
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "surrounding")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = table_start_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen rownames zijn?
    row_margin_c <- 1 + ncol(tabular) + 1
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen colnames zijn?
    col_margin_c <- start_c + 1
    col_margin_r <- 1 + nrow(tabular) + 1
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # consider coords (r,c)
  start_r <- coords[1]
  start_c <- coords[2]
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 
  
  # if caption, start the table one row lower
  if (add.caption) { start_r <- start_r + 1 }
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = start_c, startRow = start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "surrounding")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is one above start_r 
    comment_r <- start_r - 1
    writeData(
      wb = wb, sheet = sheet, startCol = start_c, startRow = comment_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    comment_merge_width <- ifelse(7 - start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = start_c:comment_merge_width, 
               rows = comment_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen rownames zijn?
    row_margin_c <- 1 + ncol(tabular) + 1
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen colnames zijn?
    col_margin_c <- start_c + 1
    col_margin_r <- 1 + nrow(tabular) + 1
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
source('table_export_openxlsx.r')


# BASIC EXAMPLES #
# ============== #

d <- as.data.frame(Titanic)
tab1 <- table(d$Class, d$Sex)
tab2 <- table(d$Class, d$Survived)
tab3 <- table(d$Sex, d$Survived)


# write single table
# ------------------

wb <- createWorkbook()
addWorksheet(wb = wb, sheetName = 'OR_tables')

wb <- print.tabular.xlsx(wb, 1, c(1,1), tab1)
openXL(wb)


# write multiple tables
# ---------------------

wb <- createWorkbook()
addWorksheet(wb = wb, sheetName = 'OR_tables')

wb <- print.tabulars.xlsx(wb, 1, list(tab1) )
#wb <- print.tabulars.xlsx(wb, 1, list(tab1, tab2, tab3) )
# Error in .self$updateCellStyles(sheet = r$sheet, rows = r$rows, cols = r$cols,  : 
#                                   CHAR() can only be applied to a 'CHARSXP', not a 'NULL'
openXL(wb)




# EXAMPLES: OR TABELLEN # 
# ===================== #

wd <- getwd()
setwd('C:/Users/MaartenH/Documents/work/HIVA/acv_or')
load('rapportering/descr_tables.RData')
setwd(wd)
rm(wd)


# General styling
# ---------------

# make custom table header style
hs1 <- createStyle(fgFill = "#DCE6F1", halign = "CENTER", 
                   textDecoration = "Italic", border = "Bottom")

# stel algemene stijlelementen in
options("openxlsx.borderColour" = "#4F80BD")
options("openxlsx.borderStyle" = "thin")


# Setup workbook, sheet
# ---------------------

wb <- createWorkbook()
addWorksheet(wb = wb, sheetName = 'OR_tables')
setColWidths(wb, sheet = 1, cols=1:30, widths = "auto") # set cols to automatically resize

# write multiple tables in single sheet
# -------------------------------------

# Table 1: cbind()'ed table

tab1 <- as.data.frame(t.wg.centrale) # omzetten naar dataframe
#class(tab1[,3] ) <- "percentage"

# Table 2: svytable()
tab2 <- as.data.frame.matrix(t.hhr.centrale)

tab3 <- t.invoed.tech

wb <- print.tabulars.xlsx(wb, 1, list(tab1, tab2, tab3))
openXL(wb) # toon excel bestand zonder weg te schrijven

saveWorkbook(wb, "OR1_descr_tables.xlsx", overwrite = TRUE)



# writeData(wb = wb, sheet = sheet_name, x = tab, xy=coords,
#           borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")
# writeData(wb = wb, 
#           sheet = sheet_name, x = tab, 
#           xy=coords,
#           borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")

library(openxlsx)

wd <- getwd()
setwd('C:/Users/MaartenH/Documents/work/HIVA/acv_or')
load('rapportering/descr_tables.RData')
setwd(wd)
rm(wd)

#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 


# General styling
# ---------------

# make custom table header style
hs1 <- createStyle(fgFill = "#DCE6F1", halign = "CENTER", 
                   textDecoration = "Italic", border = "Bottom")

# stel algemene stijlelementen in
options("openxlsx.borderColour" = "#4F80BD")
options("openxlsx.borderStyle" = "thin")


# Setup workbook, sheet
# ---------------------

wb <- createWorkbook()
sheet_name <- 'OR_tables'
addWorksheet(wb = wb, sheetName = sheet_name)
setColWidths(wb, sheet = 1, cols=1:100, widths = "auto") # set cols to automatically resize

# write multiple tables in single sheet
# -------------------------------------

# Table 1: cbind()'ed table

tab <- as.data.frame(t.wg.centrale) # omzetten naar dataframe
class(tab[,3] ) <- "percentage"
  
coords <- c(1,1)
writeData(wb = wb, sheet = sheet_name, x = tab, xy=coords,
          borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")

# Table 2: svytable()

tab <- as.data.frame.matrix(t.hhr.centrale)

coords <- c(1,nrow(tab) + 3) # hoogte tab 1 + 3 rows => 1 spatie
writeData(wb = wb, 
          sheet = sheet_name, x = tab, 
          xy=coords,
          borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")


openXL(wb) # toon excel bestand zonder weg te schrijven

saveWorkbook(wb, "OR1_descr_tables.xlsx", overwrite = TRUE)

# TODO wat is een header/footer?



# basis-elementen die rondom de data geplaatst worden
#
# * caption   	  # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.row.margin=FALSE, add.col.margin=FALSE, add.comment=FALSE, 
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # consider coords (r,c)
  start_r <- coords[1]
  start_c <- coords[2]
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 

  # if caption, start the table one row lower
  if (add.caption) { start_r <- start_r + 1 }
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = start_c, startRow = start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "surrounding")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is one above start_r 
    comment_r <- start_r - 1
    writeData(
      wb = wb, sheet = sheet, startCol = start_c, startRow = comment_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    comment_merge_width <- ifelse(7 - start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = start_c:comment_merge_width, 
               rows = comment_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  

  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
#   row.margin.name
#   col.margin.name
#   
#   margin.table(tab)
    
  # if comment, add additional row with comment
  # -------------------------------------------
  
    
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}

d <- as.data.frame(Titanic)
tab <- table(d$Class, d$Sex)
str(tab)

wb <- createWorkbook()
sheet_name <- 'OR_tables'
addWorksheet(wb = wb, sheetName = sheet_name)
#setColWidths(wb, sheet = 1, cols=1:100, widths = "auto") # set cols to automatically resize
setColWidths(wb, sheet = 1, cols=1:100, widths = "auto") # set cols to automatically resize
wb <- print.tabular.xlsx(wb, sheet='OR_tables', coords=c(1,1), tabular=t.wg.centrale, add.caption=TRUE)
wb <- print.tabular.xlsx(wb, 'OR_tables', c(1, nrow(t.wg.centrale)+4), t.hhr.centrale)

wb <- print.tabular.xlsx(wb, 'OR_tables', c(1, 1), tab)
openXL(wb)


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name
  
  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { start_r <- 1}
    else {start_r <- previous_r + 2}    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular)
    
  }
  
  wb
  
}


d <- as.data.frame(Titanic)
tab1 <- table(d$Class, d$Sex)
tab2 <- table(d$Class, d$Survived)
tab3 <- table(d$Sex, d$Survived)

wb <- createWorkbook()
sheet_name <- 'OR_tables'
addWorksheet(wb = wb, sheetName = sheet_name)

wb <- print.tabulars.xlsx(wb, 1, list(tab1, tab2, tab3) )
openXL(wb)
#' @name tundra_container
#' @title tundra_container
#' @export
NULL

#' Tundra container class
#'
#' TODO: Formally define parameter spaces for models
#' 
#' @docType class
#' @name tundraContainer
#' @aliases NULL
#' @export
tundra_container <- setRefClass('tundraContainer',  #define reference classes to access by reference instead of by value
  fields = list(keyword = 'character',
                train_fn = 'function',
                predict_fn = 'function',
                munge_procedure = 'list',  # tundra contains munge_procedure so that it remembers the data-prep steps
                default_args = 'list',
                trained = 'logical',
                input = 'list',
                output = 'ANY',    # output stores the actual output of the train function (e.g. the model object)
                internal = 'list', # for storing info about the model
                hooks = 'list'),
  methods = list(
    initialize = function(keyword = character(0),
                          train_fn = identity, predict_fn = identity,
                          munge_procedure = list(),
                          default_args = list(),
                          internal = list()) {
      keyword <<- keyword
      train_fn <<- train_fn
      predict_fn <<- predict_fn
      munge_procedure <<- munge_procedure
      default_args <<- default_args
      internal <<- internal
      trained <<- FALSE
    },

    train = function(dataframe, train_args = list(), verbose = FALSE, munge = TRUE) {
      if (trained)
        stop("Tundra model '", keyword, "' has already been trained.")

      force(train_args); force(verbose); force(munge) 

      .run_hooks('train_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        triggers <- unlist(lapply(munge_procedure,
                              function(x) inherits(x, 'trigger')))
        
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe

        # Store trained munge_procedure
        munge_procedure <<- attr(dataframe, 'mungepieces')[!triggers]

        # reset mungepieces to NULL after training
        attr(dataframe, 'mungepieces') <- NULL
      }

      run_env <- new.env(parent = old_env <- environment(train_fn))
      on.exit(environment(train_fn) <<- old_env)
      input <<- append(train_args, default_args)
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(train_fn)
      environment(train_fn) <<- run_env
      if (debug_flag) debug(train_fn)

      .run_hooks('train_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <- train_fn(dataframe))           # Apply train function to dataframe

      input <<- run_env$input; output <<- run_env$output
      trained <<- TRUE
      res 
    },

    predict = function(dataframe, predict_args = list(), verbose = FALSE, munge = TRUE) {
      if (!trained)
        stop("Tundra model '", keyword, "' has not been trained yet.")

      force(verbose); force(munge); force(predict_args)

      .run_hooks('predict_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        initial_nrow <- nrow(dataframe)
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe
        if (nrow(dataframe) != initial_nrow)
          warning(paste("Some rows were removed during data preparation.",
                        "Predictions will not match input dataframe."))

      }

      run_env <- new.env(parent = globalenv())
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(predict_fn)
      environment(predict_fn) <<- run_env
      if (debug_flag) debug(predict_fn)

      .run_hooks('predict_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <-
          if (length(formals(predict_fn)) < 2 || missing(predict_args)) {
            predict_fn(dataframe)
          } else { predict_fn(dataframe, predict_args) }
      )
      input <<- run_env$input; output <<- run_env$output
      res
    },
    
    munge = function(dataframe, steps = TRUE) {
      mungebits::munge(dataframe, munge_procedure[steps]) 
    },

    show = function() {
      cat(paste("A tundraContainer of type", sQuote(keyword)), "\n")
    },

    add_hook = function(type, hook_function) {
      stopifnot(is.character(type) && length(type) == 1)
      stopifnot(is.function(hook_function))
      allowed_types <- paste0(as.character(outer(
        c('train', 'predict'), c('pre', 'post'), paste, sep = '_')), '_munge')
      if (!is.element(type, allowed_types)) {
        stop("Tundra container hooks must be one of: ",
             paste(allowed_types, collapse = ", "))
      }

      hooks[[type]] <<- c(hooks[[type]], hook_function)
    },

    .run_hooks = function(type) {
      for (i in seq_along(hooks[[type]])) {
        eval.parent(bquote({
          `*fn*` <- hooks[[.(type)]][[.(i)]]
          environment(`*fn*`) <- environment()
          `*fn*`()
        }))
      }
    }
  )
)

#' @export
summary.tundraContainer <- function(x, ...) summary(x$output$model, ...)
#' @export
print.tundraContainer <-
  function(x, ...) print(paste("A tundraContainer of type", sQuote(x$keyword)), ...)

# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Enkrat prvak", "Dvakrat prvak", "Večkrat prvak")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
veckrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) > 2))
dvakrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) == 2))
enkrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) < 2))
stevilo.naslovov.dirkaca[veckrat.prvak] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[dvakrat.prvak] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[enkrat.prvak] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)




source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="thresher")
rs <- dbSendQuery(con, 'select T.id as tua_id, T.offsets as tua_offsets, A.text as article_text, A.city_published as city, A.state_published as state, A.date_published as date, A.article_id, A.periodical_code, A.annotators as annotators, TT.name as tua_type from thresher_tua T, thresher_article A, thresher_analysistype TT where T.article_id = A.article_id and T.analysis_type_id = TT.id;')
data <- fetch(rs, n=-1)
write.csv(data, file = "tua_data.csv", fileEncoding = "UTF-8")

# The above creates a file "tua_data.csv" with the data dump.
# It can be loaded back in with:
# data <- read.csv("tua_data.csv", header = TRUE, colClasses = c('character', 'integer', 'character', 'character', 'character', 'character', 'Date', 'integer', 'integer', 'character', 'character'))library(XML)

# Vrne vektor nizov z odstranjenimi začetnimi in končnimi "prazninami" (whitespace)
# iz vozlišč, ki ustrezajo podani poti.
stripByPath <- function(x, path) {
  unlist(xpathApply(x, path,
                    function(y) gsub("^\\s*(.*?)\\s*$", "\\1", xmlValue(y))))
}

uvoz.konstruktorske.zmage <- function() {
  url.konstruktorske.zmage <- "http://en.wikipedia.org/wiki/List_of_Formula_One_World_Drivers%27_Champions#By_constructor"
  doc.konstruktorske.zmage <- htmlTreeParse(url.konstruktorske.zmage,encoding = "UTF-8", useInternalNodes=TRUE)
  
  # Poiščemo vse tabele v dokumentu
  tabele <- getNodeSet(doc.konstruktorske.zmage, "//table")
  
  # Iz šeste tabele dobimo seznam vrstic (<tr>) neposredno pod
  # trenutnim vozliščem
  vrstice <- getNodeSet(tabele[[6]], "./tr")
  
  # Seznam vrstic pretvorimo v seznam (znakovnih) vektorjev
  # s porezanimi vsebinami celic (<td>) neposredno pod trenutnim vozliščem
  seznam <- lapply(vrstice[2:length(vrstice)], stripByPath, "./td")
  
  # Iz seznama vrstic naredimo matriko
  matrika <- matrix(unlist(seznam), nrow=length(seznam), byrow=TRUE)
  
  # Imena stolpcev matrike dobimo iz celic (<th>) glave (prve vrstice) prve tabele
  colnames(matrika) <- gsub("\n", " ", stripByPath(vrstice[[1]], ".//th"))
  
  # Podatke iz matrike spravimo v razpredelnico
  return(data.frame(Country = gsub("[^a-z ]", "", matrika[,2], ignore.case=TRUE),
                    Total = as.numeric(matrika[,3]), row.names = matrika[,1]))
}
# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Večkrat prvak", "Dva naslova prvaka", "En naslov prvaka")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
stevilo.naslovov.dirkaca[summary(svetovniprvaki$Driver) > 2] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[summary(svetovniprvaki$Driver) == 2] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[summary(svetovniprvaki$Driver) < 2] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)


source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()

# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
stevilo.zmag <- c("veliko zmag", "nekaj zmag", "ena zmaga")
zmage.ekip <- character(length(svetovniprvaki$Team))
zmage.ekip[summary(svetovniprvaki$Team) > 3] <- "veliko zmag"
zmage.ekip[summary(svetovniprvaki$Team) > 1 & summary(svetovniprvaki$Team) < 4] <- "nekaj zmag"
zmage.ekip[summary(svetovniprvaki$Team) < 2] <- "ena zmaga"
Zmage.ekip <- factor(svetovniprvaki$Team, levels = stevilo.zmag, ordered = TRUE)
Zmage.Ekip <- data.frame(svetovniprvaki$Season, svetovniprvaki$Driver, svetovniprvaki$Country,
                         svetovniprvaki$Team,svetovniprvaki$Base, svetovniprvaki$Engine, zmage.ekip)



source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()

# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
stevilo.zmag <- c("veliko zmag", "nekaj zmag", "ena zmaga")
zmage.ekip <- character(length(svetovniprvaki$Team))
zmage.ekip[summary(svetovniprvaki$Team) > 3] <- "veliko zmag"
zmage.ekip[summary(svetovniprvaki$Team) > 1 & summary(svetovniprvaki$Team) < 4] <- "nekaj zmag"
zmage.ekip[summary(svetovniprvaki$Team) < 2] <- "ena zmaga"
Zmage.ekip <- factor(svetovniprvaki$Team, levels = stevilo.zmag, ordered = TRUE)
Zmage.Ekip <- data.frame(svetovniprvaki$Season, svetovniprvaki$Driver, svetovniprvaki$Country,
                         svetovniprvaki$Team,svetovniprvaki$Base, svetovniprvaki$Engine, zmage.ekip)



# source("lib/xml.r", encoding="UTF-8")
# cat("Uvažam podatke o konstruktorskih zmagah.\n")
# konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if(debug==TRUE){print(paste("argument_test:", argument_test))}
  if(debug==TRUE){print(paste("length argument_test == TRUE:", length(argument_test==TRUE)))}
  
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files

    if(debug==TRUE){print("Rendering without metadata")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with amethst_groups")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with color_list")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      if(debug==TRUE){print("Rendering with metadata_matrix, all columns")}
      
      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE

      if(debug==TRUE){print("Rendering with metadata_matrix, single column")}

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if(debug==TRUE){print(paste("argument_test:", argument_test))}
  
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files

    if(debug==TRUE){print("Rendering without metadata")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with amethst_groups")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with color_list")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      if(debug==TRUE){print("Rendering with metadata_matrix, all columns")}
      
      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE

      if(debug==TRUE){print("Rendering with metadata_matrix, single column")}

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files

    if(debug==TRUE){print("Rendering without metadata")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with amethst_groups")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with color_list")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      if(debug==TRUE){print("Rendering with metadata_matrix, all columns")}
      
      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE

      if(debug==TRUE){print("Rendering with metadata_matrix, single column")}

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()




# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))
}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   File   : rbamtools.r
#   Date   : 12.Mar.2012
#   Sam    : Samtools downloaded September 7, 2011. Format: v1.4-r985
#   Content: R-Source for package rbamtools
#   Version: 2.9.8
#   Author : W. Kaisers
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  CRAN submission:
#  check R CMD check --as-cran
#  wput rbamtools_2.0.tar.gz ftp://cran.r-project.org/incoming/ 
#  Changelog
#  30.Okt.12  [initialize.gapList] Made printout message optional (verbose)
#  31.Okt.12  [bamRange] Included test for initialized index
#  31.Okt.12  Check for open reader in getHeader, getHeaderText, getRefCount
#  01.Nov.12  [get_const_next_align] added to correct memory leak.
#  08.Nov.12  Reading and writing big bamRanges (pure C, no R) valgrind
#                                                                checked.
#  09.Nov.12  [bamCopy.bamReader] Added which allows refwise copying.
#  31.Dec.12  gapSiteList class added
#  11.Jan.13  bamGapList class added
#  06.Feb.13  First successful test of bamGapList on 36 BAM-files 
#                                                       (871.926/sec)
#  20.Feb.13  Fixed Error in merge.bamGapList
#  27.Feb.13  Renamed createIndex -> create.index and loadIndex -> load.index
#             and bamSiteList -> bamGapList
#  18.Apr.13  Corrected some memory leaks in C-Code as reported by Brian Ripley
#  22.Apr.13  Added (read-) name and revstrand to as.data.frame.bamRange
#                                               (as proposed by Ander Muniategui)
#  11.Jun.13  Added reader2fastq and range2fastq functions
#                                               (2.5.3, valgrind tested)
#  11.Jun.13  Changed signature for bamSave: added refid argument
#               (needed to prevent samtools crashes when creating BAM files
#               with single align regions and appropriate refSeqDict entries)
#             (2.5.4, valgrind tested)
#  12.Jun.13  Added extractRanges function (2.5.5)
#  21.Jun.13  Added bamAlign function (2.5.6)
#  01.Jul.13  Added bamCount function (2.5.8)
#  02.Jul.13  Added bamCountAll function, valgrind tested (2.5.9)
#  18.Jul.13  Changed 'nGapAligns' to 'nAlignGaps (2.5.10)
#                                               nGapAligns deprecated!
#  24.JUl.13  Added alignQual function, valgrind tested (2.5.11)
#  28.Jul.13  Added alignDepth function, valgrind tested (2.5.12)
#  13.Aug.13  Added countTextLines function, valgrind tested (2.6.1)
#  26.Aug.13  Removed "coerce" from Namespace declaration
#  02.Sep.13  Changed "cat" to "message"
#  10.Jun.14  On CRAN after correction of "Mis-alignment errors"
#  19.Jun.14  Re-introduction of changes after resetting to 2.7.0
#                                                       due to internal errors.
#  21.Jul.14  Updated plotAlignDepth 
#  14.Jul.14  Added test directory
#  28.Jul.14  Added NEWS and ChangeLog file
#  29.Sep.14  Added support for DS segment in headerProgram (@PG)
#               Added support for Supplementary alignmnet FLAG
#               Corrected error in resetting FLAG values
#               Replaced rand() by runif() in ksort.h
#               Enclosed reader2fastq example in \dontrun{}
#  03.Nov.14  Changed nAligns data type to unsigned long long int
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

.onUnload <- function(libpath) { library.dynam.unload("rbamtools", libpath) }


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Declaration of classes
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  File interacting classes:
#  bamReader, bamWriter
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamReader", representation(
    filename="character", reader="externalptr", index="externalptr",
    startpos="numeric"),
    validity=function(object)
    {return(ifelse(is.null(object@reader), FALSE, TRUE))})


setClass("bamWriter",
            representation(filename="character", writer="externalptr"),
            validity=function(object)
            {
                return(ifelse(is.null(object@writer), FALSE, TRUE))
            })

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Header section related classes:
#  bamHeader, bamHeaderText,
#  headerLine,
#  
#  refSectDict, headerReadGroup,
#  headerProgram
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamHeader",
        representation(header="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@header), FALSE, TRUE))
})

setClass("headerLine",
    representation(VN="character", SO="character"),
    validity=function(object)
    {
        if( (length(VN) == 1) & (length(SO) == 1) )
            return(TRUE)
        else
            return(FALSE)
    })


setClass("refSeqDict",
    representation(SN="character", LN="numeric",   AS="character",
                   M5="numeric",   SP="character", UR="character"))

setClass("headerReadGroup", representation(
            nrg="integer",          #  Number of read groups
            ID="character",         #  Read group identifier
            CN="character",         #  Name of sequencing center
            DS="character",         #  Description
            DT="character",         #  Date
            FO="character",         #  Flow order
            KS="character",         #  Array of nucleotide bases
            LB="character",         #  Library
            PG="character",         #  Programes used for processing
            PI="character",         #  Predicted median insert size
            PL="character",         #  Platform (ILLUMINA,...)
            PU="character",         #  Platform unit (e.g. lane code)
            SM="character",         #  Sample (Pool name)
            ntl="integer"           #  number of taglabs (= 12 (static))
            ),
                                validity=function(object) {return(TRUE)})

tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG",
             "PI", "PL", "PU", "SM")

setClass("headerProgram",
    representation(l="list"),
    validity=function(object) {return(TRUE)})

setClass("bamHeaderText",
        representation(head="headerLine", dict="refSeqDict",
                    group="headerReadGroup", prog="headerProgram", 
                    com="character"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Align related classes:
#  bamAlign, bamRange, alignDepth
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamAlign", 
    representation(align="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@align, FALSE, TRUE)))
})


setClass("bamRange", 
    representation(range="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@range), FALSE, TRUE))
})


setClass("alignDepth",
            representation(depth="integer", depth_r="integer", pos="integer",
            params="numeric", refname="character"))


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Segment Count
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamSegments",
        representation(
            seqid = "numeric",
            seqname = "character",
            seqlen = "numeric",
            #
            seg_seqid = "numeric",
            seg_start = "numeric",
            seg_end = "numeric"
        ),
        validity = function(object) {
            n <- length(object@seqid)
            if(length(object@seqs)!=n || 
                length(object@seqnames)!=n ||
                length(object@seqlen) !=n)
            { return(false) }
            
            n <- length(object@seg_seqid)
            if(length(object@seg_start)!=n ||
                length(object@seg_end) != n)
            { return(false) }
        }
)

bamSegments <- function(bam=NULL)
{
    if(is.null(bam))
        return( new("bamSegments"))
    
    if(!is.character(bam))
        stop("bam must be character!")
    
    if(!file.exists(bam))
        stop("bam does not exist!")
    
    reader <- bamReader(bam)
    rd <- getRefData(reader)
    
    res <- new("bamSegments")
    res@seqid <- rd$ID
    res@seqname <- rd$SN
    res@seqlen <- rd$LN
    return(res)
}

setMethod("show", "bamSegments", function(object)
{
    n <- min(6, length(object@seqid))
    
    if(n==0)
    {
        cat("An empty object of class '", class(object), "'.\n", sep="")
        return(invisible())
    }
    
    cat("An object of class '", class(object), "'.\n", sep="")
    cat("Reference sequences: (", length(object@seqid), ")\n", sep="")
    print(data.frame(seqid=object@seqid[1:n],
                        seqname=object@seqname[1:n],
                        seqlen=object@seqlen[1:n]))
    

    cat("Segments: (",length(object@seg_seqid) ,")\n", sep="")
    n <- min(6, length(object@seg_seqid))
    if(n > 0)
    {
        print(data.frame(seqid=object@seg_seqid[1:n],
                    start=object@seg_start[1:n],
                    end=object@seg_end[1:n]))
    }
    return(invisible())
})



setClass("rangeSegCount",
        representation(
            position = "integer",
            count = "integer",
            refname = "character",
            LN = "integer",
            coords = "numeric",
            complex = "logical"
        ),
        validity = function(object) { return(length(position)==length(count)) }
)


setMethod("show", "rangeSegCount", function(object)
{
    o <- object
    op <- o@coords
    n <- 6
    cat("An object of class '", class(o), "'.\n",sep="")
    bm<-Sys.localeconv()[7]
    w<-15
    r<-"right"
    cat("Refname : ", format(o@refname              , w=w, j=r), "\n", sep="")
    cat("Seqid   : ", format(format(op[1], big.m=bm), w=w, j=r), "\n", sep="")
    cat("LN      : ", format(format(o@LN,  big.m=bm), w=w, j=r), "\n", sep="")
    cat("qrBegin : ", format(format(op[2], big.m=bm), w=w, j=r), "\n", sep="")
    cat("qrEnd   : ", format(format(op[3], big.m=bm), w=w, j=r), "\n", sep="")
    cat("Complex : ", format(o@complex              , w=w, j=r), "\n", sep="")
    cat("\n")
    print(data.frame(position=o@position[1:n], count=o@count[1:n]))
    return(invisible())
})

as.data.frame.rangeSegCount <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(data.frame(position=x@position, 
                        count=x@count,
                        row.names=row.names))
}

setGeneric("rangeSegCount", function(object, 
                coords=NULL, segments=NULL, 
                complex=FALSE) standardGeneric("rangeSegCount"))

setMethod("rangeSegCount", "bamReader", 
    function(object, coords=NULL, segments=NULL, complex=FALSE)
    {
        if(!indexInitialized(object))
            stop("Reader must have initialized index! Use 'load.index'!")
        
        if(is.null(coords))
            stop("coords argument is not optional!")
        
        if(!is.numeric(coords))
            stop("coords must be numeric!")
        
        if(length(coords) != 3)
            stop("coords must have length 3")
        
        if(any(coords < 0))
            stop("coords must not be negative")
        
        coords <- as.numeric(coords)
        
        if(is.null(segments))
            stop("segments argument is not optional")
        
        if(!is.numeric(segments))
            stop("segments must be numeric")
        
        if(any(segments < 0))
            stop("segment values must not be negative")
        
        segments <- sort(as.integer(segments))
        
        if(!is.logical(complex))
            stop("complex must be logical")
        
        res <- .Call("bam_count_segment_aligns",
                     object@reader, object@index,
                     coords, segments, 
                     complex[1], PACKAGE="rbamtools")
        
        return(res)
        
    }
)


setGeneric("meltDownSegments", 
           function(object, factor=1) standardGeneric("meltDownSegments"))

setMethod("meltDownSegments", "rangeSegCount", function(object, factor=1)
{
    if(!is.numeric(factor))
        stop("factor must be numeric")
    
    if(length(factor) != 1)
        stop("factor must contain exactly one value")
    
    if(factor[1] < 1)
        stop("factor must be >= 1")
    
    factor <- as.integer(factor)
    
    res <- .Call("bam_count_segment_melt_down", 
                 object, factor[1], PACKAGE="rbamtools")
    return(res)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Gap sites related classes:
#  gapList, gapSiteList
#  bamGapList
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("gapList", 
    representation(list="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@list), FALSE, TRUE))
})

setClass("gapSiteList",
    representation(list="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@list), FALSE, TRUE))
})

setClass("bamGapList",
        representation(list="externalptr", refdata="data.frame"),
        validity=function(object)
{ 
    return(ifelse(is.null(object@list), FALSE, TRUE))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Declaration of generics
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# Reader associated Generics

setGeneric("filename", function(object) standardGeneric("filename"))

setGeneric("isOpen", function(con, rw="") standardGeneric("isOpen"))

setGeneric("bamClose", function(object) standardGeneric("bamClose"))

setGeneric("rewind", function(object) standardGeneric("rewind"))

setGeneric("getHeader",function(object) standardGeneric("getHeader"))

setGeneric("getRefCount",function(object) standardGeneric("getRefCount"))

setGeneric("getRefData",function(object) standardGeneric("getRefData"))

setGeneric("getRefCoords",function(object, sn) standardGeneric("getRefCoords"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Replacement for (deprecated) functions -> .Defunct
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setGeneric("createIndex",function(object,idx_filename)
                                standardGeneric("createIndex"))

setGeneric("loadIndex", function(object, filename)
                                standardGeneric("loadIndex"))

setGeneric("indexInitialized", function(object) 
                                standardGeneric("indexInitialized"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Soon deprecated functions (for consistency reasons)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setGeneric("create.index",function(object, idx_filename)
                                standardGeneric("create.index"))

setGeneric("load.index",function(object, filename)
                                standardGeneric("load.index"))

setGeneric("index.initialized",function(object) 
                                standardGeneric("index.initialized"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setGeneric("bamSort",function(object, prefix="sorted",
            byName=FALSE, maxmem=1e+9,
            path=dirname(filename(object))) standardGeneric("bamSort"))

setGeneric("reader2fastq",function(object, filename, which, append=FALSE)
            standardGeneric("reader2fastq"))

setGeneric("readerToFastq", function(object, filename, which, append=FALSE)
            standardGeneric("readerToFastq"))

setGeneric("bamCopy", function(object, writer, refids, verbose=FALSE)
            standardGeneric("bamCopy"))

setGeneric("extractRanges",function(object, ranges, filename, complex=FALSE,
            header, idxname) standardGeneric("extractRanges"))

setGeneric("bamCount", function(object, coords) standardGeneric("bamCount"))

setGeneric("bamCountAll", function(object, verbose=FALSE)
            standardGeneric("bamCountAll"))

setGeneric("nucStats", function(object, ...) standardGeneric("nucStats"))


# generic for bamReader and bamRange
setGeneric("getNextAlign", function(object) standardGeneric("getNextAlign"))

# generic for bamWriter and bamRange
setGeneric("bamSave", function(object, ...) standardGeneric("bamSave"))

# Generic for conversion into list
setGeneric("as.list", function(x, ...) standardGeneric("as.list"))

# Generic for retrieving RefData string from Objects
setGeneric("getHeaderText", function(object, delim="\n")
                                    standardGeneric("getHeaderText"))

# Generic for Reading member from object list
setGeneric("getVal", function(object, member) standardGeneric("getVal"))

# Generic for Writing member to object list
setGeneric("setVal", function(object, members, values)
                                            standardGeneric("setVal"))

# Generic fora adding read group to header
setGeneric("addReadGroup",function(object, l) standardGeneric("addReadGroup"))

# Generic for retrieving of list size
setGeneric("size", function(object) standardGeneric("size"))

# Generic for retrieving Nr of aligns in BAM region from gapList
setGeneric("nAligns", function(object) standardGeneric("nAligns"))

# Generic for retrieving Nr of gapped-aligns in BAM region from gapList
setGeneric("nAlignGaps", function(object) standardGeneric("nAlignGaps"))

# Generic for reading gapLists (align gaps) from bamReader
setGeneric("gapList", function(object, coords) standardGeneric("gapList"))

# Generic for reading gapSiteList (merged align gap sites) from bamReader
setGeneric("siteList", function(object, coords) standardGeneric("siteList"))

# Generic for reading bamGapList (merged align gap sites for whole bam-files)
# from bamReader
setGeneric("bamGapList", function(object) standardGeneric("bamGapList"))

# Generic for retrieving quality values
setGeneric("getQualDf", function(object, prob=FALSE, ...)
                                    standardGeneric("getQualDf"))

# Generic for retrieving quantile values from (phred) 
# quality tables (used for plotQualQuant)
setGeneric("getQualQuantiles", function(object, quantiles, ...)
                                    standardGeneric("getQualQuantiles"))

# Generic for plotting of (phred) quality quantiles.
setGeneric("plotQualQuant", function(object)
                                    standardGeneric("plotQualQuant"))

# bamHeader related generics
setGeneric("bamWriter", function(x, filename) standardGeneric("bamWriter"))

# refSeqDict related generics
setGeneric("removeSeqs", function(x, rows) standardGeneric("removeSeqs"))

setGeneric("addSeq",
            function(object, SN, LN, AS="", M5=0, SP="", UR="")
            standardGeneric("addSeq"))

setGeneric("head", function(x, ...) standardGeneric("head"))
setGeneric("tail", function(x, ...) standardGeneric("tail"))

# bamHeaderText related generics
setGeneric("headerLine", function(object) standardGeneric("headerLine"))

setGeneric("refSeqDict", function(object) standardGeneric("refSeqDict"))

setGeneric("headerReadGroup", function(object)
        standardGeneric("headerReadGroup"))

setGeneric("headerProgram", function(object)
        standardGeneric("headerProgram"))

setGeneric("headerLine<-", function(object,value)
        standardGeneric("headerLine<-"))

setGeneric("refSeqDict<-", function(object, value)
        standardGeneric("refSeqDict<-"))

setGeneric("headerReadGroup<-", function(object, value)
        standardGeneric("headerReadGroup<-"))

setGeneric("headerProgram<-", function(object, value)
        standardGeneric("headerProgram<-"))

setGeneric("bamHeader", function(object)
        standardGeneric("bamHeader"))

# gapSiteList related generics
setGeneric("refID", function(object) standardGeneric("refID"))

# bamRange related generics
setGeneric("getCoords", function(object) standardGeneric("getCoords"))

setGeneric("getParams", function(object) standardGeneric("getParams"))

setGeneric("getSeqLen", function(object) standardGeneric("getSeqLen"))

setGeneric("getRefName", function(object) standardGeneric("getRefName"))

setGeneric("getAlignRange", function(object) standardGeneric("getAlignRange"))

setGeneric("getPrevAlign", function(object) standardGeneric("getPrevAlign"))

setGeneric("stepNextAlign", function(object) standardGeneric("stepNextAlign"))

setGeneric("stepPrevAlign", function(object) standardGeneric("stepPrevAlign"))

setGeneric("push_back", function(object, value) standardGeneric("push_back"))

setGeneric("pop_back", function(object) standardGeneric("pop_back"))

setGeneric("push_front", function(object, value) standardGeneric("push_front"))

setGeneric("pop_front", function(object) standardGeneric("pop_front"))

setGeneric("writeCurrentAlign", 
                function(object, value) standardGeneric("writeCurrentAlign"))

setGeneric("insertPastCurrent", 
                function(object, value) standardGeneric("insertPastCurrent"))

setGeneric("insertPreCurrent", 
                function(object, value) standardGeneric("insertPreCurrent"))

setGeneric("moveCurrentAlign",
                function(object, target) standardGeneric("moveCurrentAlign"))

# Deprecated:
setGeneric("range2fastq", 
        function(object, filename, which, append=FALSE)
            standardGeneric("range2fastq"))

setGeneric("rangeToFastq", 
           function(object, filename, which, append=FALSE)
               standardGeneric("rangeToFastq"))

setGeneric("countNucs", function(object) standardGeneric("countNucs"))


# alignDepth related generics
setGeneric("alignDepth", 
                function(object, gap=FALSE, flagFilter=0) standardGeneric("alignDepth"))

setGeneric("getDepth", 
                function(object, named=FALSE) standardGeneric("getDepth"))

setGeneric("getPos", function(object) standardGeneric("getPos"))

setGeneric("plotAlignDepth",
           function(object, start=NULL, end=NULL, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",  transcript="",
                    strand=NULL , log="y", cex.main=2,
                    col="grey50", fill="grey90", grid=TRUE, 
                    box.col="grey20", box.border="grey80", ... )
    standardGeneric("plotAlignDepth")
)

    
setGeneric("plotAlignDepths",
           function(object, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",
                    log="y", cex.main=2,
                    col="black", fill.fw="grey40", fill.rv="grey90", x.lines=NULL,
                    grid=is.null(x.lines),
                    ... )
    standardGeneric("plotAlignDepths")
)


# bamAlign related generics
setGeneric("name", function(object)
        standardGeneric("name"))

setGeneric("position", function(object)
        standardGeneric("position"))

setGeneric("nCigar", function(object)
        standardGeneric("nCigar"))

setGeneric("cigarData", function(object)
        standardGeneric("cigarData"))

setGeneric("mateRefID", function(object)
        standardGeneric("mateRefID"))

setGeneric("matePosition", function(object)
        standardGeneric("matePosition"))

setGeneric("insertSize", function(object)
        standardGeneric("insertSize"))

setGeneric("mapQuality", function(object)
        standardGeneric("mapQuality"))

setGeneric("alignSeq", function(object)
        standardGeneric("alignSeq"))

setGeneric("alignQual", function(object)
        standardGeneric("alignQual"))

setGeneric("alignQualVal", function(object)
    standardGeneric("alignQualVal"))

setGeneric("pcrORopt_duplicate", function(object)
    standardGeneric("pcrORopt_duplicate"))

setGeneric("pcrORopt_duplicate<-", function(object, value)
    standardGeneric("pcrORopt_duplicate<-"))

setGeneric("failedQC", function(object)
        standardGeneric("failedQC"))

setGeneric("failedQC<-", function(object, value)
        standardGeneric("failedQC<-"))

setGeneric("firstInPair", function(object) 
        standardGeneric("firstInPair"))

setGeneric("firstInPair<-", function(object ,value)
        standardGeneric("firstInPair<-"))

setGeneric("secondInPair", function(object) 
        standardGeneric("secondInPair"))

setGeneric("secondInPair<-", function(object, value)
        standardGeneric("secondInPair<-"))

setGeneric("unmapped", function(object)
        standardGeneric("unmapped"))

setGeneric("unmapped<-", function(object, value)
        standardGeneric("unmapped<-"))

setGeneric("mateUnmapped", function(object)
        standardGeneric("mateUnmapped"))

setGeneric("mateUnmapped<-", function(object, value)
        standardGeneric("mateUnmapped<-"))

setGeneric("reverseStrand", function(object)
        standardGeneric("reverseStrand"))

setGeneric("reverseStrand<-", function(object, value)
        standardGeneric("reverseStrand<-"))

setGeneric("mateReverseStrand", function(object)
        standardGeneric("mateReverseStrand"))

setGeneric("mateReverseStrand<-", function(object, value)
        standardGeneric("mateReverseStrand<-"))

setGeneric("paired", function(object) 
        standardGeneric("paired"))

setGeneric("paired<-", function(object, value)
        standardGeneric("paired<-"))

setGeneric("properPair", function(object)
        standardGeneric("properPair"))

setGeneric("properPair<-", function(object, value)
        standardGeneric("properPair<-"))

setGeneric("secondaryAlign", function(object)
        standardGeneric("secondaryAlign"))

setGeneric("secondaryAlign<-", function(object, value)
        standardGeneric("secondaryAlign<-"))

setGeneric("suppAlign", function(object)
    standardGeneric("suppAlign"))

setGeneric("suppAlign<-", function(object, value)
    standardGeneric("suppAlign<-"))

setGeneric("flag", function(object) 
        standardGeneric("flag"))

setGeneric("flag<-", function(object, value)
        standardGeneric("flag<-"))



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  static functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

gc_content <- function(An, Cn, Gn, Tn)
{
    denom <- sum(An+Cn+Gn+Tn)
    if(denom==0)
        return(0)
    return(sum(Gn + Cn) / denom)
}
at_gc_ratio <- function(An, Cn, Gn, Tn)
{
    denom <- sum(Gn+Cn)
    if(denom==0)
        return(NA)
    return(sum(An + Tn) / denom)
}



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamReader
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Opening and closing a BAM-File for reading
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", signature="bamReader",
            definition=function(.Object, filename)
{
        .Object@filename <- filename
        .Object@reader <- .Call("bam_reader_open",
                                    path.expand(filename), PACKAGE="rbamtools")
        
        .Object@startpos <- .Call("bam_reader_tell", 
                                    .Object@reader, PACKAGE="rbamtools")
        return(.Object)
})


bamReader <- function(filename, indexname, idx=FALSE, verbose=0)
{
    if(!is.logical(idx))
        stop("[bamReader] idx must be logical!")
    if(length(idx)>1)
        stop("[bamReader] length(idx) must be 1!")
    if(!is.numeric(verbose))
        stop("[bamReader] verbose must be numeric!")
    
    reader <- new("bamReader", filename)
    
    if((!idx) && missing(indexname))
    {
        if(verbose[1]==1)
            cat("[bamReader] Opened file '", basename(filename), "'.\n", sep="")
        else if(verbose[1]==2)
            cat("[bamReader] Opened file '", filename, "'.\n", sep="")
        return(reader)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  use indexname or set default
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(missing(indexname))
        idxfile <- paste(filename, "bai", sep=".")
    else
        idxfile <- indexname
    
    loadIndex(reader, idxfile)
    
    if(verbose[1]==1)
    {
        cat("[bamReader] Opened file '", basename(filename),
                    "' and index '", basename(idxfile), "'.\n", sep="")
    }else if(verbose[1]==2)
    {
        cat("[bamReader] Opened file '", filename,
                    "' and index '", idxfile, "'.\n", sep="")
    }
    
    return(reader)
}

setMethod("filename", "bamReader", function(object) return(object@filename))

setMethod("isOpen", signature="bamReader", definition=function(con, rw="")
{
    return(!(.Call("is_nil_externalptr", con@reader, PACKAGE="rbamtools")))
})

setMethod(f="bamClose", signature="bamReader", definition=function(object)
{
    if(!.Call("is_nil_externalptr", object@index, PACKAGE="rbamtools"))
    {
        .Call("bam_reader_unload_index", object@index, PACKAGE="rbamtools")
    }
    invisible(.Call("bam_reader_close", object@reader, PACKAGE="rbamtools"))
})


setMethod("show","bamReader", function(object)
{
    bm <- Sys.localeconv()[7]
    w <- 20
    r <- "right"
    cat("Class       : ", format(class(object)  , w=w, j=r)                       , "\n", sep="")
    cat("Filename    : ", format(basename(object@filename), w=w, j=r)             , "\n", sep="")
    cat("File status : ", format(ifelse(isOpen(object), "Open", "Closed"), w=w, j=r), "\n", sep="")
    cat("Index status: ", format(ifelse(indexInitialized(object), "Initialized", "Not initialized"), w=w, j=r), "\n", sep="")
    
    if(isOpen(object))
    {
        cat("RefCount    : ", format(getRefCount(object), w=w, j=r)                  , "\n", sep="")
    }
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Opening and closing a BAM-File for reading
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#   Header related functions
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   This is one standard Method for creation of bamHeader
#   and is used as a simple way to pass a header to a new
#   instance of bamWriter
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="getHeader", signature="bamReader", definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check with 'isOpen(reader)'!")
    
    return(new("bamHeader", .Call("bam_reader_get_header", object@reader))) 
})


setMethod(f="getHeaderText", signature="bamReader", definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check 'isOpen(reader)'!")
    
    return(new("bamHeaderText", .Call("bam_reader_get_header_text",
                                    object@reader, PACKAGE="rbamtools")))
})

#  + + + + + + + + + + + + + + + + + # 
#  getRefCount
#  + + + + + + + + + + + + + + + + + # 
setMethod(f="getRefCount", signature="bamReader",
                                            definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check with 'isOpen(reader)'!")
    
    return(.Call("bam_reader_get_ref_count",
                                object@reader, PACKAGE="rbamtools"))
})


#  + + + + + + + + + + + + + + + + + # 
#  getRefData
#  + + + + + + + + + + + + + + + + + # 
setMethod(f="getRefData", signature="bamReader", definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check with 'isOpen(reader)'!")
    
    return(.Call("bam_reader_get_ref_data", 
                                object@reader, PACKAGE="rbamtools"))
})


#  + + + + + + + + + + + + + + + + + # 
#  getRefCoords: Returns coordinates 
#  of entire reference for usage with
#  bamRange, gapList or siteList
#  function.
#  + + + + + + + + + + + + + + + + + # 
setMethod(f="getRefCoords",
                        signature="bamReader", definition=function(object,sn)
{
    if(!is.character(sn))
        stop("sn must be character!")
    
    if(length(sn) > 1)
        stop("sn must have length 1!")
    
    ref <- getRefData(object)
    id <- which(sn==ref$SN)
    
    if(length(id) == 0)
        stop("No match for sn in ref-data-SN!")
    
    coords <- c(ref$ID[id], 0, ref$LN[id])
    names(coords) <- c("refid", "start", "stop")
    return(c(ref$ID[id], 0, ref$LN[id]))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End Header related functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Index related functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="createIndex", signature="bamReader",
    definition=function(object,idx_filename)
{
    if(missing(idx_filename))
        idx_filename <- paste(object@filename, ".bai", sep="")
    
    return(invisible(.Call("bam_reader_create_index",
                            path.expand(object@filename),
                            path.expand(idx_filename), PACKAGE="rbamtools")))
})

setMethod("loadIndex", signature="bamReader", 
                                        definition=function(object,filename)
{
    if(!is.character(filename))
        stop("Filename must be character!\n")
    
    if(!file.exists(filename))
        stop("Index file \"", filename, "\" does not exist!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Set index Variable in given bamReader object:
    #  Read object name, create expression string and evaluate in parent frame
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    reader <- deparse(substitute(object))
    
    extxt <- paste(reader,"@index<-.Call(\"bam_reader_load_index\",\"",
                path.expand(filename), "\",PACKAGE=\"rbamtools\")", sep="")
    
    eval.parent(parse(text=extxt))
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Return true if bamReader@index!=NULL (parent frame)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    extxt <- paste(".Call(\"is_nil_externalptr\",", reader,
                                    "@index,PACKAGE=\"rbamtools\")", sep="")
    
    return(invisible(!eval.parent(parse(text=extxt))))
})


setMethod("indexInitialized", signature="bamReader", definition=function(object)
{ return(!(.Call("is_nil_externalptr", object@index, PACKAGE="rbamtools"))) })



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Deprecated functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("create.index", "bamReader", function(object, idx_filename)
{
    message("[create.index] Will soon be deprecated. Use createIndex.")
    return(createIndex(object, idx_filename))
    #.Deprecated(new="createIndex",package="rbamtools")
})


setMethod("load.index", "bamReader", function(object, filename)
{
    message("[load.index] Will soon be deprecated. Use loadIndex.")
    #.Deprecated(new="loadIndex", package="rbamtools")
    
    if(!is.character(filename))
        stop("Filename must be character!\n")
    
    if(!file.exists(filename))
        stop("Index file \"", filename, "\" does not exist!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Set index Variable in given bamReader object:
    #  Read object name, create expression string and evaluate in parent frame
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    reader <- deparse(substitute(object))
    
    extxt <- paste(reader,"@index<-.Call(\"bam_reader_load_index\",\"",
                   path.expand(filename), "\",PACKAGE=\"rbamtools\")", sep="")
    
    eval.parent(parse(text=extxt))
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Return true if bamReader@index!=NULL (parent frame)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    extxt <- paste(".Call(\"is_nil_externalptr\",", reader,
                   "@index,PACKAGE=\"rbamtools\")", sep="")
    
    return(invisible(!eval.parent(parse(text=extxt))))
})


setMethod("index.initialized", "bamReader", function(object)
{
    message("[index.initialized] Will soon be deprecated. Use indexInitialized")
    #.Deprecated(new="indexInitialized", package="rbamtools")
    return(indexInitialized(object))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# 
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="bamSort", signature="bamReader",
        definition=function(object, prefix="sorted", byName=FALSE,
                    maxmem=1e+9, path=dirname(filename(object)))
{
    if(!isOpen(object))
        stop("bamReader must be opened!")
    
    if(!is.logical(byName))
        stop("[bamSort] byName must be logical!")
    
    if(length(byName) > 1)
        stop("[bamSort] byName must have length 1!")
    
    if(!is.numeric(maxmem))
        stop("[bamSort] maxmem must be numeric!")
    
    if(length(maxmem)>1)
        stop("[bamSort] maxmem must have length 1!")
            
    maxmem <- floor(maxmem)
    message("[bamSort] Filename: ", object@filename)
    message("[bamSort] Prefix  : ", prefix)
    message("[bamSort] Maxmem  : ", maxmem)
    message("[bamSort] By Name : ", byName)
    
    .Call("bam_reader_sort_file",
            object@filename,
            path.expand(file.path(path,prefix)),
            maxmem, byName, PACKAGE="rbamtools")
    
    cat("[bamSort] Sorting finished.\n")
    
    return(invisible(paste(prefix, ".bam", sep="")))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End Index related functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# getNextAlign
setMethod(f="getNextAlign", signature="bamReader", definition=function(object)
{
    ans <- .Call("bam_reader_get_next_align", 
                                        object@reader, PACKAGE="rbamtools")
    
    if(is.null(ans))
        return(invisible(NULL))
    else
        return(new("bamAlign", ans))
})



setMethod("reader2fastq", "bamReader", 
        function(object, filename, which, append=FALSE)
{
    message("[reader2fastq] Will soon be deprecated. Use readerToFastq")
    readerToFastq(object, filename, which, append)
})

setMethod("readerToFastq", "bamReader", 
          function(object, filename, which, append=FALSE)
{
    if(!isOpen(object))
        stop("Reader must be opened!")
    
    if(!is.logical(append))
        stop("'append' must be logical!")
    
    if(!is.character(filename))
        stop("'filename' must be character!")
              
    if(missing(which))
    {
        return(invisible(.Call("bam_reader_write_fastq", object@reader,
            filename, append, PACKAGE="rbamtools")))
    }else{
        if(!is.numeric(which))
            stop("'which' argument must be numeric!")
        
        ans <- .Call("bam_reader_write_fastq_index", object@reader, filename,
            as.integer(sort(unique(which))), append, PACKAGE="rbamtools")
        
        if(ans < length(which))
            message("[readerToFastq] EOF reached.\n")
        
        message("[readerToFastq]", ans, "records written.\n")
            return(invisible(ans))
    }
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Reading gap-lists
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("gapList", "bamReader", function(object, coords)
{
    if(!indexInitialized(object))
        stop("Reader must have initialized index!")
    
    return(new("gapList", object, coords))
})

setMethod("siteList", "bamReader", function(object, coords)
{
    if(!indexInitialized(object))
        stop("Reader must have initialized index!")
    
    return(new("gapSiteList", object, coords))
})

setMethod("bamGapList", "bamReader", function(object)
{
    if(!indexInitialized(object))
        stop("Reader must have initialized index!")
    
    return(new("bamGapList", object))
})


setMethod("rewind", "bamReader", function(object)
{
    return(invisible(.Call("bam_reader_seek", 
                    object@reader, object@startpos, PACKAGE="rbamtools")))
})


setMethod("bamSave", "bamReader", function(object, writer)
{
    if(!is(writer, "bamWriter"))
        stop("'writer' must be 'bamWriter'!")
    
    if(!isOpen(object))
        stop("'reader' is not open! Check 'isOpen'!")
    
    if(!isOpen(writer))
        stop("'writer' is not open! Check 'isOpen'!")
    
    # Saving old reading position
    oldpos <- .Call("bam_reader_tell", object@reader, PACKAGE="rbamtools")
    
    # Reset reader to start position
    .Call("bam_reader_seek",
                    object@reader, object@startpos, PACKAGE="rbamtools")
    
    nAligns <- .Call("bam_reader_save_aligns",
                    object@reader, writer@writer, PACKAGE="rbamtools")
    
    bm <- Sys.localeconv()[7]
    
    message("[bamSave.bamReader] Saving ", format(nAligns, big.mark=bm),
            " to file '", basename(writer@filename), "' finished.\n", sep="")
    
    .Call("bam_reader_seek", object@reader, oldpos, PACKAGE="rbamtools")
    
    return(invisible(nAligns))
})


setMethod("bamCopy", "bamReader", function(object, writer, refids, verbose=FALSE)
{
    if(!is(writer, "bamWriter"))
        stop("writer must be 'bamWriter'!")
    
    if(!isOpen(object))
        stop("reader is not open! Check 'isOpen'!")
    
    if(!isOpen(writer))
        stop("writer is not open! Check 'isOpen'!")
    
    if(!indexInitialized(object))
        stop("reader must have initialized index! Check 'indexInitialized'!")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check refids argument: When missing copy all ref's
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ref <- getRefData(object)
    if(missing(refids))
    {
        refids <- ref$ID
        n <- length(refids)
        mtc <- 1:n
    }
    else
    {
        mtc <- match(refids, ref$ID)
        if(any(is.na(mtc)))
            stop("refids must be subset of Reference-ID's! Check 'getRefData'!")
        n <- length(refids)    
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Copy aligns with bamRanges as intermediate buffer
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    bm <- Sys.localeconv()[7]
    nAligns <- 0
    for(i in 1:n)
    {
        range <- bamRange(object, 
                        c(ref$ID[mtc[i]], 0, ref$LN[mtc[i]]), complex=FALSE)
        
        nAligns <- nAligns+size(range)
        if(verbose)
        {
            message("[bamCopy.bamReader] i: ", i, "\tCopying ", 
            format(size(range), big.mark=bm, width=10), 
                    " aligns for Reference '", ref$SN[mtc[i]], "'.\n", sep="")
        }
        
        bamSave(writer, range, ref$ID[mtc[i]])
        rm(range)
        gc()
    }
    message("[bamCopy.bamReader] Copying ", 
        format(nAligns, big.mark=bm, width=10), " aligns finished.\n", sep="")
})


setMethod("extractRanges", "bamReader",
    definition=function(object, ranges, filename, complex=FALSE, header, idxname)
{
    if(!isOpen(object))  
        stop("Provided reader must be opened!")
    
    if(!indexInitialized(object))
        stop("Provided reader must have initialized index!")
    
    if(missing(header))
    {
        header <- getHeader(object)
    }else{
        if(!is(header, "bamHeader"))
            stop("[extractRanges] header must be of class 'bamHeader'")
        
        message("[extractRanges] bamHeader provided. Slot 'headerLine' will be changed (SO: unknown). Slot 'refSeqDict' will be overwritten.\n")
    }
    if(!is.data.frame(ranges))
        stop("[extractRanges] ranges must be 'data.frame'!")
    
    if(!is.logical(complex))
        stop("[extractRanges] complex must be logical!")
    
    if(length(complex) > 1)
        stop("[extractRanges] complex must have length 1!")
    
    # Preparing ranges table
    if(!all(is.element(c("seqid", "start", "end"), names(ranges))))
        stop("ranges argument must contain columns 'seqid', 'start', 'end'!")
    
    
    # Preparing filenames
    file_prefix <- sub("^([^.]*).*", "\\1", basename(filename))
    unsort_filename <- file.path(dirname(filename),
                paste("unsort", paste(file_prefix, "bam", sep="."), sep="_"))
    
    filename <- file.path(dirname(filename), paste(file_prefix, "bam", sep="."))
    
    message("[extractRanges] Provided filename is changed to '", filename,
                                        "' (see help for 'bamSort').", sep="")
    
    if(missing(idxname))
    {
        idxname <- paste(filename, "bai", sep=".")
    }else{
        if(!is.character(idxname))
            stop("[extractRanges] idxname must be character!\n")
    }
    bm <- Sys.localeconv()[7]
    

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  prepare range data
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    # It is essential for indexing, that all ref-ID's which
    # occur in aligns are also (implicitly) present in the
    # reference sequence dictionary (RSD) section.
    #
    # E.g. when there is an align which has refid 4, there
    # must be at least 5 entries in RSD because they are
    # indexed implicitly (that is: there is no entry in RSD
    # which says refid=4).
    #
    # Their ID is identified with the numbers
    # 0 to [(number of Entries in RSD)-1].
    #
    # Otherwise samtools indexing crashes without warning.
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    gp <- ranges[, c("seqid", "start", "end")] 
    rd <- getRefData(object)
    mtc <- match(gp$seqid, rd$SN)
    isna <- is.na(mtc)
    if(all(isna))
    {
        message("[extractRanges] No matching seqids for genes:")
        print(gp)
        message("[extractRanges] No output generated.\n")
        return(invisible())
    }
    
    if(any(isna))
    {
        message("[extractRanges] Missing seqid matches. Skipping following genes:")
        print(gp[isna, ])
        gp <- gp[!isna, ]
    }
    
    n <- dim(gp)[1]
    gp$old_ID <- rd$ID[mtc]
    gp$LN <- rd$LN[mtc]
    
    # Provide (unique) new ID's
    renew <- data.frame(old=sort(unique(gp$old_ID)))
    nid <- dim(renew)[1]
    renew$new <- 0:(nid-1)
    mtc <- match(gp$old_ID, renew$old)
    
    gp$new_ID <- renew$new[mtc]
    
    new_rd <- merge(renew, rd, by.x="old", by.y="ID")
    nref <- dim(new_rd)[1]
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  create new header
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    htxt <- getHeaderText(header)
    hl <- headerLine(htxt)
    setVal(hl, "SO", "unsorted")
    
    rsd <- new("refSeqDict")
    for(i in 1:nref)
        addSeq(rsd, SN=new_rd$SN[i], LN=new_rd$LN[i])
    headerLine(htxt) <- hl
    refSeqDict(htxt) <- rsd
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Writing aligns
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    cat("[extractRanges] Writing aligns to temporary file '", 
                                    unsort_filename, "'.\n", sep="")
    
    writer <- bamWriter(bamHeader(htxt), unsort_filename)
    
    nAligns <- 0
    for(i in 1:n)
    {
        range <- bamRange(object, c(gp$old_ID[i], gp$start[i], gp$end[i]))
        if(size(range)==0)
        {
            message("No aligns found for gene '", gp$gene_name[i], "'.")
        }else{
            bamSave(writer, range, refid=gp$new_ID[i])
            nAligns <- nAligns+size(range)
        }
    }
    message("[extractRanges] Writing of", format(nAligns, big.mark=bm),
                                                        "aligns finished.")
    
    bamClose(writer)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Sorting BAM output file
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    cat("[extractRanges] Sorting:\n")
    nread <- bamReader(unsort_filename)
    if(!isOpen(nread))
        stop("unsorted bam file not found!")
    bamSort(nread, prefix=file_prefix)
    bamClose(nread)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Creating index for ouput file
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    message("[extractRanges] Creating index '", basename(idxname), "'.", sep="")
    
    nread <- bamReader(filename)
    createIndex(nread, idx_filename=idxname)
    message("[extractRanges] Finished.\n")
    message("[extractRanges] You may want to delete file '", 
                                    basename(unsort_filename), "'.\n", sep="")
    return(invisible(nAligns))
})



setMethod("bamCount", signature="bamReader", definition=function(object, coords)
{
    if(!indexInitialized(object))
        stop("[bamCount] reader must have initialized index! Use 'loadIndex'!")
    
    if(missing(coords))
        stop("[bamCount] coords is not optional!")
    
    if(!is.numeric(coords))
        stop("[bamCount] coords must be numeric")
    
    res <- .Call("bam_count", object@reader, 
                                    object@index, coords, PACKAGE="rbamtools")
    
    names(res) <- c("M", "I", "D", "N", "S", "H", "P", "=", "X", "nAligns")
    return(res)
})


setMethod("bamCountAll", "bamReader", function(object, verbose=FALSE)
{
    if(!isOpen(object))
        stop("reader is not open! Check 'isOpen'!")
    
    if(!indexInitialized(object))
        stop("reader must have initialized index! Check 'indexInitialized'!")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check refids argument: When missing copy all ref's
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ref <- getRefData(object)
    nr <- nrow(ref)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Count first refid
    #  and read size and names of result
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(verbose)
        cat("[bamCountAll] Counting ", ref$SN[1],  "\t[ 1/", nr, "]", sep="")
    count <- bamCount(object, c(ref$ID[1], 0, ref$LN[1]))
    nc <- length(count)
    
    mtx <- matrix(numeric(nc*nr), ncol=nc)
    colnames(mtx) <- names(count)
    rownames(mtx) <- ref$SN
    mtx[1, ] <- count
    
    if(nr > 1)
    {
        for(i in 2:nr)
        {
            if(verbose)
            {
                cat("\r[bamCountAll] Counting ", ref$SN[i], 
                            "\t[", format(i, width=2), "/", nr, "]", sep="")
            }
            mtx[i, ] <- bamCount(object, c(ref$ID[i], 0, ref$LN[i]))
        }
    }
    
    if(verbose)
        cat("\n[bamCountAll] Finished.\n")
    res <- as.data.frame(mtx)
    res$ID <- ref$ID
    res$LN <- ref$LN
    return(res)
})


setMethod("nucStats", "bamRange", function(object)
{
    m <- countNucs(object)
    gcc <- gc_content(m[1], m[2], m[3], m[4])
    at_gc <- at_gc_ratio(m[1], m[2], m[3], m[4])
    dfr<-data.frame(
                        nAligns=size(object),
                        A=m[1],
                        C=m[2],
                        G=m[3],
                        T=m[4],
                        N=m[5],
                        gcc=gcc,
                        at_gc_ratio=at_gc
                    )
    
    refname <- .Call("bam_range_get_refname",
                        object@range, PACKAGE="rbamtools")
    
    if(!is.null(refname))
        row.names(dfr) <- refname
    
    return(dfr)
})



setMethod("nucStats", "bamReader", function(object)
{
    if(!isOpen(object))
        stop("Reader must be open (check 'isOpen')!")
    if(!indexInitialized(object))
        stop("Reader must have initialized index (use 'loadIndex')!")
    
    
    ref <- getRefData(object)
    n <- nrow(ref)
    m <- matrix(0, nrow=n, ncol=5)
    nAligns <- numeric(n)
    for(i in 1:n)
    {
        range <- bamRange(object, c(ref$ID[i], 0, ref$LN[i]))
        nAligns[i] <- size(range)
        m[i, ] <- countNucs(range)
    }
    dfr <- data.frame(nAligns=nAligns, 
                            A=m[, 1], C=m[, 2], G=m[, 3], T=m[, 4], N=m[, 5])
    
    dfr$gcc <- gc_content(dfr$A, dfr$C, dfr$G, dfr$T)
    
    dfr$at_gc_ratio <- at_gc_ratio(dfr$A, dfr$C, dfr$G, dfr$T)
    
    rownames(dfr) <- ref$SN
    return(dfr)
})

setMethod("nucStats", "character", 
        definition=function(object, idxInfiles=paste(object, ".bai", sep=""))
{
    if(any(!file.exists(object)))
        stop("[nucStats] Files (object) not found!")
    
    if(!is.character(idxInfiles))
        stop("[nucStats] idxInfiles must be character!")
    
    if(any(!file.exists(idxInfiles)))
        stop("[nucStats] Files (idxInfiles) not found!")
    
    n <- length(object)
    if(length(idxInfiles)!=n)
        stop("[nucStats] infiles and idxInfiles must have same length!")
    
    res <- data.frame(nAligns=numeric(n), A=numeric(n),
                C=numeric(n), G=numeric(n), T=numeric(n), N=numeric(n))
    
    for(i in 1:n)
    {
        reader <- bamReader(object[i])
        loadIndex(reader, idxInfiles[i])
        nc <- nucStats(reader)
        res[i, ] <- lapply(nc[, 1:6], sum)
    }
    res$gcc <- gc_content(res$A, res$C, res$G, res$T)
    res$at_gc_ratio <- at_gc_ratio(res$A, res$C, res$G, res$T)
    rownames(res) <- 1:n
    return(res)
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamHeader
#  Description: See SAM File Format Specification (v1.4-r985)
#  September 7, 2011, Section 1.3
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod("initialize", "bamHeader", function(.Object, extptr)
{
    if(!is(extptr, "externalptr"))
        stop("extptr must be externalptr!")
    .Object@header <- extptr
    return(.Object)
})

setMethod(f="getHeaderText", signature="bamHeader", definition=function(object)
{
    return(new("bamHeaderText", .Call("bam_header_get_header_text", 
                                object@header, PACKAGE="rbamtools"))) })

setMethod("as.character", "bamHeader", function(x, ...)
{
    .Call("bam_header_get_header_text", x@header, PACKAGE="rbamtools")
})

setMethod("show", "bamHeader", function(object)
{
    cat("An object of class \"", class(object), "\"\n", sep="")
    ht <- getHeaderText(object)
    hl <- headerLine(ht)
    dc <- refSeqDict(ht)
    
    cat("headerLine:\n")
    cat("VN:", hl@VN, "\n")
    cat("SO:", hl@SO, "\n")
    
    nsq <- length(dc@SN)
    cat("refSeqDict: (size ", nsq, ")\n", sep="")
    if(nsq>0)
    {
        cat("Seqs: ")
        for(i in 1:(pmin(nsq, 3)))
            cat(dc@SN[i], ",  ")
        cat("...\n")    
    }
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  This is the main function for creating an instance of bamWriter
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("bamWriter", "bamHeader", function(x, filename)
{
    if(!is.character(filename))
        stop("[bamWriter.bamHeader] filename must be character!")
    return(new("bamWriter", x, filename))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# headerLine: Represents two entries: 
# Format version (VN) and sorting order(SO)
# Valid format for VN : /^[0-9]+\.[0-9]+$/.
# Valid entries for SO: unknown (default),  unsorted,  queryname,  coordinate.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", signature="headerLine", 
                            definition=function(.Object, hl="", delim="\t")
{
    # Parses header line from header section
    if(!is.character(hl))
        stop("[headerLine.initialize] Argument must be string.\n")
    
    # Default object content (hl="" or character(0))
    if((length(hl)==1 && nchar(hl)==0) || length(hl)==0)
    {
        .Object@VN="1.4"
        .Object@SO="unknown"
        return(.Object)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Split input string into tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    tags <- unlist(strsplit(hl, delim))
    
    #  Three tags!
    if(length(tags)!=3)
        stop("hl must contain three tags separated by '", delim, "'!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   First  tag: '@HD'
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(tags[1]!="@HD")
        stop("First tag of string must be @HD!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Second tag: 'VN'
    #   TODO: Check Accepted format: /^[0-9]+\.[0-9]+$/.  
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(substr(tags[2], 1, 2)!="VN")
        stop("Second tag of string must be VN!\n")
    
    .Object@VN=substring(tags[2], 4)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Third   tag: 'SO'
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(substr(tags[3], 1, 2)!="SO")
        stop("Third tag of string must be SO!\n")
    
    str <- substring(tags[3], 4)
    if(str=="coordinate")
        .Object@SO <- "coordinate"
    else if(str=="unknown")
        .Object@SO <- "unknown"
    else if(str=="unsorted")
        .Object@SO <- "unsorted"
    else if(str=="queryname")
        .Object@SO <- "queryname"
    
    return(.Object)
})

setMethod("getHeaderText", "headerLine", function(object, delim="\t")
    {return(paste("@HD\tVN:", object@VN, "\tSO:", object@SO, sep=""))})

setMethod("getVal", signature="headerLine", definition=function(object, member)
{
    if(!is.character(member))
        stop("[getVal.headerLine] Member must be character!\n")
    if(member=="VN")
        return(object@VN)
    if(member=="SO")
        return(object@SO)
    stop("Member '", member, "' must be 'VN' or 'SO'!\n")
})

setMethod("setVal", signature="headerLine",
                                definition=function(object, members, values)
{
    if(!is.character(members) || !is.character(values))
        stop("Members and values must be character!\n")
    if(length(members)!=length(values))
        stop("Members and values must have same length!\n")
    
    tagLabs <- c("VN", "SO")
    mtc <- match(members, tagLabs)
    if(any(is.na(mtc)))
        stop("Member names must be valid Header line entries!\n")
    
    n <- length(members)
    if(n>2)
        stop("Only two members can be set!\n")
    
    obj <- deparse(substitute(object))
    for(i in 1:n)
    {
        txt <- paste(obj, "@", members[i], " <- '", values[i], "'", sep="")
        eval.parent(parse(text=txt))
    }
    return(invisible())
})

setMethod("as.list", signature="headerLine", definition=function(x, ...)
    {return(list(VN=x@VN, SO=x@SO))})

setMethod("show", "headerLine", function(object)
{
    cat("An object of class \"", class(object), "\"\n", sep="")
    cat("VN: ", object@VN, "\nSO: ", object@SO, "\n", sep="")
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  End headerLine
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   refSeqDict: Reference Sequence Dictionary
#   Represents a variable number of Ref Seqs
#   Valid Members (Entries for each sequence, stored in a data.frame):
#   SN Reference sequence name
#   LN Reference sequence length
#   AS Genome assembly identifier
#   M5 MD5 checksum of the sequence
#   SP Species
#   UR URI of the sequence
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", signature="refSeqDict", 
                            definition=function(.Object, hsq="", delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Reference sequence dictionary of header-text
    #  hsq= Vector of characters,  each representing one Ref-Sequence
    #  length(hsq) = number of Ref-Sequences
    #  Each Ref-string contains 'internally' [tab] delimited seqments:
    #                "SN:ab\tLN:12\tAS:ab\tM5:12\tSP:ab\tUR:ab"
    #  It's allowed to skip segments
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.character(hsq))
        stop("[refSeqDict.initialize] hsq must be character!")
    
    n <- length(hsq)
    # Return empty object when no input string is given
    if((n==1 && nchar(hsq)==0) || n==0)
        return(.Object)
    
    .Object@SN <- character(n)
    .Object@LN <- numeric(n)
    .Object@AS <- character(n)
    .Object@M5 <- numeric(n)
    .Object@SP <- character(n)
    .Object@UR <- character(n)
    
    labels <- c("SN", "LN", "AS", "M5", "SP", "UR")
    for(i in 1:n)
    {
        # Containes separated tags for one sequence
        seq <- unlist(strsplit(hsq[i], delim))
        if(seq[1]!="@SQ")
        stop("First segment in Ref-sequence tag must be '@SQ'!")
        seq <- seq[-1]
        
        # Contains column number in dict@df for each tag
        cols <- match(substr(seq, 1, 2), labels)
        m <- length(cols)
        
        for(j in 1:m)
        {
            txt <- substr(seq[j], 4, nchar(seq[j]))
            # Empty entries are skipped (to avoid errors)
            if(nchar(txt)>0)
            {
                if(cols[j]==1)
                    .Object@SN[i] <- txt
                else if(cols[j]==2)
                {
                    # Try to convert into numeric value
                    numb <- suppressWarnings(as.numeric(txt))  
                    if(is.na(numb))
                    {
                        warning("[refSeqDict.initialize] No numeric value for LN: '",
                                                txt, "'!\n", sep="")
                    }else{
                        .Object@LN[i] <- numb
                    }
                }
                else if(cols[j]==3)
                    .Object@AS[i] <- txt
                else if(cols[j]==4)
                {
                    # Try to convert into numeric value
                    numb <- suppressWarnings(as.numeric(txt))  
                    if(is.na(numb))
                    {
                        warning("[refSeqDict.initialize] No numeric value for LN: '",
                                                txt, "'!\n", sep="")
                    }else{
                        .Object@M5 <- numb
                    }
                }
                else if(cols[j]==5)
                    .Object@SP[i] <- txt
                else if(cols[j]==6)
                    .Object@UR[i] <- txt
            }
        }
    }
    return(.Object)
})

setMethod(f= "[", signature="refSeqDict", definition=function(x, i)
{
    rsd <- new("refSeqDict")
    rsd@SN <- x@SN[i]
    rsd@LN <- x@LN[i]
    rsd@AS <- x@AS[i]
    rsd@M5 <- x@M5[i]
    rsd@SP <- x@SP[i]
    rsd@UR <- x@UR[i]
    return(rsd)
})

setMethod(f="dim", signature="refSeqDict", definition=function(x)
                            {return(c(length(x@SN), 6))})


setMethod("removeSeqs", signature="refSeqDict", definition=function(x, rows)
{
    #  Removes given rows (=Sequences) from Dictionary
    #  so they are excluded from header
    n <- length(x@SN)
    if(!is.numeric(rows))  
        stop("[removeSeqs.refSeqDict] Sequence indices must be numeric!")
    rows <- as.integer(rows)
    
    if(any(rows)<1)
        stop("[removeSeqs.refSeqDict] Sequence indices must be positive!")
    if(any(rows)>n)
        stop("[removeSeqs.refSeqDict] Sequence indices must be <", n, "!")
    
    # Execute per eval in parent.frame
    if(length(rows)>1)
        rmv <- paste("c(", paste(rows, collapse=", "), ")", sep="")
    else
    rmv <- rows
    
    obj <- deparse(substitute(x))
    dictcol <- paste(obj, "@SN", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@LN", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@AS", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@M5", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@SP", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@UR", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    return(invisible())
})


setMethod("addSeq", signature="refSeqDict", 
                definition=function(object, SN, LN, AS="", M5=0, SP="", UR="")
{
    index <- length(object@SN)+1
    obj <- deparse(substitute(object))
    colidx <- paste("[", index, "]", sep="")
    
    # Appends new Sequence (row) at the end
    dictcol <- paste(obj, "@SN", colidx, sep="")
    eval.parent(parse(text=paste(dictcol, "<-'", SN, "'", sep="")))
    
    dictcol <- paste(obj, "@LN", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-", LN, sep="")))
    
    dictcol <- paste(obj, "@AS", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-'", AS, "'", sep="")))
    
    dictcol <- paste(obj, "@M5", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-", M5, sep="")))
    
    dictcol <- paste(obj, "@SP", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-'", SP, "'", sep="")))
    
    dictcol <- paste(obj, "@UR", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-'", UR, "'", sep="")))
    
    return(invisible())
})

setMethod("getHeaderText", signature="refSeqDict", 
                                    definition=function(object, delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Returns Ref Data String (can be used for creating new BAM 
    #  file via bamWriter)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
                                        
    labels <- c("SN", "LN", "AS", "M5", "SP", "UR")
    n <- length(object@SN)
    
    if(n==0)
        return(character(0))
    
    seqs <- character(n)
    
    for(i in 1:n)
    {
        ans <- "@SQ"    
        if(nchar(object@SN[i])>0)
            ans <- paste(ans, delim, "SN:", object@SN[i], sep="")
        if(object@LN[i]>0)
            ans <- paste(ans, delim, "LN:", object@LN[i], sep="")
        if(nchar(object@AS[i])>0)
            ans <- paste(ans, delim, "AS:", object@AS[i], sep="")
        if(object@M5[i]>0)
            ans <- paste(ans, delim, "M5:", object@M5[i], sep="")
        if(nchar(object@SP[i])>0)
            ans <- paste(ans, delim, "SP:", object@SP[i], sep="")
        if(nchar(object@UR[i])>0)
            ans <- paste(ans, delim, "UR:", object@UR[i], sep="")
        seqs[i] <- ans
    }
    return(paste(seqs, collapse="\n"))
})


#  Return first or last part of refSeqDict data.frame
#  S3 Generic is supplied via importFrom in NAMESPACE

setMethod("head", "refSeqDict", function(x, n=6L, ...)
{
    stopifnot(length(n) == 1L)
    if (n < 0L)
        stop("[head.refSeqDict] n<0!")
    
    m <- length(x@SN)
    if(m==0)
        cat("[head.refSeqDict] Empty object.\n")
    
    n <- min(n, m)
    if(n == 0L)
        return(as.data.frame(new("refSeqDict")))
    else
        return(as.data.frame(x)[1:n, ])
})

# S3 Generic is supplied via importFrom in NAMESPACE
setMethod("tail", "refSeqDict", definition=function(x, n=6L, ...)
{
    stopifnot(length(n) == 1L)
    if (n < 0L)
        stop("[tail.refSeqDict] n<0!")
    m <- length(x@SN)
    if(m==0)
        cat("[tail.refSeqDict] Empty object.\n") 
    n <- min(n, m)
    if(n == 0L)
        return(as.data.frame(new("refSeqDict")))
    else
    {
        n <- m-n+1
        return(x@df[n:m, ])
    }
})

setMethod("show", "refSeqDict", function(object)
{
    if(length(object@SN)>0)
    {
        cat("An object of class \"", class(object), "\"\n", sep="")
        print(head(object))
    }else{
        cat("An empty object of class \"", class(object), "\".\n", sep="")
    }
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End refSeqDict
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  headerReadGroup
#  ReadGroup
#  ID Read Group identifier
#  CN Name of sequencing center
#  DS Description
#  FO Flow order
#  KS Nucleotides corresponding to key sequence of each read
#  LB Library
#  PG Programs used for processing the Read Group
#  PI Predicted median insert size
#  PL Sequencing Platform:
#     CAPILLARY, LS454, ILLUMINA, SOLID, HELICOS, IONTORRENT or PACBIO
#  SM Sample name.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



setMethod(f="initialize", signature="headerReadGroup",  
                                definition=function(.Object, hrg="", delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Read-Group part of Header data. See Sam Format 
    #  Specificatioin 1.3 (Header Section)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.character(hrg))
        stop("[headerReadGroup.initialize] Argument must be string.\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Samtools file format says: Unordered multiple @RG lines are allowed
    #  Each @RG segment comes as one string in hrg
    #  Number of @RG segments = length(hrg)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Split hgr into multiple @RG fragments
    #  In effect, hrg can be either given as vector with length > 1
    #  or as single vector with @RG entries separated by '\n'
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    hrg <- unlist(strsplit(hrg, "\n"))
    
    .Object@nrg <- length(hrg)
    
    .Object@ntl <- 12L                      # number of tags
    .Object@ID <- character(.Object@nrg)
    .Object@CN <- character(.Object@nrg)
    .Object@DS <- character(.Object@nrg)
    .Object@DT <- character(.Object@nrg)
    .Object@FO <- character(.Object@nrg)
    .Object@KS <- character(.Object@nrg)
    .Object@LB <- character(.Object@nrg)
    .Object@PG <- character(.Object@nrg)
    .Object@PI <- character(.Object@nrg)
    .Object@PL <- character(.Object@nrg)
    .Object@PU <- character(.Object@nrg)
    .Object@SM <- character(.Object@nrg)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Allows for empty object
    #  hrg="" or character(0)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if((length(hrg)==1 && nchar(hrg)==0) || length(hrg)==0)
    {
        .Object@nrg <- 0L
        return(.Object)
    }
    
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG",
                                                    "PI", "PL", "PU", "SM")
    
    for(i in 1:(.Object@nrg))
    {
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Split string into fields
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        tags <- unlist(strsplit(hrg[i], delim))
        
        if(tags[1] != "@RG")
            stop("First item of string must be @RG!\n")
        
        #  TODO: Routine does not check for:
        #  'Each @RG line must have a unique ID.' (SAM file format)
        
        tags <- tags[-1]
        ntags <- length(tags)
        for(j in 1:ntags)
        {
            if(substr(tags[j], 1, 2) == "ID")
                .Object@ID[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "CN")
                .Object@CN[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "DS")
                .Object@DS[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "DT")
                .Object@DT[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "FO")
                .Object@FO[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "KS")
                .Object@KS[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "LB")
                .Object@LB[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PG")
                .Object@PG[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PI")
                .Object@PI[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PL")
                .Object@PL[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PU")
                .Object@PU[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "SM")
                .Object@SM[i] <- substring(tags[j], 4)
        }
    }
    return(.Object)
})


setMethod("show", "headerReadGroup",  function(object)
{
    n <- object@nrg
    if(n > 0)
    {
        cat("An object of class \"", class(object), "\"\n", sep="")
        for(i in 1:n)
        {
            if(nchar(object@ID[i]) > 0)
                cat("ID:", object@ID[i], "\n")
            
            if(nchar(object@CN[i]) > 0)
                cat("CN:", object@CN[i], "\n")
            
            if(nchar(object@DS[i]) > 0)
                cat("DS:", object@DS[i], "\n")
            
            if(nchar(object@DT[i]) > 0)
                cat("DT:", object@DT[i], "\n")
            
            if(nchar(object@FO[i]) > 0)
                cat("FO:", object@FO[i], "\n")
            
            if(nchar(object@KS[i]) > 0)
                cat("KS:", object@KS[i], "\n")
            
            if(nchar(object@LB[i]) > 0)
                cat("LB:", object@LB[i], "\n")
            
            if(nchar(object@PG[i]) > 0)
                cat("PG:", object@PG[i], "\n")
            
            if(nchar(object@PI[i]) > 0)
                cat("PI:", object@PI[i], "\n")
            
            if(nchar(object@PL[i]) > 0)
                cat("PL:", object@PL[i], "\n")
            
            if(nchar(object@PU[i]) > 0)
                cat("PU:", object@PU[i], "\n")
            
            if(nchar(object@SM[i]) > 0)
                cat("SM:", object@SM[i], "\n")
            
            if(n > i)
                cat("\n")
        }
    }else{
        cat("An empty object of class \"", class(object), "\"\n", sep="")
    }
    return(invisible())
})

setMethod("getHeaderText", signature="headerReadGroup", 
                                        definition=function(object, delim="\t")
{
    n <- object@nrg
    if(n == 0)
        return(character(0))
    
    rgtxt <- character(n)
    for(i in 1:n)
    {
        #  ID should always be present
        txt <- paste(delim,"ID:",object@ID[i], sep="")
        
        if(nchar(object@CN[i]) > 0)
            txt <- paste(txt, delim,  "CN:", object@CN[i], sep="")
        
        if(nchar(object@DS[i]) > 0)
            txt <- paste(txt, delim, "DS:", object@DS[i], sep="")
        
        if(nchar(object@DT[i]) > 0)
            txt <- paste(txt, delim, "DT:", object@DT[i], sep="")
        
        if(nchar(object@FO[i]) > 0)
            txt <- paste(txt, delim, "FO:", object@FO[i], sep="")
        
        if(nchar(object@KS[i]) > 0)
            txt <- paste(txt, delim, "KS:", object@KS[i], sep="")
        
        if(nchar(object@LB[i]) > 0)
            txt <- paste(txt, delim, "LB:", object@LB[i], sep="")
        
        if(nchar(object@PG[i]) > 0)
            txt <- paste(txt, delim, "PG:", object@PG[i], sep="")
        
        if(nchar(object@PI[i]) > 0)
            txt <- paste(txt, delim, "PI:", object@PI[i], sep="")
        
        if(nchar(object@PL[i]) > 0)
            txt <- paste(txt, delim, "PL:", object@PL[i], sep="")
        
        if(nchar(object@PU[i]) > 0)
            txt <- paste(txt, delim, "PU:", object@PU[i], sep="")
        
        if(nchar(object@SM[i]) > 0)
            txt <- paste(txt, delim, "SM:", object@SM[i], sep="")
        
        # Remove last "\t"
        rgtxt[i] <- paste("@RG",txt,"\n",sep="")
    }
    return(paste(rgtxt, collapse=""))
})

setMethod("getVal", signature="headerReadGroup", 
                                        definition=function(object, member)
{
    if(!is.character(member))
        stop("Member must be character!\n")
    
    
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", 
                                                "PG", "PI", "PL", "PU", "SM")
    
    mtc <- match(member, tagLabs)
    
    if(any(is.na(mtc)))
        stop("Invalid member name!\n")
    
    l <- list()
    if(object@nrg == 0)
        return(l)
    
    for(i in 1:length(member))
    {
        if(mtc[i] == 1)
            l$ID <- object@ID
        else if(mtc[i] == 2)
            l$CN <- object@CN
        else if(mtc[i] == 3)
            l$DS <- object@DS
        else if(mtc[i] == 4)
            l$DT <- object@DT
        else if(mtc[i] == 5)
            l$FO <- object@FO
        else if(mtc[i] == 6)
            l$KS <- object@KS
        else if(mtc[i] == 7)
            l$LB <- object@LB
        else if(mtc[i] == 8)
            l$PG <- object@PG
        else if(mtc[i] == 9)
            l$PI <- object@PI
        else if(mtc[i] == 10)
            l$PL <- object@PL
        else if(mtc[i] == 11)
            l$PU <- object@PU
        else if(mtc[i] == 12)
            l$SM <- object@SM
    }
    return(l)
})

setMethod("setVal", signature="headerReadGroup", 
                                    definition=function(object, members, values)
{
    if(!is.character(members))
        stop("Member name must be character!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check for valid values list
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.list(values))
        stop("Values must be given as list object")
    
    if(length(members)!=length(values))
        stop("Members and values must have same length!\n")
    
    if(any(lapply(values,length)!=object@nrg))
        stop("Length of values must equal number of read groups!")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check for valid members entries
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG", "PI", 
                                                            "PL", "PU", "SM")
    
    mtc <- match(members, tagLabs)
    
    if(any(is.na(mtc)))
    {
        stop("Members must be valid Read Group Entries ",
                                        "(See SAM Format Specification 1.3!\n")
    }
    
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Create insertion code as string and parse in parent environment
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    n <- length(members)
    obj <- deparse(substitute(object))
    for(i in 1:n)
    {
        for(j in 1:object@nrg)
        {
            txt <- paste(obj, "@", members[i], "[", j, "]", "<-'",
                                                values[[i]][j], "'", sep="")
            eval.parent(parse(text=txt))            
        }

    }
    return(invisible())
})

setMethod("as.list", signature="headerReadGroup", 
                                            definition=function(x, ...)
{
    l <- list()
    l$ID <- x@ID
    l$CN <- x@CN
    l$DS <- x@DS
    l$DT <- x@DT
    l$FO <- x@FO
    l$KS <- x@KS
    l$LB <- x@LB
    l$PG <- x@PG
    l$PI <- x@PI
    l$PL <- x@PL
    l$PU <- x@PU
    l$SM <- x@SM
    return(l)
})


setMethod("addReadGroup", signature="headerReadGroup", 
                                            definition=function(object, l)
{
    if(!is.list(l))
        stop("'l' must be list")
    
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG", "PI", 
                            "PL", "PU", "SM")
    
    mtc <- match(names(l), tagLabs)
    if(any(is.na(mtc)))
        stop("All list names must be valid read group tags.")
    
    mtc <- match(tagLabs, names(l))
    if(is.na(mtc[1]))
       stop("There must be an ID given for new read group")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Increase number of read groups by 1
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    n <- object@nrg
    object@nrg <- n + 1L
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Insert ID tag
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(n == 0)
    {
        object@ID <- l[[mtc[1]]]
    }else{
        object@ID <- c(object@ID, l[[mtc[1]]])        
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Eventually insert other tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ins <- function(o, i)
    {
        if(!is.na(mtc[i]))
        {
            if(n == 0)
                o <- l[[mtc[i]]]
            else if(length(o) > 0)
                o <- c(o, l[[mtc[i]]])
            else
                o <- c(rep("", n), l[[mtc[i]]])
        }else{
            if(n == 0)
                o <- ""
            else
                o <- c(o,"")
        }
        
        return(o)
    }
    
    i <- 2
    object@CN <- ins(object@CN, i)
    i <- i + 1
    object@DS <- ins(object@DS, i)
    i <- i + 1
    object@DT <- ins(object@DT, i)
    i <- i + 1
    object@FO <- ins(object@FO, i)
    i <- i + 1
    object@KS <- ins(object@KS, i)
    i <- i + 1
    object@LB <- ins(object@LB, i)
    i <- i + 1
    object@PG <- ins(object@PG, i)
    i <- i + 1
    object@PI <- ins(object@PI, i)
    i <- i + 1
    object@PL <- ins(object@PL, i)
    i <- i + 1
    object@PU <- ins(object@PU, i)
    i <- i + 1
    object@SM <- ins(object@SM, i)

    return(object)
})



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End headerReadGroup
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  headerProgram
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", signature="headerProgram", 
                        definition=function(.Object, hp="", delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Program part of Header data.
    #  See Sam Format Specificatioin 1.3 (Header Section)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    .Object@l <- list()
    
    if(!is.character(hp))
        stop("[headerProgram.initialize] Argument must be string.\n")
    
    # hp="" or character(0)
    if((length(hp)==1 && nchar(hp)==0)||length(hp)==0)
        return(.Object)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Split string into fields
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    tags <- unlist(strsplit(hp, delim))
    if(tags[1]!="@PG")
        stop("[headerProgram.initialize] First item of string must be @PG!\n")
    
    tags <- tags[-1]
    tagLabs <- c("ID", "PN", "CL", "PP", "DS", "VN")
    n <- length(tags)
    for(i in 1:n)
    {
        f <- substr(tags[i], 1, 2)
        mtc <- match(f, tagLabs)
        if(is.na(mtc))
            stop("Field identifier '", f, "' not in List!\n")
        .Object@l[[f]] <- substr(tags[i], 4, nchar(tags[i]))
    }
    return(.Object)
})

setMethod("getHeaderText", signature="headerProgram", 
                                definition=function(object, delim="\t")
{
    n <- length(object@l)
    if(n==0)
        return(character(0))
    
    rfstr <- character(n)
    for(i in 1:n)
        rfstr[i] <- paste(names(object@l)[i], object@l[[i]], sep=":")
    return(paste("@PG", paste(rfstr, collapse=delim), sep=delim))
})

setMethod("getVal", signature="headerProgram", 
                                    definition=function(object, member)
{
    if(!is.character(member))
        stop("[getVal.headerProgram] Member must be character!\n")
    
    tagLabs <- c("ID", "PN", "CL", "PP", "DS", "VN")
    mtc <- match(member[1], tagLabs)
    
    if(is.na(mtc))
        stop("[getVal.headerProgram] Invalid member name!\n")
    
    return(object@l[[member]])
})

setMethod("setVal", signature="headerProgram", 
                                definition=function(object, members, values)
{
    if(!is.character(members) || !is.character(values))
        stop("Member name and value must be character!\n")
    
    if(length(members)!=length(values))
        stop("Members and values must have same length!\n")
    
    tagLabs <- c("ID", "PN", "CL", "PP", "DS", "VN")
    mtc <- match(members, tagLabs)
    if(any(is.na(mtc)))
        stop("Members must be valid Program Entries (See SAM Format Specification 1.3!\n")
    
    n <- length(members)
    obj <- deparse(substitute(object))
    for(i in 1:n)
    {
        txt <- paste(obj, "@l$", members[i], "<-'", values[i], "'", sep="")
        eval.parent(parse(text=txt))
    }
    return(invisible())
})

setMethod("as.list", signature="headerProgram", 
                                    definition=function(x, ...){return(x@l)})

setMethod("show", "headerProgram", function(object)
{
    n <- length(object@l)
    if(n>0)
    {
        cat("An object of class \"", class(object), "\"\n", sep="")
        for(i in 1:length(object@l))
        {
        cat(names(object@l)[i], ":", object@l[[i]], "\n")
        }
    }else{
        cat("An empty object of class \"", class(object), "\"\n", sep="")
    }
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End headerProgram
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   bamHeaderText: Represents and manages textual version of bamHeader
#   See SAM Format Specification (v1.4-r985)
#
#   Contains header Segments :
#    head  = headerLine        : @HD Header Line
#    dict  = refSeqDict        : @SQ Reference Sequence dictionary
#    group = headerReadGroup   : @RG Read Group
#    prog  = headerProgram     : @PG Program
#
#    TODO:
#    com   = headerComment     : @CO One-line text comment
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Class definition and creational routines for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", signature="bamHeaderText", 
                                definition=function(.Object, bh="", delim="\n")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Header data (as reported by getHeaderText)
    #  See Sam Format Specification 1.3 (Header Section)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.character(bh))
        stop("[bamHeaderText.initialize] Argument must be string.\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Create empty header Set (so it's legal to call getHeaderText()')
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(length(bh)==1 && nchar(bh)==0)
    {
        .Object@head <- new("headerLine")
        .Object@dict <- new("refSeqDict")
        .Object@group <- new("headerReadGroup")
        .Object@prog <- new("headerProgram")
        return(.Object)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Split input string: Each fragment contains data for one header segment
    # 
    #  Identification of tags must be restricted on prefix 
    #  because there may be @RG entries present inside program segment
    #  (used as command line argument e.g. for aligner)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    bht <- unlist(strsplit(bh, split=delim))
    bht_pre <- substr(bht,1,3)
    
    # Read Header Line
    bhl <- bht[grep("@HD", bht_pre)]
    .Object@head <- new("headerLine", bhl)
    
    # Read Sequence Directory
    bsd <- bht[grep("@SQ", bht_pre)]
    .Object@dict <- new("refSeqDict", bsd)
    
    # Read Group
    brg <- bht[grep("@RG", bht_pre)]
    .Object@group <- new("headerReadGroup", brg)
    
    # Read Program Data
    bpd <- bht[grep("@PG", bht_pre)]
    .Object@prog <- new("headerProgram", bpd)
    
    # Read Text comment
    btc <- bht[grep("@CO", bht_pre)]
    com <- substring(btc, 3)
    return(.Object)
})

bamHeaderText <- function(head=NULL, dict=NULL, group=NULL, prog=NULL, com=NULL)
{
    bh <- new("bamHeaderText")
    if(!is.null(head))
    {
        if(is(head, "headerLine"))
            bh@head <- head
        else
            stop("[bamHeaderText] head must be 'headerLine'!")
    }
    if(!is.null(dict))
    {
        if(is(dict, "refSeqDict"))
            bh@dict <- dict
        else
        stop("[bamHeaderText] dict must be 'refSeqDict'")
    }
    
    if(!is.null(group))
    {
        if(is(group, "headerReadGroup"))
            bh@group <- group
        else
            stop("[bamHeaderText] group must be 'headerReadGroup'!")
    }
    
    if(!is.null(prog))
    {
        if(is(prog, "headerProgram"))
            bh@prog <- prog
        else
            stop("[bamHeaderText] prog must be 'headerProgram'!")
    }
    
    if(!is.null(com))
    {
        if(is.character(com))
            bh@com <- com
        else
            stop("[bamHeaderText] com must be 'character'!")
    }
    return(invisible(bh))
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Class definition and creational routines for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Public accessors for member objects for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod(f="headerLine", signature="bamHeaderText", 
                            definition=function(object) {return(object@head)})

setMethod(f="refSeqDict", signature="bamHeaderText", 
            definition=function(object) {return(object@dict)})



setMethod(f="headerReadGroup", signature="bamHeaderText", 
                            definition=function(object){return(object@group)})


setMethod(f="headerProgram", signature="bamHeaderText", 
                            definition=function(object){return(object@prog)})


setReplaceMethod("headerLine", "bamHeaderText", function(object, value)
{
    if(!is(value, "headerLine"))
        stop("[headerLine<-.bamHeaderText] value must be 'headerLine'!")
    object@head <- value
    return(object)
})


setReplaceMethod("refSeqDict", "bamHeaderText", function(object, value)
{
    if(!is(value, "refSeqDict"))
        stop("[refSeqDict<-.bamHeaderText] value must be 'refSeqDict'!")
    object@dict <- value
    return(object)
})


setReplaceMethod("headerReadGroup", "bamHeaderText", function(object, value)
{
    if(!is(value, "headerReadGroup"))
        stop("value must be 'headerReadGroup'!")
    object@group <- value
    return(object)
})


setReplaceMethod("headerProgram", "bamHeaderText", function(object, value)
{
    if(!is(value, "headerProgram"))
        stop("value must be 'headerProgram'!")
    object@prog <- value
    return(object)
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Public accessors for member objects for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



setMethod("getHeaderText", signature="bamHeaderText",
                                    definition=function(object, delim="\n")
{
    hd <- getHeaderText(object@head)
    if(length(hd)==0)
        return(character(0))
    hd <- paste(hd, delim, sep="")
    
    dt <- getHeaderText(object@dict)
    if(length(dt)==0)
        return(character(0))
    dt <- paste(dt, delim, sep="")
    
    gp <- getHeaderText(object@group)
    if(length(gp)>0)
        gp <- paste(gp, delim, sep="")
    
    pg <- getHeaderText(object@prog)
    if(length(pg)>0)
        pg <- paste(pg, delim, sep="")
    
    if(length(object@com)>0)
        cm <- paste(paste("@CO", object@com, sep="\t"), collapse=delim)
    else
        cm <- character(0)
    return(paste(hd, dt, gp, pg, cm, sep=""))
})

setMethod("bamHeader", "bamHeaderText",  function(object)
{
    return(new("bamHeader", .Call("init_bam_header", getHeaderText(object))))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamWriter class
#  Encapsulates an write-opened Connection to a BAM-file.
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize",  signature="bamWriter", 
          definition=function(.Object, header, filename)
{
    if(!is(header, "bamHeader"))
        stop("[initialize.bamWriter] header must be bamHeader!\n")
    
    if(!is.character(filename))
        stop("[initialize.bamWriter] filename must be character!\n")
    
    .Object@filename <- filename
    .Object@writer <- .Call("bam_writer_open", header@header, 
                                path.expand(filename), PACKAGE="rbamtools")
    
    return(.Object)
})

setMethod("filename",  "bamWriter",  function(object) return(object@filename))

setMethod("isOpen", signature="bamWriter", definition=function(con, rw="")
{
    return(!(.Call("is_nil_externalptr", con@writer, PACKAGE="rbamtools")))
})

setMethod(f="bamClose", signature="bamWriter", definition=function(object)
{
    return(invisible(.Call("bam_writer_close", 
                                        object@writer, PACKAGE="rbamtools")))
})

setMethod(f="bamSave", signature="bamWriter", 
                                definition=function(object, value, refid) 
{
    if(missing(refid))
        stop("[bamSave] refid is not optional!")
    
    if(!is.numeric(refid))
        stop("[bamSave] refid must be numeric")
    
    if(refid < 0)
        stop("[bamSave] refid must be >=0!")
    
    refid <- as.integer(refid)
    
    if(is(value, "bamAlign"))
    {
        return(invisible(.Call("bam_writer_save_align", object@writer, 
                            value@align, refid, PACKAGE="rbamtools")))
    }
    
    if(is(value, "bamRange")){
        return(invisible(.Call("bam_range_write", object@writer, 
                               value@range, refid, PACKAGE="rbamtools")))
    }
    else
        stop("bamSave: Saved object must be of type bamAlign or bamRange!\n")
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  gapList
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", "gapList", 
                definition=function(.Object, reader, coords, verbose=FALSE)
{
    if(!is(reader, "bamReader"))
    {
        cat("[initialize.gapList] Class of reader: ", class(reader), ".\n")
        stop("reader must be an instance of bamReader!\n")
    }
    
    if(length(coords) != 3)
        stop("coords must be 3-dim numeric (ref, start, stop)!\n")
    
    if(is.null(reader@index))
        stop("bamReader must have initialized index!\n")
    
    .Object@list <- .Call("gap_list_fetch", 
                reader@reader, reader@index, trunc(coords), PACKAGE="rbamtools")
    
    glsize <- .Call("gap_list_get_size", .Object@list, PACKAGE="rbamtools")
    
    if(verbose)
    {
        message("[initialize.gapList] Fetched list of size ", 
        format(glsize, big.mark=Sys.localeconv()[7]),
                                        " for refid ", coords[1], ".")
    }
    return(.Object)
})

# gapList function for retrieving objects in bamReader section

setMethod("size", signature="gapList", definition=function(object)
    {.Call("gap_list_get_size", object@list, PACKAGE="rbamtools")})

setMethod("nAligns", signature="gapList", definition=function(object)
    {.Call("gap_list_get_nAligns", object@list, PACKAGE="rbamtools")})

setMethod("nAlignGaps", signature="gapList", definition=function(object)
    {.Call("gap_list_get_nAlignGaps", object@list, PACKAGE="rbamtools")})

setMethod("show", "gapList", function(object)
{
    cat("An object of class '", class(object), "'. size: ",
                                                    size(object), "\n", sep="")
    
    cat("nAligns:", nAligns(object), "\tnAlignGaps:", nAlignGaps(object), "\n")
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  gapSiteList
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", "gapSiteList", 
                                definition=function(.Object, reader, coords)
{
    if(missing(reader) || missing(coords))
        return(.Object)
    
    if(!is(reader, "bamReader"))
        stop("reader must be an instance of bamReader!\n")
    
    if(length(coords) != 3)
        stop("coords must be 3-dim numeric (ref, start, stop)!\n")
    
    if(is.null(reader@index))
        stop("bamReader must have initialized index!\n")
    
    .Object@list <- .Call("gap_site_list_fetch", 
        reader@reader, reader@index, trunc(coords), PACKAGE="rbamtools")
    
    return(.Object)
})

setMethod("size", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_size", object@list, PACKAGE="rbamtools")})

setMethod("nAligns", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_nAligns", object@list, PACKAGE="rbamtools")})

setMethod("nAlignGaps", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_nAlignGaps", object@list, PACKAGE="rbamtools")})

setMethod("refID", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_ref_id", object@list, PACKAGE="rbamtools")})


setMethod("show",  "gapSiteList", function(object)
{
    cat("An object of class '", class(object), 
                        "'. size: ", size(object), "\n", sep="")
    
    cat("nAligns:", nAligns(object), "\tnAlignGaps:", nAlignGaps(object), "\n")
    
    return(invisible())
})

merge.gapSiteList <- function(x, y, ...)
{
    if(!is(y,"gapSiteList"))
        stop("'y' must be of class 'gapSiteList'!")
    
    res <- new("gapSiteList")
    xref <- refID(x)
    
    if(refID(x) != refID(y))
        warning("[merge] 'x' and 'y' have different refID's. Using refID(x)!")
    
    res@list <- .Call("gap_site_list_merge", x@list, y@list, refID(x))
    
    return(res)
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamGapList
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", "bamGapList", definition=function(.Object, reader)
{
    if(missing(reader))
    {
        .Object@list <- .Call("gap_site_ll_init")
        return(.Object)
    }
    
    if(!is(reader, "bamReader"))
        stop("reader must be an instance of bamReader!\n")
    if(is.null(reader@index))
        stop("bamReader must have initialized index!\n")
    
    ref <- getRefData(reader)
    ref$start <- 0L
    .Object@list <- .Call("gap_site_ll_fetch", 
                        reader@reader, reader@index, ref$ID, ref$start,
                        ref$LN, PACKAGE="rbamtools")
    
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  filter refdata for existing lists
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    sm <- .Call("gap_site_ll_get_summary_df", .Object@list, PACKAGE="rbamtools")
    mtc <- match(ref$ID, sm$ID)
    .Object@refdata <- ref[!is.na(mtc), ]
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Re-enumerate ID's to 1:n
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    .Object@refdata$ID <- .Call("gap_site_ll_reset_refid", 
                                        .Object@list, PACKAGE="rbamtools")
    
    # ToDo: merge refdata with summary df?
  
    return(.Object)
})



setMethod("size", signature="bamGapList", definition=function(object)
    {.Call("gap_site_ll_get_size", object@list, PACKAGE="rbamtools")})

setMethod("nAligns", signature="bamGapList", definition=function(object)
    {.Call("gap_site_ll_get_nAligns", object@list, PACKAGE="rbamtools")})

setMethod("nAlignGaps", signature="bamGapList", definition=function(object)
    {.Call("gap_site_ll_get_nAlignGaps", object@list, PACKAGE="rbamtools")})

setMethod("show", "bamGapList", function(object)
{
    bm <- Sys.localeconv()[7]
    
    cat("An object of class '", class(object), "'. size: ", 
                    format(size(object), big.mark=bm), "\n", sep="")
    
    cat("nAligns:", format(nAligns(object), big.mark=bm), 
            "\tnAlignGaps:", format(nAlignGaps(object), big.mark=bm), "\n")
    
    return(invisible())
})

summary.bamGapList <- function(object, ...)
{
    return(merge(object@refdata, 
                        .Call("gap_site_ll_get_summary_df", object@list)))
}

merge.bamGapList <- function(x, y, ...)
{
    if(!is(y, "bamGapList"))
        stop("[merge.bamGapList] y must be bamGapList!")
    
    if(size(x)==0)
        stop("[merge.bamGapList] size(x)==0!")
    
    if(size(y)==0)
        stop("[merge.bamGapList] size(y)==0!")
    
    mref <- merge(x@refdata, y@refdata, by="SN", all=T)
    
    n <- dim(mref)[1]
    .Call("gap_site_ll_set_curr_first", x@list)
    .Call("gap_site_ll_set_curr_first", y@list)
    
    res <- new("bamGapList")
    for(i in 1:n)
    {
        if(is.na(mref$ID.x[i]))
        {
            .Call("gap_site_ll_add_curr_pp", 
                        y@list, res@list, as.integer(i-1))
            # copy values from .y to .x side (for later use in ref)
            mref[i, 2:4] <- mref[i, 5:7]
        }
        else if(is.na(mref$ID.y[i]))
        {
            .Call("gap_site_ll_add_curr_pp", 
                        x@list, res@list, as.integer(i-1))
        }else{
            .Call("gap_site_ll_add_merge_pp", 
                        x@list, y@list, res@list, as.integer(i-1))
        }
    }
    
    # get l-part of refdata
    ref <- mref[, 1:4]
    names(ref) <- c("SN", "ID", "LN", "start")
    
    # reset ID to new values  
    ref$ID <- 0:(n-1)
    res@refdata <- ref
    return(res)
}

readPooledBamGaps <- function(infiles, idxInfiles=paste(infiles, ".bai", sep=""))
{
    if(!is.character(infiles))
        stop("infiles must be character!")
    
    if(any(!file.exists(infiles)))
        stop("Files (infiles) not found!")
    
    if(!is.character(idxInfiles))
        stop("idxInFiles must be character!")
    
    if(any(!file.exists(idxInfiles)))
        stop("idxInfiles not found!")
    
    n <- length(infiles)  
    if(length(idxInfiles)!=n)
        stop("infiles and idxInfiles must have same length!")
    
    bm <- Sys.localeconv()[7]
    for(i in 1:n)
    {
        bam <- infiles[i]
        reader <- bamReader(bam)
        if(!file.exists(idxInfiles[i]))
        {
            message("[readPooledBamGaps] Creating BAM-index.", appendLF=FALSE)
            createIndex(reader, idxInfiles[i])
            message("Finished.")
        }
        
        loadIndex(reader, idxInfiles[i])
        message("[readPooledBamGaps] (",
                    format(i, width=2), "/", n, ")", appendLF=FALSE)
        
        if(i==1)
        ga <- bamGapList(reader)
        else
        {
            ga1 <- bamGapList(reader)
            ga <- merge.bamGapList(ga, ga1)
        }
            message("\tList-size: ", format(size(ga), width=7, big.mark=bm), 
                "\tnAligns: ", format(nAligns(ga), width=13, big.mark=bm), ".")
    }
    
    message("[readPooledBamGaps] Finished.")
    return(ga)
}

readPooledBamGapDf <- function(infiles, idxInfiles=paste(infiles, ".bai", sep=""))
{ 
    ga <- readPooledBamGaps(infiles, idxInfiles=paste(infiles, ".bai", sep=""))
    dfr <- as.data.frame(ga)
    attr(dfr, "nAligns") <- nAligns(ga)
    attr(dfr, "nAlignGaps") <- nAlignGaps(ga)
    return(dfr)
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamRange
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Encapsulates a bunch of Alignment datasets that typically have been
#  read from a defined reference region in a BAM-file.
#  Technically,  the alignments are stored in a (C-implemented) double linked
#  list.
#  bamRange objects can be created by a reading procedure on an indexed
#  BAM-file. The alignments can be iterated, readed, written, deleted and
#  added. bamRange objects can be written to a BAM-file via an Instance
#  of bamWriter.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  bamRange parameters:
#  1: seqid      : 0-based index of seqid
#  2: qrBegin    : 0-based left boundary of query region (query range begin)
#  3: qrEnd      : 0-based right boundary of query region (query range end)
#  4: complex    : 0= all aligns included, 1= only aligns with n_cigar > 1
#                                                    included
#  5: rSeqLen    : Length of reference sequence (from getRefData)
#  6: qSeqMinLen : Minimum of query sequence length (= read length)
#  7: qSeqMaxLen : Maximum of query sequence length (= read length)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


bamRange <- function(object=NULL, coords=NULL, complex=FALSE)
{
    if(is.null(object))
        return(new("bamRange", NULL, NULL, FALSE))
    
    if(!is(object, "bamReader"))
        stop("object must be of class 'bamReader'!")
    
    if(!indexInitialized(object))
        stop("reader must have initialized index! Use 'loadIndex'!")

    return(new("bamRange", object, coords, complex))
}


setMethod(f="initialize", signature="bamRange", 
          definition=function(.Object, reader=NULL, coords=NULL, complex=FALSE)
{ 

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Create empty range
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(is.null(reader))
    {
        .Object@range <- .Call("bam_range_init", PACKAGE="rbamtools")
        return(.Object)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Create range from bam-file
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(!is(reader, "bamReader"))
        stop("reader must be an instance of bamReader!")
    
    # coords may either be missing or 3 entries are needed
    if(!is.null(coords))
    {
        if(length(coords)!=3)
            stop("coords must be numeric with length=3 (ref, start, stop)!")
    }

    
    if(is.null(reader@index))
        stop("bamReader must have initialized index!")
    
    if(!is(complex, "logical"))
        stop("complex must be logical!")
    
    if(length(complex) > 1)
        stop("complex must have length 1!")
    
    if(!indexInitialized(reader))
        stop("reader must have initialized index! Use 'loadIndex'!")
    
    .Object <- .Call("bam_range_fetch", reader@reader, 
                    reader@index, trunc(coords), complex, PACKAGE="rbamtools")
    
    return(.Object)
})


setMethod("size", signature="bamRange", definition=function(object)
    {.Call("bam_range_get_size", object@range, PACKAGE="rbamtools")})


setMethod("getCoords", "bamRange", function(object)
    { return(.Call("bam_range_get_coords", object@range))})

setMethod("getParams", "bamRange", function(object)
    { return(.Call("bam_range_get_params", object@range))})

setMethod("getSeqLen", "bamRange", function(object){
  return(.Call("bam_range_get_seqlen", object@range, PACKAGE="rbamtools"))
})


setMethod("getRefName", "bamRange", function(object)
    return(.Call("bam_range_get_refname", object@range, PACKAGE="rbamtools")))


setMethod("show", "bamRange", function(object){
  bm <- Sys.localeconv()[7]
  w <- 11
  r <- "right"
  cat("Class       : ", format(class(object), w=w, j=r)                   , "\n", sep="")
  cat("Size        : ", format(format(size(object), big.m=bm), w=w, j=r)   , "\n", sep="")

  params <- .Call("bam_range_get_params", object@range, PACKAGE="rbamtools")
  cat("Seqid       : ", format(format(params[1], big.m=bm), w=w, j=r)     , "\n", sep="")
  cat("qrBegin     : ", format(format(params[2], big.m=bm), w=w, j=r)     , "\n", sep="")
  cat("qrEnd       : ", format(format(params[3], big.m=bm), w=w, j=r)     , "\n", sep="")
  cat("Complex     : ", format(params[4], w=w, big.m=bm)                , "\n", sep="")
  cat("rSeqLen(LN) : ", format(format(params[5], big.m=bm), w=w, j=r)   , "\n", sep="")
  cat("qSeqMinLen  : ", format(format(params[6], big.m=bm), w=w, j=r)   , "\n", sep="")
  cat("qSeqMaxLen  : ", format(format(params[7], big.m=bm), w=w, j=r)   , "\n", sep="")
  
  refname <- .Call("bam_range_get_refname", object@range, PACKAGE="rbamtools")
  if(!is.null(refname))
  cat("Refname     : ", format(refname, w=w, j="right")       , "\n", sep="")  
  return(invisible())
})


setMethod("getAlignRange", "bamRange", function(object)
    return(.Call("bam_range_get_align_range", 
                object@range, PACKAGE="rbamtools")))


setMethod("getNextAlign", signature="bamRange", definition=function(object)
{
    ans <- .Call("bam_range_get_next_align", object@range, PACKAGE="rbamtools")
    # Must be checked because align list returns NULL when end is reached
    if(is.null(ans))
        return(ans)
    else
        return(new("bamAlign", ans))
})


setMethod("getPrevAlign", signature="bamRange", definition=function(object)
{
    return(new("bamAlign", .Call("bam_range_get_prev_align", 
                        object@range, PACKAGE="rbamtools")))
})


setMethod("stepNextAlign", signature("bamRange"), definition=function(object)
{
    .Call("bam_range_step_next_align", object@range)
    return(invisible())
})


setMethod("stepPrevAlign", signature("bamRange"), definition=function(object)
{
    .Call("bam_range_step_prev_align", object@range)
    return(invisible())
})


# Resets current align to NULL position (i.e. before first element)
# The next call to getNextAlign then returns the first element of list
setMethod("rewind", signature="bamRange", definition=function(object)
{
    invisible(.Call("bam_range_wind_back", object@range, PACKAGE="rbamtools"))
})


setMethod("push_back", signature="bamRange", definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("pushed object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_push_back", object@range, value@align, PACKAGE="rbamtools")
})


setMethod("pop_back", signature="bamRange", definition=function(object)
{
    .Call("bam_range_pop_back", object@range, PACKAGE="rbamtools")
})


setMethod("push_front", signature="bamRange", definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("pushed object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_push_front", object@range, value@align, PACKAGE="rbamtools")
})


setMethod("pop_front", signature="bamRange", definition=function(object)
{
    .Call("bam_range_pop_front", object@range, PACKAGE="rbamtools")
})


setMethod("writeCurrentAlign", signature="bamRange", definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("written object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_write_current_align",
                        object@range, value@align, PACKAGE="rbamtools")
})


setMethod("insertPastCurrent", signature="bamRange", 
                                            definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("written object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_insert_past_curr_align", 
                                object@range, value@align, PACKAGE="rbamtools")
})


setMethod("insertPreCurrent", signature="bamRange",
                                            definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("written object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_insert_pre_curr_align", 
                        object@range, value@align, PACKAGE="rbamtools")
})


setMethod("moveCurrentAlign", signature="bamRange", 
                                        definition=function(object, target)
{
    if(!is(target, "bamRange"))
        stop("target must be bamRange!\n")
    
    .Call("bam_range_mv_curr_align", object@range, target@range)
    return(invisible())
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Rudimentary subsetting operator:
#  Does not change the order of elements, just returns subset
#  Therefore sorts given index i
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("[", signature="bamRange", function(x, i)
{
    i <- sort(as.integer(i))
    if(i[1] < 1)
        stop("No negative indices allowed. Use 'pop_front' or 'pop_back'!")
    
    if(i[length(i)] > size(x))
        stop("Out of bounds index (> size(x))!")
    
    return(.Call("bam_range_idx_copy", x@range, i, PACKAGE="rbamtools"))
})


setMethod("range2fastq", signature="bamRange",
    definition=function(object, filename, which, append=FALSE)
{
    message("[range2fastq] Function is deprecated. Use rangeToFastq.")
    return(rangeToFastq(object, filename, which, append))
})

setMethod("rangeToFastq", signature="bamRange",
    definition=function(object, filename, which, append=FALSE)
{
    if(!is.character(filename))
        stop("'filename' must be character!")
    
    if(!is.logical(append))
        stop("'append' must be logical!")
    
    if(missing(which))
    {
        .Call("bam_range_write_fastq", object@range, filename,
                            append, PACKAGE="rbamtools")
    }else{
        if(!is.numeric(which))
            stop("'which' must be numeric!")
        
        mx <- max(which)
        
        if(mx>size(object))
        {
            cat("[rangeToFastq] Maximum index (", mx,
                    ") is greater than size of range (",
                    size(object), ")!\n", sep="")
        }
        
        written <- .Call("bam_range_write_fastq_index",
            object@range, filename, as.integer(sort(unique(which))),
            append, PACKAGE="rbamtools")
        
        cat("[rangeToFastq]", written, "records written.\n")
    }
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Functions to read and display phred qualities from bamRange
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("getQualDf", "bamRange", function(object, prob=FALSE, ...)
{
    if(!is.logical(prob))
        stop("[getQualDf.bamRange] ")
    if(prob)
    {
        qdf <- .Call("bam_range_get_qual_df", 
                                        object@range, PACKAGE="rbamtools")
        
        rel <- function(x)
        {
            xs <- sum(x)
            if(xs > 0)
                return(x / xs)
            return(x)
        }
        
        res <- data.frame(lapply(qdf, rel))
        names(res) <- names(qdf)
        attributes(res)$col.sums <- unlist(lapply(qdf, sum))
        return(res)
    }
    return(.Call("bam_range_get_qual_df", object@range, PACKAGE="rbamtools"))
})


setMethod("getQualQuantiles", "bamRange", function(object, quantiles, ...)
{
    if(!is.numeric(quantiles))
        stop("[getQualQuantiles.bamRange] quantiles must be numeric!")
    
    if(!(all(quantiles >= 0) & all(quantiles <= 1)))
        stop("[getQualQuantiles.bamRange] all quantiles mustbe in [0, 1]")
    
    quantiles <- sort(unique(round(quantiles, 2)))

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Count qual values for each sequence position
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    qdf <- .Call("bam_range_get_qual_df", object@range, PACKAGE="rbamtools")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Convert integer counts into column-wise relative values
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    rel <- function(x)
    {
        xs <- sum(x)
        if(xs>0)
            return(x/xs)
        return(x)
    }
    
    qrel <- data.frame(lapply(qdf, rel))
    names(qrel) <- names(qdf)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Walk through each column and extract row number
    #  for given quantile values
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    res <- .Call("get_col_quantiles", quantiles, qrel, PACKAGE="rbamtools")
    return(res)
})


setMethod("plotQualQuant",  "bamRange",  function(object)
{
    quant <- c(0.1, 0.25, 0.5, 0.75, 0.9)
    cols <- c("#1F78B4", "#FF7F00", "#E31A1C", "#FF7F00", "#1F78B4")
    
    qq <- getQualQuantiles(object, quant)
    
    maxQ <- floor(1.2 * max(qq))
    xv <- 1:ncol(qq)
    
    plot(xv, xv, ylim=c(0, maxQ), type="n", bty="n", las=1,
            ylab="phred score", xlab="sequence position",
            main="Phred Quantiles for sequence")
    
    lines(xv, qq[1, ], col=cols[1], lty=2)
    lines(xv, qq[2, ], col=cols[2], lty=1)
    lines(xv, qq[3, ], col=cols[3], lwd=2)
    lines(xv, qq[4, ], col=cols[4], lty=1)
    lines(xv, qq[5, ], col=cols[5], lty=2)
    
    legend("top", ncol=6, lty=c(2, 1, 1, 1, 2),
        lwd=c(1, 1, 2, 1, 1), col=cols, xjust=0.5,
        legend=c("10%", "25%", "50%", "75%", "90%"), bty="n", cex=0.8)
    
    return(invisible()) 
})



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  alignDepth
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  alignDepth parameters:
#  - - bamRange derived - -
#  1: seqid      : 0-based index of seqid
#  2: qrBegin    : 0-based left boundary of query region (query range begin)
#  3: qrEnd      : 0-based right boundary of query region (query range end)
#  4: complex    : 0= all aligns included, 1= only aligns with n_cigar > 1
#                                                    included
#  5: rSeqLen    : Length of reference sequence (from getRefData)
#  6: qSeqMinLen : Minimum of query sequence length (= read length)
#  7: qSeqMaxLen : Maximum of query sequence length (= read length)
#  - - alignDepth proprietary - -
#  6: gap     : 0=all aligns counted, 1=only gap adjacent match regions
#  counted
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



setMethod("alignDepth", "bamRange", function(object, gap=FALSE, flagFilter=0)
{
    if(!is.logical(gap))
        stop("gap must be logical!")
    flagFilter <- as.integer(flagFilter)
    if(flagFilter < 0)
        stop("flagFilter must be non-negative")
    
    return(.Call("bam_range_get_align_depth", 
                        object@range, gap, flagFilter, PACKAGE="rbamtools"))
})

setMethod("show", "alignDepth", function(object){
    bm <- Sys.localeconv()[7]
    w <- 11
    cat("Class       : ", format(class(object), w=w, j="right")  , "\n", sep="")
    cat("Seqid       : ", format(object@params[1], w=w, big.m=bm)    , "\n", sep="")
    cat("qrBegin     : ", format(object@params[2], w=w, big.m=bm)    , "\n", sep="")
    cat("qrEnd       : ", format(object@params[3], w=w, big.m=bm)    , "\n", sep="")
    cat("Complex     : ", format(object@params[4], w=w, big.m=bm)    , "\n", sep="")
    cat("rSeqLen(LN) : ", format(object@params[5], w=w, big.m=bm)    , "\n", sep="")
    cat("qSeqMinLen  : ", format(object@params[6], w=w, big.m=bm)    , "\n", sep="")  
    cat("qSeqMaxLen  : ", format(object@params[7], w=w, big.m=bm)    , "\n", sep="")
    cat("refname     : ", format(object@refname, w=w, j="right")     , "\n", sep="") 
    n <- 6
    x <- object@depth[1:n]
    names(x) <- object@pos[1:n]
    print(x)
    return(invisible())
})


setMethod("getDepth", "alignDepth", function(object, named=FALSE)
{
    if(!is.logical(named))
        stop("[getDepth.alignDepth] named must be logical!")
    if(named)
    {
        dp <- object@depth
        names(dp)=object@pos
        return(dp)
    }
    return(object@depth)
})


setMethod("getPos",     "alignDepth", function(object) {return(object@pos)})
setMethod("getParams", "alignDepth", function(object) {return(object@params)})


setMethod("plotAlignDepth", "alignDepth",
        function(object, start=NULL, end=NULL, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",  transcript="",
                    strand=NULL , log="y", cex.main=2,
                    col="grey50", fill="grey90", grid=TRUE, 
                    box.col="grey20", box.border="grey80", ... )
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Start and end positions for exon - rectangles
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.null(start))
    {
        if(is.null(end))
            stop("'end' must be given when start is present")
        
        if(length(start) != length(end))
            stop("'start' and 'end' must have same length!")
        
        if(any(start <0 ) || any(end < 0))
           stop("No negative values allowed in 'start' and 'end'")
    }
    
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Prepare align depth values for polygon plotting and
    #  logarithmic scale
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    nx <- length(object@pos)
    x <- c(object@pos[1], object@pos, object@pos[nx])
    y <- c(1, ifelse(object@depth == 0, 1, object@depth), 1)
    
    
    #  
    if(is.null(xlim))
        xlim <- c(x[1], x[nx])
    
    
    if(!is.null(start))
    {
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Prepare plot area and layout
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        
        # Reset values
        op <- par(no.readonly=TRUE)
        par(oma=c(3, 2, 1, 3))
        
        m <- matrix(c(1, 0, 2), ncol=1)
        layout(m, heights=c(5, lcm(0.2), 2))
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Do upper plot: align depth polygon
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        par(mar=c(0, 4, 3, 1) + 0.1)
        
        plot(x, y, type="n", las=1, main=main, xlim=xlim, 
            xlab="", ylab="", log=log, xaxt="n", bty="n",
            cex.axis=1.5, cex.main=cex.main, ...)
        
        polygon(x, y, col=fill, border=col, lwd=2)
        
        if(grid)
            grid()
        
        #
        mtext(paste("Refname:", object@refname), adj=1, cex=0.8)
        # ylab has to be positioned more outside
        mtext(ylab, side=2, line=4 , adj=0.5)
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Do lower plot: Draw exon boxes, x-axis and transcript text
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        par(mar=c(4, 4, 0, 1) + 0.1)
        plot(x, y, type="n", yaxt="n", xlim=xlim, ylim=c(0, 10), 
            cex.axis=1.5, bty="n", ylab="", xlab=xlab , 
            cex.lab=1.5, ...)
        
        # Draw horizontal gene - line
        if(is.null(strand))
            lines(xlim,c(8,8))
        else
        {
            if(strand == "+")
            {
                arrows(x0=xlim[1], y0=8, x1=xlim[2], y1=8, code=2)
            } else {
                arrows(x0=xlim[1], y0=8, x1=xlim[2], y1=8, code=1)
            }
        }
        
        
        # Draw exon boxes
        for(i in 1:length(start))
            rect(start[i], 6, end[i], 10, col=box.col, border=box.border)
        
        # Write transcript text
        text(xlim[1], 2, transcript, adj=0, cex=1.2)
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Cleanup
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        par(op)
        
    }else{
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Alternative plot when no exon positions are given
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        plot(x, y, type="l", las=1, col=col, bty="n" , log=log,
                    xlab=xlab, ylab=ylab, main=main, ...)
        # log="" turns log scaling off.
        
        if(grid)
            grid()
        mtext(paste("Refname:", object@refname))
    }
    
    return(invisible())
})

## A function for plotting both the forward and reverse strands
## This should probably be called from within another type of function
## plots only the Align depth. Does not deal with transcripts / positions
setMethod("plotAlignDepths", "alignDepth",
        function(object, xlim=NULL,
                 main="Align Depth", xlab="Position", 
                 ylab="Align Depth",
                 log="y", cex.main=1,
                 col="black", fill.fw="grey40", fill.rv="grey90", x.lines=NULL,
                 grid=is.null(x.lines),
                 ... )
{
    ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ##  Prepare align depth values for polygon plotting and
    ##  logarithmic scale
    ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    nx <- length(object@pos)
    x <- c(object@pos[1], object@pos, object@pos[nx])
    y_fw <- c(0, object@depth, 0)
    y_rv <- c(0, object@depth_r, 0)
    ## if logs we don't like 0s. But more complicated is handling a reverse
    ## plot So let's do:
    if(log == "y"){
        y_fw = 1 + y_fw
        y_rv = 1 / (1 + y_rv)
    }else{
        y_rv = -y_rv
    }
    
    if(is.null(xlim))
        xlim <- range(x)
    ylim <- range(c(y_fw, y_rv))
    ## then set up the plot
    plot(x, y_fw, type='n', ylim=ylim, xlim=xlim,
         xlab=xlab, ylab=ylab, main=main,
         cex.main=cex.main, log=log, ...)

    if(grid)
        grid()
    if(!is.null(x.lines))
        segments(x.lines, ylim[1], x.lines, ylim[2], col='grey', lty=2)
    
    polygon(x, y_fw, col=fill.fw, border=col, lwd=1)
    polygon(x, y_rv, col=fill.rv, border=col, lwd=1)
    mtext(paste("Refname:", object@refname), adj=1, cex=0.8)
})

## draws arrows with the arrowhead defined by plot units rathr
## than by inches. Allows the arrowhead to be scaled with the
## code 1, 2, 3, arrowhead at x1, x2, x1 & x2 respectively
## headLength determines the direction of the arrow head, with
## positive numbers pointing to the right.
pu.arrows <- function(x1, y1, x2, y2, headLength, headWidth, code=2, ...)
{
    a.n <- length(x1)
    if(a.n != length(x2) || a.n != length(y1) || a.n != length(y2)){
        warning("pu.arrows, segment coordinates of different length. No arrows drawn")
        return()
    }
    if( code < 1 || code > 2 ){
        code <- 2
        warn("pu.arrows code less than 1 or larger than 2. Set to 2")
    }
    if( code == 3 ){
        head.segments <- matrix(nrow=(4*a.n), ncol=4) ## x1, y1, x2, y2
    }else{
        head.segments <- matrix(nrow=(2*a.n), ncol=4)
    }
    if(code == 1 || code == 3){
        head.segments[1:(2*a.n),1] <- rep(x1, 2)
        head.segments[1:(2*a.n),2] <- rep(y1, 2)
        head.segments[1:(2*a.n),3] <- rep((x1-headLength), 2)
        head.segments[1:a.n,4] <- y1+headWidth
        head.segments[(a.n+1):(2*a.n),4] <- y1-headWidth
    }
    ## next we have to adjust where we put the segment information as that
    ## depends on how many arrowheads we have
    r1 <- ifelse( (code == 2), 1, (2*a.n + 1) )  ## r1 = row1
    if(code == 2 || code == 3){
        head.segments[ r1:(r1+2*a.n-1), 1] <- rep(x2, 2)
        head.segments[ r1:(r1+2*a.n-1), 2] <- rep(y2, 2)
        head.segments[ r1:(r1+2*a.n-1), 3] <- rep((x2-headLength), 2)
        head.segments[ r1:(r1+a.n-1), 4] <- y2+headWidth
        head.segments[ (r1+a.n):(r1+2*a.n-1), 4] <- y2-headWidth
    }
    segments( c(x1, head.segments[,1]), c(y1, head.segments[,2]),
              c(x2, head.segments[,3]), c(y2, head.segments[,4]), ...
             )
    
}
## t should be a list containing
## t$transcripts : dataframe containing columns identifier, start, end, strand
## t$exons       : dataframe containing columns transcript identifier, start, end
## strand is defined as +1 / -1
## if do.plot is FALSE returns the number of y positions required to plot.
plotTranscripts <- function(t, xlim=NULL, main="", xlab="position", ylab="",
                            ex.height=0.25, min.sep=0.02, ar.head.pos=2, yaxt='n',
                            bty='n', doPlot=TRUE, ...)
{
    tr <- t$transcripts
    ex <- t$exons
    ## 
    if(is.null(xlim))
        xlim <- range( c(tr[,'start'], tr[,'end']) )

    min.sep <- min.sep * (xlim[2] - xlim[1])
    ## order by position
    tr <- tr[ order(tr[,'start']), ]

    ## for collission detection set up a set of y positions

    ypos <- rep(1, nrow(tr))
    ex.y <- rep(1, nrow(ex)) ## default position
    i <- 2
    while(i < (1+nrow(tr))){
        o.i <- which( (tr[i,'start'] - tr[1:(i-1), 'end']) < min.sep ) ## those that can overlap.
        ypos[i] <- min(setdiff(1:nrow(tr), ypos[o.i]))     ## the minimum of y positions that don't overlap
        ## set the exon positions as well
        ex.y[ ex[,'transcript'] == tr[i,'transcript'] ] <- ypos[i]
        i <- i + 1
    }
    if(!doPlot)
        return( max(ypos) )

    ypos <- -ypos
    ex.y <- -ex.y
    
    plot(1,1, type='n', xlim=xlim, ylim=c(min(ex.y)-2*ex.height, max(ex.y)+2*ex.height),
         main=main, xlab=xlab, ylab=ylab,
         yaxt=yaxt, bty=bty, ...)
    ## two types of arrow forward and reverse.
    ar.l <- min.sep / ar.head.pos
    fwd.b <- tr[,'seq_region_strand'] == 1
    segments( tr[,'start'], ypos, tr[,'end'], ypos, col=1:nrow(tr) )
    
    pu.arrows( tr[fwd.b,'end'], ypos[fwd.b], tr[fwd.b,'end']+ar.l,
               ypos[fwd.b], col=which(fwd.b), code=2, headLength=ar.l/2,
               headWidth=ex.height, lty=1 )
    pu.arrows( tr[!fwd.b,'start']-ar.l, ypos[!fwd.b],
               tr[!fwd.b,'start'], ypos[!fwd.b], col=which(!fwd.b),
               code=1, headLength=-ar.l/2, headWidth=ex.height, lty=1 )
    ## but only one type of exon!
    rect(ex[,'start'], ex.y-ex.height, ex[,'end'],
         ex.y+ex.height, col=grey(0.5), border='black')

}

## we should define a set of 
plotDepthsTranscripts <- function(object, xlim=NULL,
                                  main="Align Depth", xlab="",
                                  ylab="Align Depth",
                                  log="y", cex.main=1,
                                  col="black", fill.fw="grey40", fill.rv="grey90",
                                  grid=FALSE,
                                  tr, tr.xlab="position", tr.ylab="", ex.height=0.4, min.sep=0.02,
                                  ar.head.pos=2, tr.yaxt='n', tr.bty='n', plotsRatio=5,
                                  ...)
{
    op <- par(no.readonly=TRUE)
    ### first we need to work out a reasonable layout. This will depend on
    ### how many layers of transcripts that we need to show
    tr.layers <- plotTranscripts(tr, doPlot=FALSE)

    if(is.null(xlim))
        xlim <- range(object@pos)
    
    ## for each layer give 1/5th the height of the plot
    l.m <- matrix(c(1,2), nrow=2, ncol=1)
    layout(l.m, heights=c(plotsRatio, tr.layers))
    x.lines <- c(tr$exons[,'start'], tr$exons[,'end'])
    par(mar=c(0,4,4,2))
    ##par(oma=c())  
    plotAlignDepths(object, xlim, main=main, xlab=xlab, ylab=ylab, log=log,
                    cex.main=cex.main, col=col, fill.fw=fill.fw, fill.rv=fill.rv,
                    grid=grid, x.lines=x.lines, bty='n', xaxt='n', ...)

    par(mar=c(5,4,0,2))
    plotTranscripts(tr, xlim=xlim, xlab=tr.xlab, ylab=tr.ylab, ex.height=ex.height,
                    min.sep=min.sep, ar.head.pos=2, yaxt=tr.yaxt, bty='n')
    ## the following seems to make sense, but is a little bit too messy.
    ##usr <- par("usr")
    ##segments(x.lines, usr[3], x.lines, usr[4], lty=2, col='grey')
    
    par(op)
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Count nucleotides
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("countNucs", "bamRange", function(object)
                { return(.Call("bam_range_count_nucs",
                            object@range, PACKAGE="rbamtools"))})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamAlign
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  bamAlign encapsulates all contained data in a single dataset in
#  a BAM-file.
#  bamAlign objects can be read from a bamReader instance and written to a
#  bamWriter instance. All contained data can be read and written via
#  accessors functions.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", signature="bamAlign",
                                    definition=function(.Object,align=NULL)
{
    .Object@align <- align
    return(.Object)
})


setMethod("show", "bamAlign", function(object)
{
    bm <- Sys.localeconv()[7]
    w <- 11
    r <- "right"
    cat("Class       : ", format(class(object)  , w=w, j=r)                     , "\n", sep="")
    cat("refId       : ", format(refID(object)  , w=w, j=r)                     , "\n", sep="") 
    cat("Position    : ", format(format(position(object), big.m=bm), w=w, j=r)   , "\n", sep="")
    
    cat("\nCigar Data  :\n")
    print(cigarData(object))
})


bamAlign <- function(qname, qseq, qqual, cigar, refid, position, 
                flag=272L, alqual=10L, mrefid=(-1L), mpos=(-1L), insertsize=0L)
{
    if(missing(qname))
        stop("[bamAlign] Missing query name!")
    
    if(missing(qseq))
        stop("[bamAlign] Missing query sequence string!")
    
    if(missing(qqual))
        stop("[bamAlign] Missing query quality string!")
    
    if(missing(cigar))
        stop("[bamAlign] Missing CIGAR string!")
    
    if(missing(refid))
        stop("[bamAlign] Missing refid!")
    
    if(missing(position))
        stop("[bamAlign] Missing position!")
    
    
    if(!is.character(qname))
        stop("[bamAlign] Query name must be character!")
    
    if(!is.character(qseq))
        stop("[bamAlign] Query sequence must be character!")
    
    if(!is.character(qqual))
        stop("[bamAlign] Query quality must be character!")
    
    if(nchar(qseq)!=nchar(qqual))
        stop("Query sequence string and quality string must have equal size!")
    
    
    if(!is.character(cigar))
        stop("[bamAlign] CIGAR string must be character!")
    
    if(!is.numeric(refid))
        stop("[bamAlign] refid must be numeric!")
    
    if(!is.numeric(position))
        stop("[bamAlign] position must be numeric!")
    
    refid <- as.integer(refid)
    position <- as.integer(position)
    
    # String-values:
    # 1) query-name
    # 2) query sequence
    # 3) quality string
    # 4) CIGAR string
    
    strval <- character(4)
    strval[1] <- qname
    strval[2] <- qseq
    strval[3] <- qqual
    strval[4] <- cigar
    
    # Integer-values:
    # 1) refid
    # 2) position
    # 3) flag
    # 4) align quality
    # 5) mate refid
    # 6) mate position
    # 7) insert size
    intval <- integer(4)
    intval[1] <- refid
    intval[2] <- position
    intval[3] <- flag
    intval[4] <- alqual
    intval[5] <- mrefid
    intval[6] <- mpos
    intval[7] <- insertsize
    
    ans <- .Call("bam_align_create", strval, intval)
    
    # Must be checked because align list returns NULL when end is reached
    if(is.null(ans))
    {  
        cat("[bamAlign] Align creation unsuccessful! Data inconsistency?\n")
        return(NULL)
    }
    
    return(new("bamAlign", ans))
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  bamAlign Member Reader functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="name", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_name", object@align, PACKAGE="rbamtools")
})

setMethod(f="refID", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_refid", object@align, PACKAGE="rbamtools")
})

setMethod(f="position", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_position", object@align, PACKAGE="rbamtools")
})

setMethod("nCigar", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_nCigar", object@align, PACKAGE="rbamtools")
})

setMethod(f="cigarData", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_cigar_df", object@align, PACKAGE="rbamtools")
})

setMethod(f="mateRefID", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_mate_refid", object@align, PACKAGE="rbamtools")
})

setMethod(f="matePosition", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_mate_position", object@align, PACKAGE="rbamtools")
})

setMethod(f="insertSize", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_insert_size", object@align, PACKAGE="rbamtools")
})

setMethod(f="mapQuality", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_map_quality", object@align, PACKAGE="rbamtools")
})

setMethod(f="alignSeq", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_segment_sequence", object@align, PACKAGE="rbamtools")
})

setMethod(f="alignQual", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_qualities", object@align, PACKAGE="rbamtools")
})

setMethod(f="alignQualVal", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_qual_values", object@align, PACKAGE="rbamtools")
})




# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  1.4  The alignment section: mandatory fields
#       2. FLAG: bitwise FLAG
#  Queries against alignment flag (Readers and Accessors)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x1 template having multiple segments in sequencing
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("paired", "bamAlign", function(object)
{
    .Call("bam_align_is_paired", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="paired",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_paired", 
                    object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x2 each segment properly aligned according to the aligner
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("properPair", "bamAlign", function(object)
{
    .Call("bam_align_mapped_in_proper_pair", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="properPair",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_mapped_in_proper_pair",
                    object@align, value, PACKAGE="rbamtools")
    
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x4 segment unmapped
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("unmapped", "bamAlign", function(object)
{
    .Call("bam_align_is_unmapped", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="unmapped",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_unmapped",
                    object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x8 next segment in the template unmapped
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("mateUnmapped", "bamAlign", function(object)
{
    .Call("bam_align_mate_is_unmapped", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="mateUnmapped",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_mate_is_unmapped",
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x10 SEQ being reverse complemented
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("reverseStrand", "bamAlign", function(object)
{
    .Call("bam_align_strand_reverse", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="reverseStrand",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_strand_reverse", 
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x20 SEQ of the next segment in the template being reversed
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("mateReverseStrand", "bamAlign", function(object)
{
    .Call("bam_align_mate_strand_reverse", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="mateReverseStrand",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_mate_strand_reverse",
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x40 the first segment in the template
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("firstInPair",  "bamAlign",  function(object)
{
    .Call("bam_align_is_first_in_pair", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="firstInPair", 
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("class bamReader, FirstInPair setter: value must be boolean")
     
    .Call("bam_align_set_is_first_in_pair", 
            object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x80 the last segment in the template
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("secondInPair", "bamAlign", function(object)
{
    .Call("bam_align_is_second_in_pair", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="secondInPair",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_second_in_pair", 
        object@align, value, PACKAGE="rbamtools")
                     
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x100 secondary alignment
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("secondaryAlign", "bamAlign", function(object)
{
  .Call("bam_align_is_secondary_align",object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="secondaryAlign", signature="bamAlign",
                                        definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_secondary_align", 
                    object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x200 not passing quality controls
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("failedQC", "bamAlign", function(object)
{
    return(.Call("bam_align_fail_qc", object@align, PACKAGE="rbamtools"))
})

setReplaceMethod(f="failedQC", 
        signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("class bamReader, failedQC setter: value must be boolean")
    
    .Call("bam_align_set_fail_qc", object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x400 PCR or optical duplicate
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("pcrORopt_duplicate", "bamAlign", function(object)
{
    return(.Call("bam_align_is_pcr_or_optical_dup",
                object@align, PACKAGE="rbamtools"))
})

setReplaceMethod(f="pcrORopt_duplicate",
        signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("class bamReader, Duplicate setter: value must be boolean")
    .Call("bam_align_set_is_pcr_or_optical_dup", 
                            object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x800 supplementary alignment
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("suppAlign", "bamAlign", function(object)
{
    .Call("bam_align_is_supplementary_align",object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="suppAlign",
        signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_supplementary_align", 
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  flag
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("flag", "bamAlign", function(object)
{
  .Call("bam_align_get_flag", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="flag", signature="bamAlign",
                                    definition=function(object, value)
{
    if(!is.numeric(value))
        stop("value must be numeric")
    
    if(!is.integer(value))
    {
        value <- as.integer(value)
        message("[flag] Value is coerced to integer.")
    }
    
    .Call("bam_align_set_flag", object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Queries against alignment flag (Readers and Accessors)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("countNucs","bamAlign",function(object)
{
    return(.Call("bam_align_count_nucs", object@align, PACKAGE="rbamtools"))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: bamAlign
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   coercing
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

as.data.frame.bamRange <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("bam_range_get_align_df", x@range, PACKAGE="rbamtools"))
}

as.data.frame.gapList <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("gap_list_get_df", x@list, PACKAGE="rbamtools"))
}

as.data.frame.gapSiteList <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("gap_site_list_get_df", x@list, PACKAGE="rbamtools"))
}

as.data.frame.bamGapList <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("gap_site_ll_get_df", x@list,
                                        x@refdata$SN, PACKAGE="rbamtools"))
}

as.data.frame.refSeqDict <- function(x, row.names=NULL, optional=FALSE, ...)
{
    n <- length(x@SN)
    if(n == 0)
    {
        return(data.frame(SN=character(0), LN=numeric(0), AS=character(0),
                        M5=numeric(0), SP=character(0) , UR=character(0)))
    }
    
    if(is.null(row.names))
        row.names <- 1:(length(x@SN))
    else if(length(row.names) != length(x@SN))
        stop("length(row.names)!=length(x@SN)!")
    
    return(data.frame(SN=x@SN, LN=x@LN, 
                AS=x@AS ,M5=x@M5, SP=x@SP, UR=x@UR, row.names=row.names))
}


setAs("bamRange","data.frame", function(from)
{
    return(.Call("bam_range_get_align_df", from@range, PACKAGE="rbamtools"))
})

setAs("gapList", "data.frame", function(from)
{
    return(.Call("gap_list_get_df", from@list, PACKAGE="rbamtools"))
})

setAs("refSeqDict", "data.frame", function(from)
{
    return(data.frame(SN=from@SN, LN=from@LN, AS=from@AS, M5=from@M5,
                    SP=from@SP, UR=from@UR, row.names=1:length(from@SN)))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  End: coercing
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Miscellaneous functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


createIdxBatch <- function(bam, idx=paste(bam, ".bai", sep=""), rebuild=FALSE)
{
    if(!is.character(bam))
        stop("'bam' must be character!")
    
    if(!is.character(idx))
        stop("'idx' must be character!")
    
    if(length(bam)!=length(idx))
        stop("'bam' and 'idx' must have same length!")
    
    if(!is.logical(rebuild))
        stop("'rebuild' must be logical!")
    
    if(length(rebuild) > 1)
        stop("'rebuild' must have length 1!")
    
    
    n <- length(bam)
    for(i in 1:n)
    {
        message("[", format(i, width=2), "/", n, "] ", appendLF=FALSE)
        if(!file.exists(bam[i]))
        stop("File ", i, " does not exist!")
        
        if(rebuild[1])
        {
        reader <- bamReader(bam[i])
        createIndex(reader, idx[i])
        bamClose(reader)       
        }else{
            if(!file.exists(idx[i]))
            {
                reader <- bamReader(bam[i])
                createIndex(reader, idx[i])
                bamClose(reader)     
            }
        }
        message("OK.")
    }
    return(invisible())
}

create.idx.batch <- function(bam, idx=paste(bam, ".bai", sep=""), rebuild=FALSE)
{ .Deprecated("createIdxBatch",package="rbamtools") }



countTextLines <- function(filenames)
{
    if(!is.character(filenames))
        stop("[countTextLines] filename must be character!")
    
    if(!all(file.exists(filenames)))
        stop("[countTextLines] Missing files!")
    
    n <- length(filenames)
    res <- numeric(n)
    bm <- Sys.localeconv()[7]
    
    for(i in 1:n)
    {
        cat("[countTextLines] Counting '", basename(filenames[i]), "'", sep="")
        res[i] <- .Call("count_text_lines", filenames[i])
        cat("\t found:", format(res[i], big.mark=bm), ".\n")
    }
    cat("[countTextLines] Finished. Found", 
                                format(sum(res), big.mark=bm), "lines.\n")
    return(res)
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Unexported and undocumented routines
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

readSepGapTables <- function(bam, profo, defo="sep_gap",
                                            idx=paste(bam, ".bai", sep=""))
{
    require(rbamtools)
    fo <- file.path(profo, defo)
    
    if(!file.exists(fo))
        dir.create(fo)
    bm <- Sys.localeconv()[7]
    
    n <- length(bam)
    for(i in 1:n)
    {
        cat("[readSepGapTables] i:(", format(i, width=2), "/", n, ")", sep="")
        
        if(!file.exists(bam[i]))
            stop("[readSepGapTables] i:", i, " File does not exist!")
        
        reader <- bamReader(bam[i])
        
        if(!file.exists(idx[i]))
            createIndex(reader, idx[i])
        
        loadIndex(reader, idx[i])
        
        if(i==1)
        {
            bsl <- bamGapList(reader)
            dfr <- as.data.frame(bsl)
            save(dfr, file=file.path(fo, paste("bsl_", i, ".RData", sep="")))
            write.table(dfr, file=file.path(fo, 
                paste("bsl_", i, ".csv", sep="")), sep=";", row.names=FALSE)
            
            cat("\r[readSepGapTables] i:(", format(i, width=2),
                "/", n, ")\tnr sites: ", format(size(bsl), big.mark=bm,
                                                width=9), "\n", sep="")
            
        }else{
            # save site-table for bam[i]
            bsli <- bamGapList(reader)
            dfri <- as.data.frame(bsli)
            save(dfri, file=file.path(fo, paste("bsl_", i, ".RData", sep="")))
            write.table(dfri, file=file.path(fo, paste("bsl_", i, ".csv", sep="")), 
                                                    sep=";", row.names=FALSE)
            
            # save cum-merged site-table for bam[i]
            bsl <- merge(bsl, bsli)
            dfr <- as.data.frame(bsl)
            
            save(dfr, file=file.path(fo, paste("bsl_c_", i, ".RData", sep="")))
            
            write.table(dfr, file=file.path(fo, paste("bsl_c_", i, 
                    ".csv", sep="")), sep=";", row.names=FALSE)
            
            cat("\r[readSepGapTables] i:(", format(i, width=2),
                "/", n, ")\tnr sites: ",  format(size(bsl), big.mark=bm,
                                                width=9), "\n", sep="")
        }
    }
    cat("[readSepGapTables] Finished.")
}

#  Unexported and undocumented
readAccGapTables <- function(bam, profo, defo="sep_gap",
                                            idx=paste(bam, ".bai", sep=""))
{
    # setup
    require(rbamtools)
    fo <- file.path(profo, defo)
    
    if(!file.exists(fo))
        dir.create(fo)
    
    bm <- Sys.localeconv()[7]
    
    n <- length(bam)
    res <- data.frame(i=1:n, sites=numeric(n), acc=numeric(n), nov=numeric(n))
    
    for(i in 1:n)
    {
        cat("[readAccGapTables] i:(", format(i, width=2), "/", n, ")", sep="")
        
        if(!file.exists(bam[i]))
            stop("[readAccGapTables] i:", i, " File does not exist!")
        
        reader <- bamReader(bam[i])
        if(!file.exists(idx[i]))
            createIndex(reader, idx[i])
        loadIndex(reader, idx[i])
        
        if(i==1) # first bam file
        {
            bsl <- bamGapList(reader)
            dfr <- as.data.frame(bsl)
            save(dfr, file=file.path(fo, paste("bsl_", i, ".RData", sep="")))
            
            # write report values
            res$sites[1] <- dim(dfr)[1]
            res$acc[1] <- res$sites[1]
            res$nov[1] <- res$sites[1]
            
            # printout status line
            cat("\r[readAccGapTables] i:(", format(i, width=2),
                "/", n, ")\tnr sites: ",  format(size(bsl), big.mark=bm,
                                                width=9), "\n", sep="")
            
        }else{    # subsequent bam file
            
            # read sites from bam[i]
            bsli <- bamGapList(reader)
            dfri <- as.data.frame(bsli)
            
            # extract novel sites as difference from accumulated sites
            mrg <- merge(dfri[, c("id", "seqid", "lend", "rstart")], 
                        dfr[, c("id", "seqid", "lend", "rstart")], 
                        by=c("seqid", "lend", "rstart"), all.x=TRUE)
            
            mrg$new <- is.na(mrg$id.y)
            mrg$id.x <- NULL
            mrg$id.y <- NULL
            nov <- merge(dfri, mrg, all=T)
            nov <- nov[nov$new, c(4, 1, 5, 2, 3, 6:13)]
            nov$new <- NULL
            nov <- nov[order(nov$seqid, nov$lend, nov$rstart), ]
            
            # Save image
            save(dfri, nov, dfr , file=file.path(fo, paste("acc_", i,
                                                        ".RData", sep="")))
            
            # create new accumulation via merging
            bsl <- merge(bsl, bsli)
            dfr <- as.data.frame(bsl)
            
            # write report values
            res$sites[i] <- dim(dfri)[1]
            res$acc[i] <- dim(dfr)[1]
            res$nov[i] <- dim(nov)[1]
            
            # print-out status line
            cat("\r[readAccGapTables] i:(", format(i, width=2), "/", n,
                ")\tnr sites: ", format(size(bsl), big.mark=bm, width=9),
                                "\n", sep="")
        }
    }
    
    # save final image
    save(dfr, file=file.path(fo, "bsl_acc_final.RData"))
    
    cat("[readAccGapTables] Final sites: ", 
                            format(size(bsl), big.mark=bm, width=9), "\n")
    
    return(res)
}

#  Unexported and undocumented
copy_fastq <- function(infile, outfile, which, append=FALSE)
{
    if(!is.character(infile))
        stop("[copy_fastq] infile must be character!")
    
    if(!is.character(outfile))
        stop("[copy_fastq] outfile must be character!")
    
    if(!is.numeric(which))
        stop("[copy_fastq] which must be numeric!")
    
    if(any(which<=0))
        stop("[copy_fastq] Only positive numbers in which allowed!")
    
    which <- as.integer(sort(unique(which)))
    if(!is.logical(append))
        stop("[copy_fastq] append must be logical!")
    
    if(!file.exists(infile))
        stop("[copy_fastq] infile does not exist!")
    
    ans <- .Call("copy_fastq_records", infile, outfile, which,
                                            append, PACKAGE="rbamtools")
    
    bm <- Sys.localeconv()[7]
    
    if(length(which)<ans){
        cat("[copy_fastq] Incomplete copy: ", format(ans, big.mark=bm), "/", 
                format(length(which), big.mark=bm), ". EOF reached?", sep="")
    }
    return(invisible(ans))
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Function declaration for extraction of regions into separate BAM files:
#
# Extracts alignments from given (genetic) ranges and BAM files
# into a set of output BAM files.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

extractBamRegions <- function(bamFiles, ranges,
                idxFiles=paste(bamFiles, "bai", sep="."),
                outFiles=paste("bam", 1:length(bamFiles),".bam", sep=""))
{
    if(!is.character(bamFiles))
        stop("'bamFiles' must be character!")
    
    if(!is.character(idxFiles))
        stop("'idxFiles' must be character!")
    
    if(!is.character(outFiles))
        stop("'outFiles' must be character!")
    
    if(!all(file.exists(bamFiles)))
        stop("bam file(s) not found!")
    
    if(!all(file.exists(idxFiles)))
        stop("idx file(s) not found!")
    
    if(length(bamFiles) != length(idxFiles))
        stop("bamFiles and idxFiles must have equal length!")
    
    if(length(bamFiles) != length(outFiles))
        stop("bamFiles and outFiles must have equal length!")
    
    if(!all(ranges$end > ranges$start))
        stop("All 'end' positions must be greater than 'start'!")
    
    
    nr <- nrow(ranges)
    nf <- length(bamFiles)
    
    for(i in 1:nf)
    {
        reader <- bamReader(bamFiles[i], idx=TRUE)
        cat("[i] ", format(i, width=2), "\n")
        header <- getHeader(reader)
        writer <- bamWriter(header, outFiles[i])
        
        for(j in 1:nr)
        {
            sn <- getRefCoords(reader,as.character(ranges$seqid[j]))
            coords <- c(sn[1], ranges$start[j], ranges$end[j])
            brg <- bamRange(reader, coords)
            bamSave(writer, brg, refid=sn[1])        
        }
        bamClose(reader)
        bamClose(writer)
    }
    return(invisible())
}



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  End of File (rbamtools.r)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
`%||%` <- function(x, y) if (is.null(x)) y else x

#' Merge two lists and overwrite latter entries with former entries
#' if names are the same.
#'
#' For example, \code{list_merge(list(a = 1, b = 2), list(b = 3, c = 4))}
#' will be \code{list(a = 1, b = 3, c = 4)}.
#' @param list1 list
#' @param list2 list
#' @return the merged list.
#' @examples
#' stopifnot(identical(syberiaStages:::list_merge(list(a = 1, b = 2), list(b = 3, c = 4)),
#'                     list(a = 1, b = 3, c = 4)))
#' stopifnot(identical(syberiaStages:::list_merge(NULL, list(a = 1)), list(a = 1)))
# TODO: (RK) This is a duplicate of the function in mungebits -- is there
# any way to pull them out into one place? Maybe Ramd?
list_merge <- function(list1, list2) {
  list1 <- list1 %||% list()
  # Pre-allocate memory to make this slightly faster.
  list1[Filter(function(x) nchar(x) > 0, names(list2) %||% c())] <- NULL
  for (i in seq_along(list2)) {
    name <- names(list2)[i]
    if (!identical(name, NULL) && !identical(name, "")) list1[[name]] <- list2[[i]]
    else list1 <- append(list1, list(list2[[i]]))
  }
  list1
}

#' Parse functions out of a custom resource.
#'
#' @param functions character. The names of functions to parse out.
#' @param provided_env environment. The environment the resource was loaded from.
#' @param type character. The keyword for the resource.
#' @param resource_type character. The type of the resource (e.g., "classifier",
#'   "adapter", etc.). This will be used to generate error messages.
#' @param strict logical. Whether or not to error if the functions are not found.
#' @return a list containing keys same as the \code{functions} argument.
#'    and predict functions.
parse_custom_functions <- function(functions, provided_env, type,
                                   resource_type = 'classifier', strict = TRUE) {
  provided_fns <- setNames(vector('list', length(functions)), functions)
  for (function_type in names(provided_fns)) {
    fn <- Filter(
      function(x) is.function(provided_env[[x]]),
      grep(function_type, ls(provided_env), value = TRUE)
    )
    # TODO: (RK) Refactor this to be more careful about idempotent resources.
    error <- function(snip = 'a') paste0("The custom ", resource_type, " in ",
      "lib/", resource_type, "s/", type, ".R should define ", snip, " '",
      testthat::colourise(function_type, 'green'), "' function.")
    if (length(fn) == 0 && identical(strict, TRUE)) stop(error(), call. = FALSE)
    else if (length(fn) > 1)
      stop(error('only one'), " Instead, you defined ", length(fn), ", namely: ",
           paste0(fn, collapse = ', '), call. = FALSE)
    else if (length(fn) == 1)
      provided_fns[[function_type]] <- provided_env[[fn]]
  }
  provided_fns
}

# Helper function to serialize a tundraContainer of xgboost model object
#
# TODO: (RK) Refactor this function out of the package.
serialize_xgb_object <- function(object) {
	file_save <- tempfile()
  on.exit(unlink(file_save))
  xgboost::xgb.save(object$output$model, file_save)
  stopifnot(!is.na(as.integer(file.info(file_save)$size)))
  object$output$model <- NULL
  con <- file(file_save, 'rb')
  on.exit(close(con), add = TRUE)
  invisible(structure(
    class = 'special_serialized_object', 
    list(
      deserialize = function(x) {
        file_load <- tempfile()
        on.exit(unlink(file_load))
        con <- file(file_load, 'wb')
        on.exit(close(con), add = TRUE)
        writeBin(x$xgb.bin, con, useBytes = TRUE)
        x$container$output$model <- xgboost::xgb.load(file_load)
        invisible(x$container)
      }, 
      object = list(
       container = object, 
       xgb.bin = readBin(con, raw(), n = file.info(file_save)$size)
      )
    )
  ))
}

#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()
    if (is(object, 'tundraContainer') &&
        # Hack for model object requiring customized
        # serializer, e.g., xgb.Booster
        is(object$output$model, 'xgb.Booster')) {
      file_save <- tempfile()
      on.exit(unlink(file_save))
      xgboost::xgb.save(object$output$model, file_save)
      stopifnot(!is.na(as.integer(file.info(file_save)$size)))
      object$output$model <- NULL
      con <- file(file_save, 'rb')
      on.exit(close(con), add = TRUE)
      object <- structure(class = 'special_serialized_object', list(
                  deserialize = function(x) {
                    file_load <- tempfile()
                    on.exit(unlink(file_load))
                    con <- file(file_load, 'wb')
                    on.exit(close(con), add = TRUE)
                    writeBin(x$xgb.bin, con, useBytes = TRUE)
                    close(con)
                    x$container$output$model <- xgboost::xgb.load(file_load)
                    x$container
                  }, object = list(container = object, xgb.bin = readBin(con, raw(), n = file.info(file_save)$size)))
                )
      close(con)
    }
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Native function specs"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0.
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Note: [
		"Used to generates C enums and tables"
		"Boot bind attributes are SET and not DEEP"
		"Todo: before beta release remove extra/unused refinements"
	]
]

;-- Control Natives - nat_control.c

ajoin: native [
	{Reduces and joins a block of values into a new string.}
	block [block!]
]

also: native [
	{Returns the first value, but also evaluates the second.}
	value1 [any-type!]
	value2 [any-type!]
]

all: native [
	{Shortcut AND. Evaluates and returns at the first FALSE or NONE.}
	block [block!] {Block of expressions}
]

any: native [
	{Shortcut OR. Evaluates and returns the first value that is not FALSE or NONE.}
	block [block!] {Block of expressions}
]

apply: native [
	{Apply a function to a reduced block of arguments.}
	func [any-function!] "Function value to apply"
	block [block!] "Block of args, reduced first (unless /only)"
	/only "Use arg values as-is, do not reduce the block"
]

assert: native [
	"Assert that condition is true, else cause an assertion error."
	conditions [block!]
	/type "Safely check datatypes of variables (words and paths)"
]

attempt: native [
	"Tries to evaluate a block and returns result or NONE on error."
	block [block!]
]

break: native [
	{Breaks out of a loop, while, until, repeat, foreach, etc.}
	/return {Forces the loop function to return a value}
	value [any-type!]
]

case: native [
	{Evaluates each condition, and when true, evaluates what follows it.}
	block [block!] {Block of cases (conditions followed by values)}
	/all {Evaluate all cases (do not stop at first true case)}
]

catch: native [
	{Catches a throw from a block and returns its value.}
	block [block!] {Block to evaluate}
	/name {Catches a named throw}
	word [word! block!] {One or more names}
	/quit {Special catch for QUIT native}
]

;cause: native [
;	{Force error processing on an error value.}
;	error [error!]
;]

comment: native [
	{Ignores the argument value and returns nothing.}
	value {A string, block, file, etc.}
]

compose: native [
	{Evaluates a block of expressions, only evaluating parens, and returns a block.}
	value "Block to compose"
	/deep "Compose nested blocks"
	/only {Insert a block as a single value (not the contents of the block)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

context: native [
	{Creates an object.}
	spec ; [block!] -- no check required, we know it is correct
]

continue: native [
	{Throws control back to top of loop.}
]

;dir?: native [
;	{Returns true if file is a directory.}
;	file [any-string! none!]
;	/any {Allow * or ? wildcards for directory}
;]

;disarm: native [
;	{(Deprecated - not needed) Converts error to an object. Other types not modified.}
;	error [any-type!]
;]

do: native [
	{Evaluates a block, file, URL, function, word, or any other value.}
	value [any-type!] "Normally a file name, URL, or block"
	/args "If value is a script, this will set its system/script/args"
	arg   "Args passed to a script (normally a string)"
	/next "Do next expression only, return it, update block variable"
	var [word!] "Variable updated with new block position"
]

;eval: native [
;	{Evaluates a block, file, URL, function, word, or any other value.}
;	value "Normally a file name, URL, or block"
;]

either: native [
	{If TRUE condition return first arg, else second; evaluate blocks by default.}
	condition
	true-branch
	false-branch
	/only "Suppress evaluation of block args."
]

exit: native [
	{Exits a function, returning no value.}
]

find-script: native [
	{Find a script header within a binary string. Returns starting position.}
	script [binary!]
]

for: native [
	{Evaluate a block over a range of values. (See also: REPEAT)}
	'word [word!] "Variable to hold current value"
	start [series! number!] "Starting value"
	end   [series! number!] "Ending value"
	bump  [number!] "Amount to skip each time"
	body  [block!] "Block to evaluate"
]

forall: native [
	"Evaluates a block for every value in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	body [block!] "Block to evaluate each time"
]

forever: native [
	{Evaluates a block endlessly.}
	body [block!] {Block to evaluate each time}
]

foreach: native [
	{Evaluates a block for each value(s) in a series.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series! any-object! map! none!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

forskip: native [
	"Evaluates a block for periodic values in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	size [integer! decimal!] "Number of positions to skip each time"
	body [block!] "Block to evaluate each time"
	/local orig result
]

halt: native [
	{Stops evaluation and returns to the input prompt.}
]

if: native [
	{If TRUE condition, return arg; evaluate block args by default}
	condition
	true-branch
	/else "If FALSE condition, return second arg; evaluate block by default"
	false-branch
	/only "Suppress evaluation of block args."
]

loop: native [
	{Evaluates a block a specified number of times.}
	count [number!] {Number of repetitions}
	block [block!] {Block to evaluate}
]

map-each: native [
	{Evaluates a block for each value(s) in a series and returns them as a block.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [block! vector!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

;replace-all: native [
;	"Search and replace multiple values with a series; returns a new series."
;	target [block! string! binary!]
;	values [block!] "A block of [old new] search/replace pairs"
;]

quit: native [
	{Stops evaluation and exits the interpreter.}
	/return {Returns a value (to prior script or command shell)}
	value {Note: use integers for command shell}
	/now {Quit immediately}
]

protect: native [
	"Protect a series or a variable from being modified."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series/objects as well"
	/words  "Process list as words (and path words)"
	/values "Process list of values (implied GET)"
	/hide "Hide variables (avoid binding and lookup)"
]

unprotect: native [
	"Unprotect a series or a variable (it can again be modified)."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series as well"
	/words "Block is a list of words"
	/values "Process list of values (implied GET)"
]

recycle: native [
	{Recycles unused memory.}
	/off {Disable auto-recycling}
	/on {Enable auto-recycling}
	/ballast {Trigger for auto-recycle (memory used)}
	size [integer!]
	/torture {Constant recycle (for internal debugging)}
]

reduce: native [
	{Evaluates expressions and returns multiple results.}
	value
	/no-set {Keep set-words as-is. Do not set them.}
	/only {Only evaluate words and paths, not functions}
	words [block! none!] {Optional words that are not evaluated (keywords)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

repeat: native [
	{Evaluates a block a number of times or over a series.}
	'word [word!] {Word to set each time}
	value [number! series! none!] {Maximum number or series to traverse}
	body [block!] {Block to evaluate each time}
]

remove-each: native [
	{Removes values for each block that returns true; returns removal count.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series!] {The series to traverse (modified)}
	body [block!] {Block to evaluate (return TRUE to remove)}
]

return: native [
	{Returns a value from a function.}
	value [any-type!]
	/redo {Upon return, re-evaluate the returned result. (Used for DO)}
]

switch: native [
	"Selects a choice and evaluates the block that follows it."
	value "Target value"
	cases [block!] "Block of cases to check"
	/default case "Default case if no others found"
	/all "Evaluate all matches (not just first one)"
]

throw: native [
	{Throws control back to a previous catch.}
	value [any-type!] {Value returned from catch}
	/name {Throws to a named catch}
	word [word!]
]

trace: native [
	{Enables and disables evaluation tracing and backtrace.}
	mode [integer! logic!]
	/back {Set mode ON to enable or integer for lines to display}
	/function {Traces functions only (less output)}
;	/stack {Show stack index}
]

try: native [
	{Tries to DO a block and returns its value or an error.}
	block [block!]
	/except "On exception, evaluate this code block"
	code [block! any-function!]
]

unless: native [
	{If FALSE condition, return arg; evaluate block args by default.}
	condition
	false-branch
	/only "Suppress evaluation of block args."
]

until: native [
	{Evaluates a block until it is TRUE. }
	block [block!]
]

while: native [
	{While a condition block is TRUE, evaluates another block.}
	cond-block [block!]
	body-block [block!]
]

;-- Data Natives - nat_data.c

;alias: native [
;	See CC#1835
;	{Creates an alternate spelling for a word.}
;	word [word!] {Word to alias}
;	name [string!] {Name of alias}
;]

;as-binary: native [
;	{Coerces any type of string into a binary! datatype without copying it.}
;	string [any-string!]
;]
;
;as-string: native [
;	{Coerces any type of string into a string! datatype without copying it.}
;	string [any-string!]
;]

bind: native [
	{Binds words to the specified context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	context [any-word! any-object!] {A reference to the target context}
	/copy {Bind and return a deep copy of a block, don't modify original}
	/only {Bind only first block (not deep)}
	/new {Add to context any new words found}
	/set {Add to context any new set-words found}
]

unbind: native [
	{Unbinds words from context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	/deep "Process nested blocks"
]

bound?: native [
	{Returns the context in which a word is bound.}
	word [any-word!]
]

collect-words: native [
	"Collect unique words used in a block (used for context construction)."
	block [block!]
	/deep "Include nested blocks"
	/set "Only include set-words"
	/ignore "Ignore prior words"
	words [any-object! block! none!] "Words to ignore"
]

checksum: native [
	{Computes a checksum, CRC, or hash.}
	data [binary!] {Bytes to checksum}
	/part length {Length of data}
	/tcp {Returns an Internet TCP 16-bit checksum}
	/secure {Returns a cryptographically secure checksum}
	/hash {Returns a hash value}
	size [integer!] {Size of the hash table}
	/method {Method to use}
	word [word!] {Methods: SHA1 MD5 CRC32}
	/key {Returns keyed HMAC value}
	key-value [any-string!] {Key to use}
]

compress: native [
	{Compresses a string series and returns it.}
	data [binary! string!] {If string, it will be UTF8 encoded}
	/part length {Length of data (elements)}
	/gzip {Use GZIP checksum}
]

decompress: native [
	{Decompresses data. Result is binary.}
	data [binary!] {Data to decompress}
	/part length {Length of compressed data (must match end marker)}
	/gzip {Use GZIP checksum}
	/limit size {Error out if result is larger than this}
]

construct: native [
	{Creates an object with scant (safe) evaluation.}
	block [block! string! binary!] "Specification (modified)"
	/with "Default object" object [object!]
	/only "Values are kept as-is"
]

debase: native [
	{Decodes binary-coded string (BASE-64 default) to binary value.}
	value [binary! string!] {The string to decode}
	/base {Binary base to use}
	base-value [integer!] {The base to convert from: 64, 16, or 2}
]

enbase: native [
	{Encodes a string into a binary-coded string (BASE-64 default).}
	value [binary! string!] {If string, will be UTF8 encoded}
	/base {Binary base to use}
	base-value [integer!] {The base to convert to: 64, 16, or 2}
]

decloak: native [
	{Decodes a binary string scrambled previously by encloak.}
	data [binary!] "Binary series to descramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

encloak: native [
	{Scrambles a binary string based on a key.}
	data [binary!] "Binary series to scramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

deline: native [
	"Converts string terminators to standard format, e.g. CRLF to LF."
	string [any-string!] {(modified)}
	/lines "Return block of lines (works for LF, CR, CR-LF endings) (no modify)"
]

enline: native [
	"Converts string terminators to native OS format, e.g. LF to CRLF."
	series [any-string! block!] {(modified)}
]

detab: native [
	"Converts tabs to spaces (default tab size is 4)."
	string [any-string!] {(modified)}
	/size  "Specifies the number of spaces per tab"
	number [integer!]
]

entab: native [
	"Converts spaces to tabs (default tab size is 4)."
	string [any-string!] {(modified)}
	/size "Specifies the number of spaces per tab"
	number [integer!]
]

delect: native [
	"Parses a common form of dialects. Returns updated input block."
	 dialect [object!] "Describes the words and datatypes of the dialect"
	 input [block!] "Input stream to parse"
	 output [block!] "Resulting values, ordered as defined (modified)"
	 /in "Search for var words in specific objects (contexts)"
	 where [block!] "Block of objects to search (non objects ignored)"
	 /all "Parse entire block, not just one command at a time"
]

difference: native [
	{Returns the special difference of two values.}
	set1 [block! string! binary! bitset! date! typeset!] "First data set"
	set2 [block! string! binary! bitset! date! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

exclude: native [
	{Returns the first data set less the second data set.}
	set1 [block! string! binary! bitset! typeset!] "First data set"
	set2 [block! string! binary! bitset! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

intersect: native [
	{Returns the intersection of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

union: native [
	{Returns the union of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Use case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

unique: native [
	{Returns the data set with duplicates removed.}
	set1 [block! string! binary! bitset! typeset!]
	/case  {Use case-sensitive comparison (except bitsets)}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

lowercase: native [
	"Converts string of characters to lowercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

uppercase: native [
	"Converts string of characters to uppercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

dehex: native [
	{Converts URL-style hex encoded (%xx) strings.}
	value [any-string!] {The string to dehex}
]

get: native [
	{Gets the value of a word or path, or values of an object.}
	word {Word, path, object to get}
	/any {Allows word to have no value (allows unset)}
]

in: native [
	{Returns the word or block in the object's context.}
	object [any-object! block!]
	word [any-word! block! paren!]  {(modified if series)}
]

parse: native [
	{Parses a string or block series according to grammar rules.}
	input [series!] {Input series to parse}
	rules [block! string! char! none!] {Rules to parse by (none = ",;")}
	/all {For simple rules (not blocks) parse all chars including whitespace}
	/case {Uses case-sensitive comparison}
]

set: native [
	{Sets a word, path, block of words, or object to specified value(s).}
	word [any-word! any-path! block! object!] {Word, block of words, path, or object to be set (modified)}
	value [any-type!] {Value or block of values}
	/any {Allows setting words to any value, including unset}
	/pad {For objects, if block is too short, remaining words are set to NONE}
]

to-hex: native [
	{Converts numeric value to a hex issue! datatype (with leading # and 0's).}
	value [integer! tuple!] {Value to be converted}
	/size {Specify number of hex digits in result}
	len [integer!]
]

type?: native [
	{Returns the datatype of a value.}
	value [any-type!]
	/word {Returns the datatype as a word}
]

unset: native [
	{Unsets the value of a word (in its current context.)}
	word [word! block!] {Word or block of words}
]

utf?: native [
	{Returns UTF BOM (byte order marker) encoding; + for BE, - for LE.}
	data [binary!]
]

invalid-utf?: native [
	{Checks UTF encoding; if correct, returns none else position of error.}
	data [binary!]
	/utf "Check encodings other than UTF-8"
	num [integer!] "Bit size - positive for BE negative for LE"
]

value?: native [
	{Returns TRUE if the word has a value.}
	value
]

;-- IO Natives - nat_io.c

print: native [
	{Outputs a value followed by a line break.}
	value [any-type!] {The value to print}
]

prin: native [
	{Outputs a value with no line break.}
	value [any-type!]
]

mold: native [
	{Converts a value to a REBOL-readable string.}
	value [any-type!] {The value to mold}
	/only {For a block value, mold only its contents, no outer []}
	/all  {Use construction syntax}
	/flat {No indentation}
]

form: native [
	{Converts a value to a human-readable string.}
	value [any-type!] {The value to form}
]

new-line: native [
	{Sets or clears the new-line marker within a block or paren.}
	position [block! paren!] {Position to change marker (modified)}
	value {Set TRUE for newline}
	/all {Set/clear marker to end of series}
	/skip {Set/clear marker periodically to the end of the series}
	size [integer!]
]

new-line?: native [
	{Returns the state of the new-line marker within a block or paren.}
	position [block! paren!] {Position to check marker}
]

to-local-file: native [
	{Converts a REBOL file path to the local system file path.}
	path [file! string!]
	/full "Prepends current dir for full path (for relative paths only)"
]

to-rebol-file: native [
	{Converts a local system file path to a REBOL file path.}
	path [file! string!]
]

transcode: native [
	{Translates UTF-8 binary source to values. Returns [value binary].}
	source [binary!] "Must be Unicode UTF-8 encoded"
	/next "Translate next complete value (blocks as single value)"
	/only "Translate only a single value (blocks dissected)"
	/error "Do not cause errors - return error object as value in place"
]

echo: native [
    {Copies console output to a file.}
    target [file! none! logic!]
]

now: native [
	{Returns date and time.}
	/year {Returns year only}
	/month {Returns month only}
	/day {Returns day of the month only}
	/time {Returns time only}
	/zone {Returns time zone offset from UCT (GMT) only}
	/date {Returns date only}
	/weekday {Returns day of the week as integer (Monday is day 1)}
	/yearday {Returns day of the year (Julian)}
	/precise {High precision time}
	/utc {Universal time (no zone)}
]

wait: native [
	{Waits for a duration, port, or both.}
	value [number! time! port! block! none!]
	/all {Returns all in a block}
	/only {only check for ports given in the block to this function}
]

wake-up: native [
	{Awake and update a port with event.}
	port [port!]
	event [event!]
]

what-dir: native ["Returns the current directory path."]

change-dir: native [
	"Changes the current directory path."
	path [file!]
]

;-- Series Natives

first: native [
	{Returns the first value of a series.}
	value
]

second: native [
	{Returns the second value of a series.}
	value
]

third: native [
	{Returns the third value of a series.}
	value
]

fourth: native [
	{Returns the fourth value of a series.}
	value
]

fifth: native [
	{Returns the fifth value of a series.}
	value
]

sixth: native [
	{Returns the sixth value of a series.}
	value
]

seventh: native [
	{Returns the seventh value of a series.}
	value
]

eighth: native [
	{Returns the eighth value of a series.}
	value
]

ninth: native [
	{Returns the ninth value of a series.}
	value
]

tenth: native [
	{Returns the tenth value of a series.}
	value
]

last: native [
	{Returns the last value of a series.}
	value [series! tuple! gob!]
]

;-- Math Natives - nat_math.c

cosine: native [
	{Returns the trigonometric cosine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

sine: native [
	{Returns the trigonometric sine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

tangent: native [
	{Returns the trigonometric tangent.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

arccosine: native [
	{Returns the trigonometric arccosine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arcsine: native [
	{Returns the trigonometric arcsine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arctangent: native [
	{Returns the trigonometric arctangent (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

exp: native [
	{Raises E (the base of natural logarithm) to the power specified}
	power [number!]
]

log-10: native [
	{Returns the base-10 logarithm.}
	value [number!]
]

log-2: native [
	{Return the base-2 logarithm.}
	value [number!]
]

log-e: native [
	{Returns the natural (base-E) logarithm of the given value} 
	value [number!]
]

not: native [
	{Returns the logic complement.}
	value {(Only FALSE and NONE return TRUE)}
]

square-root: native [
	{Returns the square root of a number.}
	value [number!]
]

shift: native [
	{Shifts an integer left or right by a number of bits.}
	value [integer!]
	bits [integer!] "Positive for left shift, negative for right shift"
	/logical "Logical shift (sign bit ignored)"
]

;-- New, hackish stuff:

++: native [
	{Increment an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

--: native [
	{Decrement an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

first+: native [
	{Return the FIRST of a series then increment the series index.}
	'word [word!] "Word must refer to a series"
]

stack: native [
	{Returns stack backtrace or other values.}
	offset [integer!] "Relative backward offset"
	/block "Block evaluation position"
	/word "Function or object name, if known"
	/func "Function value"
	/args "Block of args (may be modified)"
	/size "Current stack size (in value units)"
	/depth "Stack depth (frames)"
	/limit "Stack bounds (auto expanding)"
]

resolve: native [
	{Copy context by setting values in the target from those in the source.}
	target [any-object!] {(modified)}
	source [any-object!]
	/only from [block! integer!] "Only specific words (exports) or new words in target (index to tail)"
	/all "Set all words, even those in the target that already have a value"
	/extend "Add source words to the target if necessary"
]

;in-context: native [
;	{Set the default context for global words.}
;	context [object!]
;]

get-env: native [
	{Returns the value of an OS environment variable (for current process).}
	var [any-string! any-word!]
]

set-env: native [
	{Sets the value of an operating system environment variable (for current process).} 
	var [any-string! any-word!] "Variable to set" 
	value [string!  none!] "Value to set, or NONE to unset it"
]

list-env: native [
	{Returns a map of OS environment variables (for current process).}
]

call: native [
	{Run another program; return immediately.}
	command [string! block! file!] "An OS-local command line (quoted as necessary), a block with arguments, or an executable file"
	/wait "Wait for command to terminate before returning"
	/console "Runs command with I/O redirected to console"
	/shell "Forces command to be run from shell"
	/info "Returns process information object"
	/input in [string! binary! file! none!] "Redirects stdin to in"
	/output out [string! binary! file! none!] "Redirects stdout to out"
	/error err [string! binary! file! none!] "Redirects stderr to err"
]

browse: native [
	{Open web browser to a URL or local file.}
	url [url! file! none!]
]

evoke: native [
	{Special guru meditations. (Not for beginners.)}
	chant [word! block! integer!] "Single or block of words ('? to list)"
]

request-file: native [
	{Asks user to select a file and returns full file path (or block of paths).}
	/save "File save mode"
	/multi "Allows multiple file selection, returned as a block"
	/file name [file!] "Default file name or directory"
	/title text [string!] "Window title"
	/filter list [block!] "Block of filters (filter-name filter)"
]

ascii?: native [
	{Returns TRUE if value or string is in ASCII character range (below 128).}
	value [any-string! char! integer!]
]

latin1?: native [
	{Returns TRUE if value or string is in Latin-1 character range (below 256).}
	value [any-string! char! integer!]
]

; Temps...

stats: native [
	{Provides status and statistics information about the interpreter.}
	/show {Print formatted results to console}
	/profile {Returns profiler object}
	/timer {High resolution time difference from start}
	/evals {Number of values evaluated by interpreter}
	/dump-series pool-id [integer!] {Dump all series in pool pool-id, -1 for all pools}
]

do-codec: native [
	{Evaluate a CODEC function to encode or decode media types.}
	handle [handle!] "Internal link to codec"
	action [word!] "Decode, encode, identify"
	data [binary! image!]
]

set-scheme: native [
	"Low-level port scheme actor initialization."
	scheme [object!]
]

load-extension: native [
	"Low level extension module loader (for DLLs)."
	name [file! binary!] "DLL file or UTF-8 source"
	/dispatch "Specify native command dispatch (from hosted extensions)"
	function [handle!] "Command dispatcher (native)"
]

do-commands: native [
	"Evaluate a block of extension module command functions (special evaluation rules.)"
	commands [block!] "Series of commands and their arguments"
]

ds: native ["Temporary stack debug"]
dump: native ["Temporary debug dump" v]
check: native ["Temporary series debug check" val [series!]]

do-callback: native [
	"Internal function to process callback events."
	event [event!] "Callback event"
]


limit-usage: native [
	"Set a usage limit only once (used for SECURE)."
	field [word!] "eval (count) or memory (bytes)"
	limit [number!]
]

selfless?: native [
    "Returns true if the context doesn't bind 'self."
    context [any-word! any-object!] "A reference to the target context"
]

map-event: native [
	"Returns event with inner-most graphical object and coordinate."
	event [event!]
]

map-gob-offset: native [
	"Translates a gob and offset to the deepest gob and offset in it, returned as a block."
	gob [gob!] "Starting object"
	xy [pair!] "Staring offset"
	/reverse "Translate from deeper gob to top gob."
]

as-pair: native [
	"Combine X and Y values into a pair."
	x [number!]
	y [number!]
]

;read-file: native [f [file!]]

equal?: native [
	{Returns TRUE if the values are equal.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equal?: native [
	{Returns TRUE if the values are not equal.}
	value1 [any-type!]
	value2 [any-type!]
]

equiv?: native [
	{Returns TRUE if the values are equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equiv?: native [
	{Returns TRUE if the values are not equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-equal?: native [
	{Returns TRUE if the values are strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-not-equal?: native [
	{Returns TRUE if the values are not strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

same?: native [
	{Returns TRUE if the values are identical.}
	value1 [any-type!]
	value2 [any-type!]
]

greater?: native [ ; Note: some datatypes expect >, <, >=, <= to be in this order.
	{Returns TRUE if the first value is greater than the second value.}
	value1 value2
]

greater-or-equal?: native [
	{Returns TRUE if the first value is greater than or equal to the second value.}
	value1 value2
]

lesser?: native [
	{Returns TRUE if the first value is less than the second value.}
	value1 value2
]

lesser-or-equal?: native [
	{Returns TRUE if the first value is less than or equal to the second value.}
	value1 value2
]

minimum: native [
	{Returns the lesser of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

maximum: native [ ; Note: Some datatypes expect all binary ops to be <= this
	{Returns the greater of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

negative?: native [
	{Returns TRUE if the number is negative.}
	number [number! money! time! pair!]
]

positive?: native [
	{Returns TRUE if the value is positive.}
	number [number! money! time! pair!]
]

zero?: native [
	{Returns TRUE if the value is zero (for its datatype).}
	value
]
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Native function specs"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0.
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Note: [
		"Used to generates C enums and tables"
		"Boot bind attributes are SET and not DEEP"
		"Todo: before beta release remove extra/unused refinements"
	]
]

;-- Control Natives - nat_control.c

ajoin: native [
	{Reduces and joins a block of values into a new string.}
	block [block!]
]

also: native [
	{Returns the first value, but also evaluates the second.}
	value1 [any-type!]
	value2 [any-type!]
]

all: native [
	{Shortcut AND. Evaluates and returns at the first FALSE or NONE.}
	block [block!] {Block of expressions}
]

any: native [
	{Shortcut OR. Evaluates and returns the first value that is not FALSE or NONE.}
	block [block!] {Block of expressions}
]

apply: native [
	{Apply a function to a reduced block of arguments.}
	func [any-function!] "Function value to apply"
	block [block!] "Block of args, reduced first (unless /only)"
	/only "Use arg values as-is, do not reduce the block"
]

assert: native [
	"Assert that condition is true, else cause an assertion error."
	conditions [block!]
	/type "Safely check datatypes of variables (words and paths)"
]

attempt: native [
	"Tries to evaluate a block and returns result or NONE on error."
	block [block!]
]

break: native [
	{Breaks out of a loop, while, until, repeat, foreach, etc.}
	/return {Forces the loop function to return a value}
	value [any-type!]
]

case: native [
	{Evaluates each condition, and when true, evaluates what follows it.}
	block [block!] {Block of cases (conditions followed by values)}
	/all {Evaluate all cases (do not stop at first true case)}
]

catch: native [
	{Catches a throw from a block and returns its value.}
	block [block!] {Block to evaluate}
	/name {Catches a named throw}
	word [word! block!] {One or more names}
	/quit {Special catch for QUIT native}
]

;cause: native [
;	{Force error processing on an error value.}
;	error [error!]
;]

comment: native [
	{Ignores the argument value and returns nothing.}
	value {A string, block, file, etc.}
]

compose: native [
	{Evaluates a block of expressions, only evaluating parens, and returns a block.}
	value "Block to compose"
	/deep "Compose nested blocks"
	/only {Insert a block as a single value (not the contents of the block)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

context: native [
	{Creates an object.}
	spec ; [block!] -- no check required, we know it is correct
]

continue: native [
	{Throws control back to top of loop.}
]

;dir?: native [
;	{Returns true if file is a directory.}
;	file [any-string! none!]
;	/any {Allow * or ? wildcards for directory}
;]

;disarm: native [
;	{(Deprecated - not needed) Converts error to an object. Other types not modified.}
;	error [any-type!]
;]

do: native [
	{Evaluates a block, file, URL, function, word, or any other value.}
	value [any-type!] "Normally a file name, URL, or block"
	/args "If value is a script, this will set its system/script/args"
	arg   "Args passed to a script (normally a string)"
	/next "Do next expression only, return it, update block variable"
	var [word!] "Variable updated with new block position"
]

;eval: native [
;	{Evaluates a block, file, URL, function, word, or any other value.}
;	value "Normally a file name, URL, or block"
;]

either: native [
	{If TRUE condition return first arg, else second; evaluate blocks by default.}
	condition
	true-branch
	false-branch
	/only "Suppress evaluation of block args."
]

exit: native [
	{Exits a function, returning no value.}
]

find-script: native [
	{Find a script header within a binary string. Returns starting position.}
	script [binary!]
]

for: native [
	{Evaluate a block over a range of values. (See also: REPEAT)}
	'word [word!] "Variable to hold current value"
	start [series! number!] "Starting value"
	end   [series! number!] "Ending value"
	bump  [number!] "Amount to skip each time"
	body  [block!] "Block to evaluate"
]

forall: native [
	"Evaluates a block for every value in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	body [block!] "Block to evaluate each time"
]

forever: native [
	{Evaluates a block endlessly.}
	body [block!] {Block to evaluate each time}
]

foreach: native [
	{Evaluates a block for each value(s) in a series.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series! any-object! map! none!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

forskip: native [
	"Evaluates a block for periodic values in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	size [integer! decimal!] "Number of positions to skip each time"
	body [block!] "Block to evaluate each time"
	/local orig result
]

halt: native [
	{Stops evaluation and returns to the input prompt.}
]

if: native [
	{If TRUE condition, return arg; evaluate block args by default}
	condition
	true-branch
	/else "If FALSE condition, return second arg; evaluate block by default"
	false-branch
	/only "Suppress evaluation of block args."
]

loop: native [
	{Evaluates a block a specified number of times.}
	count [number!] {Number of repetitions}
	block [block!] {Block to evaluate}
]

map-each: native [
	{Evaluates a block for each value(s) in a series and returns them as a block.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [block! vector!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

;replace-all: native [
;	"Search and replace multiple values with a series; returns a new series."
;	target [block! string! binary!]
;	values [block!] "A block of [old new] search/replace pairs"
;]

quit: native [
	{Stops evaluation and exits the interpreter.}
	/return {Returns a value (to prior script or command shell)}
	value {Note: use integers for command shell}
	/now {Quit immediately}
]

protect: native [
	"Protect a series or a variable from being modified."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series/objects as well"
	/words  "Process list as words (and path words)"
	/values "Process list of values (implied GET)"
	/hide "Hide variables (avoid binding and lookup)"
]

unprotect: native [
	"Unprotect a series or a variable (it can again be modified)."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series as well"
	/words "Block is a list of words"
	/values "Process list of values (implied GET)"
]

recycle: native [
	{Recycles unused memory.}
	/off {Disable auto-recycling}
	/on {Enable auto-recycling}
	/ballast {Trigger for auto-recycle (memory used)}
	size [integer!]
	/torture {Constant recycle (for internal debugging)}
]

reduce: native [
	{Evaluates expressions and returns multiple results.}
	value
	/no-set {Keep set-words as-is. Do not set them.}
	/only {Only evaluate words and paths, not functions}
	words [block! none!] {Optional words that are not evaluated (keywords)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

repeat: native [
	{Evaluates a block a number of times or over a series.}
	'word [word!] {Word to set each time}
	value [number! series! none!] {Maximum number or series to traverse}
	body [block!] {Block to evaluate each time}
]

remove-each: native [
	{Removes values for each block that returns true; returns removal count.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series!] {The series to traverse (modified)}
	body [block!] {Block to evaluate (return TRUE to remove)}
]

return: native [
	{Returns a value from a function.}
	value [any-type!]
	/redo {Upon return, re-evaluate the returned result. (Used for DO)}
]

switch: native [
	"Selects a choice and evaluates the block that follows it."
	value "Target value"
	cases [block!] "Block of cases to check"
	/default case "Default case if no others found"
	/all "Evaluate all matches (not just first one)"
]

throw: native [
	{Throws control back to a previous catch.}
	value [any-type!] {Value returned from catch}
	/name {Throws to a named catch}
	word [word!]
]

trace: native [
	{Enables and disables evaluation tracing and backtrace.}
	mode [integer! logic!]
	/back {Set mode ON to enable or integer for lines to display}
	/function {Traces functions only (less output)}
;	/stack {Show stack index}
]

try: native [
	{Tries to DO a block and returns its value or an error.}
	block [block!]
	/except "On exception, evaluate this code block"
	code [block! any-function!]
]

unless: native [
	{If FALSE condition, return arg; evaluate block args by default.}
	condition
	false-branch
	/only "Suppress evaluation of block args."
]

until: native [
	{Evaluates a block until it is TRUE. }
	block [block!]
]

while: native [
	{While a condition block is TRUE, evaluates another block.}
	cond-block [block!]
	body-block [block!]
]

;-- Data Natives - nat_data.c

;alias: native [
;	See CC#1835
;	{Creates an alternate spelling for a word.}
;	word [word!] {Word to alias}
;	name [string!] {Name of alias}
;]

;as-binary: native [
;	{Coerces any type of string into a binary! datatype without copying it.}
;	string [any-string!]
;]
;
;as-string: native [
;	{Coerces any type of string into a string! datatype without copying it.}
;	string [any-string!]
;]

bind: native [
	{Binds words to the specified context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	context [any-word! any-object!] {A reference to the target context}
	/copy {Bind and return a deep copy of a block, don't modify original}
	/only {Bind only first block (not deep)}
	/new {Add to context any new words found}
	/set {Add to context any new set-words found}
]

unbind: native [
	{Unbinds words from context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	/deep "Process nested blocks"
]

bound?: native [
	{Returns the context in which a word is bound.}
	word [any-word!]
]

collect-words: native [
	"Collect unique words used in a block (used for context construction)."
	block [block!]
	/deep "Include nested blocks"
	/set "Only include set-words"
	/ignore "Ignore prior words"
	words [any-object! block! none!] "Words to ignore"
]

checksum: native [
	{Computes a checksum, CRC, or hash.}
	data [binary!] {Bytes to checksum}
	/part length {Length of data}
	/tcp {Returns an Internet TCP 16-bit checksum}
	/secure {Returns a cryptographically secure checksum}
	/hash {Returns a hash value}
	size [integer!] {Size of the hash table}
	/method {Method to use}
	word [word!] {Methods: SHA1 MD5 CRC32}
	/key {Returns keyed HMAC value}
	key-value [any-string!] {Key to use}
]

compress: native [
	{Compresses a string series and returns it.}
	data [binary! string!] {If string, it will be UTF8 encoded}
	/part length {Length of data (elements)}
	/gzip {Use GZIP checksum}
]

decompress: native [
	{Decompresses data. Result is binary.}
	data [binary!] {Data to decompress}
	/part length {Length of compressed data (must match end marker)}
	/gzip {Use GZIP checksum}
	/limit size {Error out if result is larger than this}
]

construct: native [
	{Creates an object with scant (safe) evaluation.}
	block [block! string! binary!] "Specification (modified)"
	/with "Default object" object [object!]
	/only "Values are kept as-is"
]

debase: native [
	{Decodes binary-coded string (BASE-64 default) to binary value.}
	value [binary! string!] {The string to decode}
	/base {Binary base to use}
	base-value [integer!] {The base to convert from: 64, 16, or 2}
]

enbase: native [
	{Encodes a string into a binary-coded string (BASE-64 default).}
	value [binary! string!] {If string, will be UTF8 encoded}
	/base {Binary base to use}
	base-value [integer!] {The base to convert to: 64, 16, or 2}
]

decloak: native [
	{Decodes a binary string scrambled previously by encloak.}
	data [binary!] "Binary series to descramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

encloak: native [
	{Scrambles a binary string based on a key.}
	data [binary!] "Binary series to scramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

deline: native [
	"Converts string terminators to standard format, e.g. CRLF to LF."
	string [any-string!] {(modified)}
	/lines "Return block of lines (works for LF, CR, CR-LF endings) (no modify)"
]

enline: native [
	"Converts string terminators to native OS format, e.g. LF to CRLF."
	series [any-string! block!] {(modified)}
]

detab: native [
	"Converts tabs to spaces (default tab size is 4)."
	string [any-string!] {(modified)}
	/size  "Specifies the number of spaces per tab"
	number [integer!]
]

entab: native [
	"Converts spaces to tabs (default tab size is 4)."
	string [any-string!] {(modified)}
	/size "Specifies the number of spaces per tab"
	number [integer!]
]

delect: native [
	"Parses a common form of dialects. Returns updated input block."
	 dialect [object!] "Describes the words and datatypes of the dialect"
	 input [block!] "Input stream to parse"
	 output [block!] "Resulting values, ordered as defined (modified)"
	 /in "Search for var words in specific objects (contexts)"
	 where [block!] "Block of objects to search (non objects ignored)"
	 /all "Parse entire block, not just one command at a time"
]

difference: native [
	{Returns the special difference of two values.}
	set1 [block! string! binary! bitset! date! typeset!] "First data set"
	set2 [block! string! binary! bitset! date! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

exclude: native [
	{Returns the first data set less the second data set.}
	set1 [block! string! binary! bitset! typeset!] "First data set"
	set2 [block! string! binary! bitset! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

intersect: native [
	{Returns the intersection of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

union: native [
	{Returns the union of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Use case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

unique: native [
	{Returns the data set with duplicates removed.}
	set1 [block! string! binary! bitset! typeset!]
	/case  {Use case-sensitive comparison (except bitsets)}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

lowercase: native [
	"Converts string of characters to lowercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

uppercase: native [
	"Converts string of characters to uppercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

dehex: native [
	{Converts URL-style hex encoded (%xx) strings.}
	value [any-string!] {The string to dehex}
]

get: native [
	{Gets the value of a word or path, or values of an object.}
	word {Word, path, object to get}
	/any {Allows word to have no value (allows unset)}
]

in: native [
	{Returns the word or block in the object's context.}
	object [any-object! block!]
	word [any-word! block! paren!]  {(modified if series)}
]

parse: native [
	{Parses a string or block series according to grammar rules.}
	input [series!] {Input series to parse}
	rules [block! string! char! none!] {Rules to parse by (none = ",;")}
	/all {For simple rules (not blocks) parse all chars including whitespace}
	/case {Uses case-sensitive comparison}
]

set: native [
	{Sets a word, path, block of words, or object to specified value(s).}
	word [any-word! any-path! block! object!] {Word, block of words, path, or object to be set (modified)}
	value [any-type!] {Value or block of values}
	/any {Allows setting words to any value, including unset}
	/pad {For objects, if block is too short, remaining words are set to NONE}
]

to-hex: native [
	{Converts numeric value to a hex issue! datatype (with leading # and 0's).}
	value [integer! tuple!] {Value to be converted}
	/size {Specify number of hex digits in result}
	len [integer!]
]

type?: native [
	{Returns the datatype of a value.}
	value [any-type!]
	/word {Returns the datatype as a word}
]

unset: native [
	{Unsets the value of a word (in its current context.)}
	word [word! block!] {Word or block of words}
]

utf?: native [
	{Returns UTF BOM (byte order marker) encoding; + for BE, - for LE.}
	data [binary!]
]

invalid-utf?: native [
	{Checks UTF encoding; if correct, returns none else position of error.}
	data [binary!]
	/utf "Check encodings other than UTF-8"
	num [integer!] "Bit size - positive for BE negative for LE"
]

value?: native [
	{Returns TRUE if the word has a value.}
	value
]

;-- IO Natives - nat_io.c

print: native [
	{Outputs a value followed by a line break.}
	value [any-type!] {The value to print}
]

prin: native [
	{Outputs a value with no line break.}
	value [any-type!]
]

mold: native [
	{Converts a value to a REBOL-readable string.}
	value [any-type!] {The value to mold}
	/only {For a block value, mold only its contents, no outer []}
	/all  {Use construction syntax}
	/flat {No indentation}
]

form: native [
	{Converts a value to a human-readable string.}
	value [any-type!] {The value to form}
]

new-line: native [
	{Sets or clears the new-line marker within a block or paren.}
	position [block! paren!] {Position to change marker (modified)}
	value {Set TRUE for newline}
	/all {Set/clear marker to end of series}
	/skip {Set/clear marker periodically to the end of the series}
	size [integer!]
]

new-line?: native [
	{Returns the state of the new-line marker within a block or paren.}
	position [block! paren!] {Position to check marker}
]

to-local-file: native [
	{Converts a REBOL file path to the local system file path.}
	path [file! string!]
	/full "Prepends current dir for full path (for relative paths only)"
]

to-rebol-file: native [
	{Converts a local system file path to a REBOL file path.}
	path [file! string!]
]

transcode: native [
	{Translates UTF-8 binary source to values. Returns [value binary].}
	source [binary!] "Must be Unicode UTF-8 encoded"
	/next "Translate next complete value (blocks as single value)"
	/only "Translate only a single value (blocks dissected)"
	/error "Do not cause errors - return error object as value in place"
]

echo: native [
    {Copies console output to a file.}
    target [file! none! logic!]
]

now: native [
	{Returns date and time.}
	/year {Returns year only}
	/month {Returns month only}
	/day {Returns day of the month only}
	/time {Returns time only}
	/zone {Returns time zone offset from UCT (GMT) only}
	/date {Returns date only}
	/weekday {Returns day of the week as integer (Monday is day 1)}
	/yearday {Returns day of the year (Julian)}
	/precise {High precision time}
	/utc {Universal time (no zone)}
]

wait: native [
	{Waits for a duration, port, or both.}
	value [number! time! port! block! none!]
	/all {Returns all in a block}
	/only {only check for ports given in the block to this function}
]

wake-up: native [
	{Awake and update a port with event.}
	port [port!]
	event [event!]
]

what-dir: native ["Returns the current directory path."]

change-dir: native [
	"Changes the current directory path."
	path [file!]
]

;-- Series Natives

first: native [
	{Returns the first value of a series.}
	value
]

second: native [
	{Returns the second value of a series.}
	value
]

third: native [
	{Returns the third value of a series.}
	value
]

fourth: native [
	{Returns the fourth value of a series.}
	value
]

fifth: native [
	{Returns the fifth value of a series.}
	value
]

sixth: native [
	{Returns the sixth value of a series.}
	value
]

seventh: native [
	{Returns the seventh value of a series.}
	value
]

eighth: native [
	{Returns the eighth value of a series.}
	value
]

ninth: native [
	{Returns the ninth value of a series.}
	value
]

tenth: native [
	{Returns the tenth value of a series.}
	value
]

last: native [
	{Returns the last value of a series.}
	value [series! tuple! gob!]
]

;-- Math Natives - nat_math.c

cosine: native [
	{Returns the trigonometric cosine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

sine: native [
	{Returns the trigonometric sine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

tangent: native [
	{Returns the trigonometric tangent.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

arccosine: native [
	{Returns the trigonometric arccosine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arcsine: native [
	{Returns the trigonometric arcsine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arctangent: native [
	{Returns the trigonometric arctangent (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

exp: native [
	{Raises E (the base of natural logarithm) to the power specified}
	power [number!]
]

log-10: native [
	{Returns the base-10 logarithm.}
	value [number!]
]

log-2: native [
	{Return the base-2 logarithm.}
	value [number!]
]

log-e: native [
	{Returns the natural (base-E) logarithm of the given value} 
	value [number!]
]

not: native [
	{Returns the logic complement.}
	value {(Only FALSE and NONE return TRUE)}
]

square-root: native [
	{Returns the square root of a number.}
	value [number!]
]

shift: native [
	{Shifts an integer left or right by a number of bits.}
	value [integer!]
	bits [integer!] "Positive for left shift, negative for right shift"
	/logical "Logical shift (sign bit ignored)"
]

;-- New, hackish stuff:

++: native [
	{Increment an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

--: native [
	{Decrement an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

first+: native [
	{Return the FIRST of a series then increment the series index.}
	'word [word!] "Word must refer to a series"
]

stack: native [
	{Returns stack backtrace or other values.}
	offset [integer!] "Relative backward offset"
	/block "Block evaluation position"
	/word "Function or object name, if known"
	/func "Function value"
	/args "Block of args (may be modified)"
	/size "Current stack size (in value units)"
	/depth "Stack depth (frames)"
	/limit "Stack bounds (auto expanding)"
]

resolve: native [
	{Copy context by setting values in the target from those in the source.}
	target [any-object!] {(modified)}
	source [any-object!]
	/only from [block! integer!] "Only specific words (exports) or new words in target (index to tail)"
	/all "Set all words, even those in the target that already have a value"
	/extend "Add source words to the target if necessary"
]

;in-context: native [
;	{Set the default context for global words.}
;	context [object!]
;]

get-env: native [
	{Returns the value of an OS environment variable (for current process).}
	var [any-string! any-word!]
]

set-env: native [
	{Sets the value of an operating system environment variable (for current process).} 
	var [any-string! any-word!] "Variable to set" 
	value [string!  none!] "Value to set, or NONE to unset it"
]

list-env: native [
	{Returns a map of OS environment variables (for current process).}
]

call: native [
	{Run another program; return immediately.}
	command [string! block! file!] "An OS-local command line (quoted as necessary), a block with arguments, or an executable file"
	/wait "Wait for command to terminate before returning"
	/console "Runs command with I/O redirected to console"
	/shell "Forces command to be run from shell"
	/info "Returns process information object"
	/input in [string! binary! file! none!] "Redirects stdin to in"
	/output out [string! binary! file! none!] "Redirects stdout to out"
	/error err [string! binary! file! none!] "Redirects stderr to err"
]

browse: native [
	{Open web browser to a URL or local file.}
	url [url! file! none!]
]

evoke: native [
	{Special guru meditations. (Not for beginners.)}
	chant [word! block! integer!] "Single or block of words ('? to list)"
]

request-file: native [
	{Asks user to select a file and returns full file path (or block of paths).}
	/save "File save mode"
	/multi "Allows multiple file selection, returned as a block"
	/file name [file!] "Default file name or directory"
	/title text [string!] "Window title"
	/filter list [block!] "Block of filters (filter-name filter)"
]

ascii?: native [
	{Returns TRUE if value or string is in ASCII character range (below 128).}
	value [any-string! char! integer!]
]

latin1?: native [
	{Returns TRUE if value or string is in Latin-1 character range (below 256).}
	value [any-string! char! integer!]
]

; Temps...

stats: native [
	{Provides status and statistics information about the interpreter.}
	/show {Print formatted results to console}
	/profile {Returns profiler object}
	/timer {High resolution time difference from start}
	/evals {Number of values evaluated by interpreter}
	/dump-series pool-id [integer!] {Dump all series in pool pool-id, -1 for all pools}
]

do-codec: native [
	{Evaluate a CODEC function to encode or decode media types.}
	handle [handle!] "Internal link to codec"
	action [word!] "Decode, encode, identify"
	data [binary! image!]
]

set-scheme: native [
	"Low-level port scheme actor initialization."
	scheme [object!]
]

load-extension: native [
	"Low level extension module loader (for DLLs)."
	name [file! binary!] "DLL file or UTF-8 source"
	/dispatch "Specify native command dispatch (from hosted extensions)"
	function [handle!] "Command dispatcher (native)"
]

do-commands: native [
	"Evaluate a block of extension module command functions (special evaluation rules.)"
	commands [block!] "Series of commands and their arguments"
]

ds: native ["Temporary stack debug"]
dump: native ["Temporary debug dump" v]
check: native ["Temporary series debug check" val [series!]]

do-callback: native [
	"Internal function to process callback events."
	event [event!] "Callback event"
]


limit-usage: native [
	"Set a usage limit only once (used for SECURE)."
	field [word!] "eval (count) or memory (bytes)"
	limit [number!]
]

selfless?: native [
    "Returns true if the context doesn't bind 'self."
    context [any-word! any-object!] "A reference to the target context"
]

map-event: native [
	"Returns event with inner-most graphical object and coordinate."
	event [event!]
]

map-gob-offset: native [
	"Translates a gob and offset to the deepest gob and offset in it, returned as a block."
	gob [gob!] "Starting object"
	xy [pair!] "Staring offset"
	/reverse "Translate from deeper gob to top gob."
]

as-pair: native [
	"Combine X and Y values into a pair."
	x [number!]
	y [number!]
]

;read-file: native [f [file!]]

equal?: native [
	{Returns TRUE if the values are equal.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equal?: native [
	{Returns TRUE if the values are not equal.}
	value1 [any-type!]
	value2 [any-type!]
]

equiv?: native [
	{Returns TRUE if the values are equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equiv?: native [
	{Returns TRUE if the values are not equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-equal?: native [
	{Returns TRUE if the values are strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-not-equal?: native [
	{Returns TRUE if the values are not strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

same?: native [
	{Returns TRUE if the values are identical.}
	value1 [any-type!]
	value2 [any-type!]
]

greater?: native [ ; Note: some datatypes expect >, <, >=, <= to be in this order.
	{Returns TRUE if the first value is greater than the second value.}
	value1 value2
]

greater-or-equal?: native [
	{Returns TRUE if the first value is greater than or equal to the second value.}
	value1 value2
]

lesser?: native [
	{Returns TRUE if the first value is less than the second value.}
	value1 value2
]

lesser-or-equal?: native [
	{Returns TRUE if the first value is less than or equal to the second value.}
	value1 value2
]

minimum: native [
	{Returns the lesser of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

maximum: native [ ; Note: Some datatypes expect all binary ops to be <= this
	{Returns the greater of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

negative?: native [
	{Returns TRUE if the number is negative.}
	number [number! money! time! pair!]
]

positive?: native [
	{Returns TRUE if the value is positive.}
	number [number! money! time! pair!]
]

zero?: native [
	{Returns TRUE if the value is zero (for its datatype).}
	value
]
#extract commit log from each relase cycle

##### set from args #####
args<-commandArgs(trailingOnly=T)

#check the number of arguments
if(length(args) == 0){
  print("use default setting (for Chromium), --args 42 2 2014-06-20 24")
  release_cycle<-42#days(= 6 weeks = 1.5month)
  threshold<-2#commits/release_cycle
  newest_release_date<-as.Date("2014-06-20")#ver37
  num_release<-24#: a number of past release to trace
}else if(length(args) != 4){
  write("Error: commandline arguments for <release_cycle(days)> <threshold of commits> <newest release date(yyyy-mm-dd)> <the number of going back release> are required", stderr())
  q()
}else{
  release_cycle<-as.numeric(args[1])
  threshold<-as.numeric(args[2])
  newest_release_date<-as.Date(args[3])
  num_release<-as.numeric(args[4])
}
# import merged git log file
git_log.df<-read.csv("git_log_main_change_merged.csv",header=T)
git_log.df$author_date<-as.Date(git_log.df$author_date)
git_log.df$author_mail<-as.character(git_log.df$author_mail)
#filtering
activity.df<-data.frame(1:num_release,1:2)
names(activity.df)<-c("Duration","Effort")
for(i in 1:num_release){
  git_log_tmp.df<-subset(git_log.df,git_log.df$author_date<(newest_release_date-release_cycle*(i-1)) & (newest_release_date-release_cycle*i)<=git_log.df$author_date)
  auth_freq.df<-data.frame(table(git_log_tmp.df$author_mail))
  names(auth_freq.df)<-c("author_mail","commit_count")
  
  activity.df$Duration[i]<-paste(newest_release_date-release_cycle*(i-1),"-",newest_release_date-release_cycle*i,sep="")
  # In original paper, non-fulltime developers' effort is caliculated by commit_count/threshold, so using ">="
  # http://gsyc.urjc.es/~grex/repro/2014-msr-effort/msr14-robles-estimating-effort.pdf
  fulltime_auth.df<-subset(auth_freq.df,auth_freq.df$commit_count>=threshold)
  parttime_auth.df<-subset(auth_freq.df,auth_freq.df$commit_count<threshold)
  parttime_auth.df$effort<-parttime_auth.df$commit_count/threshold
  # 28 = 1 month
  activity.df$Effort[i]<-(nrow(fulltime_auth.df)+sum(parttime_auth.df$effort))*(release_cycle/28)
  activity.df$commits[i]<-nrow(git_log_tmp.df)
  activity.df$bugfix_commits[i]<-nrow(subset(git_log_tmp.df,git_log_tmp.df$bug_fix==1))
  activity.df$refactoring_commits[i]<-nrow(subset(git_log_tmp.df,git_log_tmp.df$refactoring_flag==1))
  activity.df$newfunc_commits[i]<-nrow(subset(git_log_tmp.df,git_log_tmp.df$bug_fix!=1 & git_log_tmp.df$refactoring_flag!=1))
  activity.df$add_lines[i]<-sum(git_log_tmp.df$add_lines)
  activity.df$del_lines[i]<-sum(git_log_tmp.df$del_lines)
  activity.df$change_files[i]<-sum(git_log_tmp.df$change_files)
  
  ##temporary dataframe output
  #write.csv(auth_freq.df,paste("author_activity_from_",(newest_release_date-release_cycle*i),"_to_",(newest_release_date-release_cycle*(i-1)),".csv",sep=""),row.names=F)
}
write.csv(activity.df,paste("chromium_activity_metrics.csv",sep=""),row.names=F)
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
		require(xgboost)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()
    if (is(object, 'tundraContainer') &&
        # Hack for model object requiring customized
        # serializer, e.g., xgb.Booster
        is(object$output$model, 'xgb.Booster')) {
      file_save <- tempfile()
      on.exit(unlink(file_save))
      xgboost::xgb.save(object$output$model, file_save)
      stopifnot(!is.na(as.integer(file.info(file_save)$size)))
      object$output$model <- NULL
      con <- file(file_save, 'rb')
      on.exit(close(con), add = TRUE)
      object <- structure(class = 'special_serialized_object', list(
                  deserialize = function(x) {
                    file_load <- tempfile()
                    on.exit(unlink(file_load))
                    con <- file(file_load, 'wb')
                    on.exit(close(con), add = TRUE)
                    writeBin(x$xgb.bin, con, useBytes = TRUE)
                    close(con)
                    x$container$output$model <- xgboost::xgb.load(file_load)
                    x$container
                  }, object = list(container = object, xgb.bin = readBin(con, raw(), n = file.info(file_save)$size)))
                )
      close(con)
    }
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll) {
    abind::asub(X, ll, drop=F)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along])) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
		require(xgboost)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

		if (is(object, 'tundraContainer') &&
		  # Hack for model object requiring customized
			#	serializer, e.g., xgb.Booster
		  is(object$output$model, 'xgb.Booster')) {
		    file_save <- tempfile()
				on.exit(unlink(file_save))
		    xgboost::xgb.save(object$output$model, file_save)
				stopifnot(!is.na(as.integer(file.info(file_save)$size)))
		    object$output$model <- NULL
				con <- file(file_save, 'rb')
				on.exit(close(con), add = TRUE)
		    object <- structure(class = 'special_serialized_object', list(
		      deserialize = function(x) {
		        file_load <- tempfile()
		        on.exit(unlink(file_load))
						con <- file(file_load, 'wb')
						on.exit(close(con), add = TRUE)
		        writeBin(x$xgb.bin, con, useBytes = TRUE)
						close(con)
		        x$container$output$model <- xgboost::xgb.load(file_load)
		        x$container
		      }, object = list(container = object,
						 							 xgb.bin = readBin(con, raw(), n = file.info(file_save)$size))
		    ))
				close(con)
		}
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v11b <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if(debug==TRUE){print(paste("argument test:", argument_test))}

  
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly one of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done
  
  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors

  # save some space by removing my_data
  rm(my_data)

  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)

  
  # make sure everything is sorted by id
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]

  if(debug==TRUE){
    #eigen_vectors.test<<-eigen_vectors
    #eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  #num_samples <- ncol(my_data$eigen_vectors)
  num_samples <- ncol(eigen_vectors)
  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  #pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug)
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(eigen_vectors), debug)

  #if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  # save some space by removing pch_object
  rm(pch_object)
  
  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files

    if(debug==TRUE){print("RENDERING PCoA WIH NO METADATA")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("RENDERING PCoA WIH amethst_groups METADATA")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("RENDERING PCoA WIH color_list METADATA")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    if(debug==TRUE){print("RENDERING PCoA WIH metadata_table METADATA")}

    #num_lines_string <- paste("wc -l ", metadata_table)
    #num_lines <- scan(pipe(num_lines_string), what=list(0, NULL))[[1]]
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                                 read.table(
                                            file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                            colClasses = "character", check.names=FALSE,
                                            comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE #, nrows=num_lines
                                            )
                                 )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      if(debug==TRUE){print("RENDERING PCoA WIH metadata_table METADATA (all columns)")}
      
      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        #if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        #if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        #if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          #test.color_column <<- color_column
          #test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      
      if(debug==TRUE){print("RENDERING PCoA WIH metadata_table METADATA (single column)")}
      
      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      #if(debug==TRUE){ test1<<-metadata_column }
      
      image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
      figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      #if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
      #if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")

  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      #plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
    pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    #if(debug==TRUE){pch_levels.test<<-pch_levels}
    pch_labels <- pch_labels
    #if(debug==TRUE){pch_labels.test<<-pch_labels}
    
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      #plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    #if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch))) ##### ? does this need to be a global ? 10-7-14


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  #if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ order(sample_names), metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  #if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  #if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  #if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v11b <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if(debug==TRUE){print(paste("argument test:", argument_test))}

  
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly one of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done
  
  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors

  # save some space by removing my_data
  rm(my_data)

  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)

  
  # make sure everything is sorted by id
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]

  if(debug==TRUE){
    #eigen_vectors.test<<-eigen_vectors
    #eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  #num_samples <- ncol(my_data$eigen_vectors)
  num_samples <- ncol(eigen_vectors)
  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  #pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug)
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(eigen_vectors), debug)

  #if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  # save some space by removing pch_object
  rm(pch_object)
  
  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==0 ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    #num_lines_string <- paste("wc -l ", metadata_table)
    #num_lines <- scan(pipe(num_lines_string), what=list(0, NULL))[[1]]
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                                 read.table(
                                            file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                            colClasses = "character", check.names=FALSE,
                                            comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE #, nrows=num_lines
                                            )
                                 )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        #if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        #if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        #if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          #test.color_column <<- color_column
          #test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      #if(debug==TRUE){ test1<<-metadata_column }
      
      image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
      figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      #if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
      #if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")

  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      #plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
    pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    #if(debug==TRUE){pch_levels.test<<-pch_levels}
    pch_labels <- pch_labels
    #if(debug==TRUE){pch_labels.test<<-pch_labels}
    
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      #plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    #if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch))) ##### ? does this need to be a global ? 10-7-14


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  #if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ order(sample_names), metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  #if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  #if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  #if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

subsets = function(X, along, subsets) {
    if (length(subsets) != dim(as.array(X))[along])
        stop("subset length must match X dimension on along axis")

    if (any(is.na(subsets)))
        stop("found NA in subsets, exiting")
}

along = function(X, along) {
    if (any(duplicated(dimnames(X)[[along]])))
        stop("duplicated names found along mapping axis, exiting")

    if (is.character(along))
        assign('along', which(names(dim(X)) == along, envir=parent.frame()))
}

x = function(X, to.array, classes=NULL, envir=parent.frame()) {
    if (!is.null(classes) && !class(X) %in% classes)
        stop(paste("class of X not in classes:", classes))

    if (to.array)
        assign('X', as.array(X), envir=envir)
}

all = function(X, along, subsets, x.to.array=FALSE, envir=parent.frame()) {
    along(X, along)
    subsets(X, along, subsets)
    x(X, x.to.array, envir=envir)
}
REBOL [
    Title: "Wav-to-mp3"
    Date: 24-Sep-2013/13:41:18+2:00
    Name: none
    Version: none
    File: none
    Home: none
    Author: "A Rebol"
    Owner: none
    Rights: none
    Needs: none
    Tabs: none
    Usage: none
    Purpose: none
    Comment: none
    History: none
    Language: none
    Type: none
    Content: none
    Email: none
]

camelize-wav-name: func[name][
	name: uppercase/part name 1
	parse/all name [
		any [
			  s: "_16bit" e: (s: remove/part s e) :s
			| s: "_16b"   e: (s: remove/part s e) :s
			;| s: ".wav" end e: (s: remove/part s e) :s
			| s: some [#" " | #"_" | #"-"] e: (s: remove/part s e uppercase/part s 1) :s
			|
			1 skip	
		]
	]
	probe name
]


wav-to-mp3: func[source [file! string!] /local dir name wavs cmd loop?][
	wavs: copy []
	if string? source [source: to-rebol-file source]
	if #"/" <> first source [ insert source what-dir ]
	either dir? source [
		foreach file read source [
			append wavs rejoin [source file]
		]
	][
		append wavs source
	]
	foreach wav-file wavs [
		if parse wav-file [thru ".wav" end][
			set [dir name] split-path wav-file
			parse name ["_loop_" to end (loop?: true)]
			
			either loop? [
				mp3: join dir replace name ".wav" ".mp3"
				
				print join "==> " cmd: rejoin [{x:\utils\mp3loop --encoder=x:\utils\lame\lame.exe -V0 -h --silent "} to-local-file wav-file {"}]
			][
				mp3: join dir camelize-wav-name replace name ".wav" ".mp3"
				;print join "==> " cmd: rejoin [{x:\utils\lame\lame -b 320 -h --silent -t "} to-local-file wav-file {" "} to-local-file mp3 {"}]
				print join "==> " cmd: rejoin [{x:\utils\lame\lame -V 0 -h --silent -t "} to-local-file wav-file {" "} to-local-file mp3 {"}]
			
			]
			call/console cmd
			if loop? [
				rename mp3 camelize-wav-name copy skip name 6
			]
		]
	]
]
wmc: does [wav-to-mp3 read clipboard://]REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   30]
		%PlanetaZluta      [600     1300   100    250   30]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 250 30]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = map(X, along, function(x) FUN(x), subsets)
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=length, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll) {
    abind::asub(X, ll, drop=F)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    else if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along])) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)==dim(X)[along])
        lnames = base::dimnames(X)[[along]]
    else
        lnames = usubsets
    setNames(lapply(idxList, function(ll) subset(X, ll)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=mean) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = map(X, along, function(x) FUN(x), subsets)
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=length, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll) {
    abind::asub(X, ll, drop=F)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    else if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along])) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)==dim(X)[along])
        lnames = base::dimnames(X)[[along]]
    else
        lnames = usubsets
    setNames(lapply(idxList, function(ll) subset(X, ll)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=mean) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
#Load Packages

library(XML)
library(tidyr)
library(stringr)
library(magrittr)
library(plyr)
library(dplyr)
library(RWeka)

#Remove non-words from the raw icc texts
get_real_words <- function(word) {
  word[!stringr::str_detect(word, "[^a-z ]")]
}

#' Remove unreasonable n-grams containing characters other than letters and spaces
#' @param ngrams A list of n-grams
#' @return Returns a list of filtered n-grams
filter_unreasonable_ngrams <- function(ngrams) {
  require(stringr)
  ngrams[!str_detect(ngrams, "[^a-z ]")]
}

#load OCR'd ICC Deceisions data into R
icc_dir <- "text"
files <- dir(icc_dir, "*.txt")
raw <- file.path(icc_dir, files) %>%
  lapply(., scan, "character", sep = "\n")
names(raw) <- files
icc_texts <- lapply(raw, paste, collapse = " ") %>%
  lapply(., tolower) %>%
  lapply(., WordTokenizer) %>%
  lapply(., get_real_words) %>%
  lapply(., paste, collapse = " ")

#Create an N-gram maker with Rweka's function
#ngrammify <- function(data, n) { 
 # NGramTokenizer(data, Weka_control(min = n, max = n))
#}

#Turn text list into N-grams, in this case 5-grams
#icc_grams <- lapply(icc_texts, ngrammify, 5)
#every_grams <- icc_grams %>% unlist() %>% unique()

#attach the 
icc.df <- ldply(icc_texts)

#have to use the old plyr package- currently a bug in dplyr with rename_ function- but it creates the correct data.frame all the same
decisions <- icc.df %>%
                    plyr::rename(c(".id" = "id",
                          "V1" = "text"))


#Run the filter_unreasonable_ngrams function
#fix_grams <- filter_unreasonable_ngrams(icc_grams)
#head(fix_grams)

#Save the data
write.csv(icc.df, file = "out/icc_texts.csv")
        R D   p     b   | R <    `   ( * - ^/ V1 2 C= >  v w { ٴ  i G P N  h  Q V   f	 & 9t (x e  u & @: o> A 0U a P    F  "   c ( A5 A F   7|  1 .	 5	 9g	 g	 ]	 
 O# 9 ~E    E t 0 7 R m gt t  ?    <' (I q  R      * E7 D u 2w ' c   r% * .  0 2 3 #L d |    v  < v \  m  l  Y   t	 6 J W[ `    &C P -q w } m   
 H  & a v G  ny l x : X ܔ   8 R e l !s N  X
 W "v m G   }      3&  1 @ [F K P  9_    7  < C *c Tz     { f  \  \     m   0/ 5 S n T   8 = n   K <  >  F  s    1    ! ! }F! j! I! ! ! :! ! " " )" 	9" H" X" 5}" " l" <" " *" z# A{# # -$ ͢$ 2$ % % 2% ~9% 	w% r% % % % 4& K& u-' "T' 'T' Y' ' q( )5( W( 4i( ( !) +) ) s* * + I5+ $E+ L+ o, }, `, , Ş, , :,  . . . 	. 
. @. . G. g. Մ. . E. . . / 6/ _2/ [/ l/ / / ئ/ / 1 1 51 T1 s1 1 1 ĭ1 ~1 f1 1 $@2 y2 2 ߛ2 2 2 2 f2 2 2 ~
3 3 '3 )3 {/3 63 {>3 B3 4 04 5 l6 o6 (8 "8 9 9 .9 v: <: Hk: : b; *< \-< 2< < < K(= .= #!/usr/bin/env Rscript

# Josep Ll. Berral-García
# ALOJA-BSC-MSR hadoop.bsc.es
# 2014-12-11
# Launcher of ALOJA-ML
 
# usage: ./aloja_cli.r -m method [-d dataset] [-l learned model] [-p param1=aaaa:param2=bbbb:param3=cccc:...] [-a] [-n dims] [-v]
#	 ./aloja_cli.r --method method [--dataset dataset] [--learned learned model] [--params param1=aaaa:param2=bbbb:param3=cccc:...] [--allvars] [--numvars dims] [--verbose]
#
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1-small:vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size"
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p1 -d m5p1-tt.csv -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":sorted=asc -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":sorted=asc -v
#
#	 ./aloja_cli.r -m aloja_outlier_dataset -d m5p1-tt.csv -l m5p1 -p sigma=3:hdistance=3:saveall=m5p1test
#	 ./aloja_cli.r -m aloja_outlier_instance -l m5p1 -p instance="sort,ETH,RR3,8,10,1,65536,None,32,Azure L":observed=100000:display=1 -v
#
#	 ./aloja_cli.r -m aloja_pca -d aloja-dataset.csv -p saveall=pca1
#	 ./aloja_cli.r -m aloja_regtree -d pca1-transformed.csv -p prange=1e-4,1e+4:saveall=m5p-simple-redim -n 20
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p-simple-redim -p inst_predict="1922.904354752,70.1570440421649,2.9694955079494,-3.64259027685954,-0.748746678239734,0.161321484374316,0.617610510007444,-0.459044093400257,0.251211132013151,0.251937462205716,-0.142007748147355,-0.0324862729758309,0.406308900544488,0.13593705166432,0.397452596451088,-0.731635384355167,-0.318297127484775,-0.0876192175148721,-0.0504762335523307,-0.0146283091875174" -v
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p-simple-redim -d m5p-simple-redim-tt.csv -v
#	 ./aloja_cli.r -m aloja_transform_data -d newdataset.csv -p pca_name=pca1:saveall=newdataset
#	 ./aloja_cli.r -m aloja_transform_instance -p pca_name=pca1:inst_transform="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1
#	 ./aloja_cli.r -m aloja_dataset_collapse_expand -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1:inst_general="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L"
#	 ./aloja_cli.r -m aloja_best_configurations -p bvec_name=dsc1 -v

library(devtools);
source_url("https://raw.githubusercontent.com/Aloja/aloja-ml/master/functions.r");
options(width=as.integer(1000));

###############################################################################
# Read arguments from CLI

	suppressPackageStartupMessages(require(optparse));

	option_list = list(
		make_option(c("-m", "--method"), action="store", default=NULL, type='character', help="Method to be executed"),
		make_option(c("-p", "--params"), action="store", default=NULL, type='character', help="Generic list of parameters, separated by two points and no spaces"),
		make_option(c("-v", "--verbose"), action="store_true", default=FALSE, help="Outputs the result of the method"),
		make_option(c("-d", "--dataset"), action="store", default=NULL, type='character', help="For training methods: Dataset source of data"),
		make_option(c("-a", "--allvars"), action="store_true", default=FALSE, help="All vars are input but first one (for reduced dimensions)"),
		make_option(c("-n", "--numvars"), action="store", default=NULL, type='integer', help="All n vars after first one are input (for reduced dimensions)"),
		make_option(c("-l", "--learned"), action="store", default=NULL, type='character', help="For prediction methods: Learned model for prediction")
	);

	opt = parse_args(OptionParser(option_list=option_list));

###############################################################################
# Error and Warning messages on arguments

	if (is.null(opt$method))
	{
		cat("[ERROR] No method selected. Aborting mission.\n");
		quit(save="no", status=-1);
	}

###############################################################################
# Read datasets

	dataset <- NULL;

	if (!is.null(opt$dataset))
	{
		# Call for aloja_get_data
		params_1 <- list();
		params_1[["fread"]] = opt$dataset;

		dataset <- do.call(aloja_get_data,params_1);
	}

###############################################################################
# Parse parameters

	params <- list();
	params[["ds"]] <- dataset;

	if (opt$method %in% c("aloja_regtree","aloja_nneighbors","aloja_linreg","aloja_nnet","aloja_pca","aloja_dataset_collapse","aloja_dataset_collapse_expand","aloja_outlier_dataset","aloja_outlier_instance","aloja_binarize_instance"))
	{
		if (is.null(opt$vout)) params[["vout"]] <- "Exe.Time";

		if (is.null(opt$vin))
		{
			if (opt$allvars)
			{
				params[["vin"]] = colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))];
			} else if (!is.null(opt$numvars)) {
				params[["vin"]] = (colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))])[1:opt$numvars];
			} else {
				params[["vin"]] = c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
			}
		}
	}

	if (opt$method  == "aloja_print_individual_summaries" || opt$method  == "aloja_print_summaries")
	{
		params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
	}

	if (opt$method  %in% c("aloja_predict_instance","aloja_predict_dataset","aloja_outlier_dataset","aloja_outlier_instance"))
	{
		params_2 <- list();
		params_2[["tagname"]] <- opt$learned;
		params[["learned_model"]] <- do.call(aloja_load_object,params_2);
	}

	if (opt$method == "aloja_dataset_clustering")
	{
		params_3 <- list();
		params_3[["tagname"]] <- opt$learned;
		params[["na.predict"]] <- do.call(aloja_load_object,params_3);
	}

	if (!is.null(opt$params))
	{
		saux_1 <- strsplit(opt$params, ":");
		saux_2 <- strsplit(saux_1[[1]],"=");

		for (i in 1:length(saux_2))
		{
			params[[saux_2[[i]][1]]] <- strsplit(saux_2[[i]][2],",")[[1]];
		}
		rm(saux_1,saux_2);
	}

	if (is.null(params$vin) && opt$method  == "aloja_predict_instance")
	{
		if (length(params$inst_predict) == length(params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
		}
	}
	if (is.null(params$vin) && opt$method  == "aloja_predict_dataset")
	{
		if (all(colnames(params$ds) %in% params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster","Cl.Name","Datanodes","Headnodes","VM.OS","VM.Cores","VM.RAM","Provider","VM.Size","Type");
		}
	}

###############################################################################
# Execute call

	result <- do.call(opt$method,params);

	if (opt$verbose) result;

###############################################################################
# C'est fini

	quit(save="no", status=0);

REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		forever foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct try
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall forever]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| #get pos: (process-get-directive pos/1 pos)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	make-typeset: func [
		spec [block!] option [block! none!]
		/local cache bs ts word bit idx name
	][
		cache: []										;-- [types array name...]
		spec: sort spec									;-- sort types to reduce cache misses
		
		either bs: find/only/skip cache spec 3 [
			ts: bs/2
			name: bs/3
		][
			ts: copy [0 0 0]

			foreach type spec [
				type: either word: in extracts/scalars type [get word][reduce [type]]
				
				foreach word type [
					word: head remove back tail form word	;-- remove ending #"!"
					replace/all word #"-" #"_"
					type: to word! uppercase head insert word "TYPE_"
					bit: select extracts/definitions type
					idx: (bit / 32) + 1
					poke ts idx ts/:idx or shift/logical -2147483648 bit and 255
				]
			]
			forall ts [ts/1: to integer! to-bin32 ts/1]	;-- convert to little-endian values
			
			redirect-to literals [
				name: decorate-series-var 'ts
				emit reduce [to set-word! name 'typeset/create ts/1 ts/2 ts/3]
				insert-lf -5
			]
			append cache reduce [spec ts name]
		]
		either option [
			option: to word! join "~" clean-lf-flag option/1
			reduce ['type-check-alt option name]
		][
			reduce ['type-check name]
		]
	]
	
	emit-type-checking: func [name [word!] spec [block!] /local pos type][
		name: to word! next form name					;-- remove prefix decoration
		
		either pos: find spec name [
			type: case [
				block? pos/2 					[pos/2]
				all [string? pos/3 block? pos/3][pos/3]
				'else 							[[default!]]
			]
			make-typeset type find/reverse pos refinement!
		][
			none
		]
		
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit [[stack/adjust]]
			][
				mark: tail output
				unless head? path [
					emit [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
								if path? pc/1 [emit [as red-path!]]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
							emit [as red-path!]
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
							if path? pc/1 [emit [as red-path!]]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-change*
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-change*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-change* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-try: does [
		unless block? pc/1 [
			pc: back pc
			comp-word									;-- fallback to interpreter
			exit
		]
		emit [catch RED_ERROR]
		insert-lf -2
		body: comp-sub-block 'try
		if body/1 = 'stack/reset [remove body]
		mark: tail output
		emit-open-frame 'try
		insert body mark
		clear mark
		append body [
			stack/unwind
		]
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
	
	comp-forever: does [
		pc: back pc
		change/part pc [while [true]] 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk args?
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		args?: yes
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			if symbols/1 = '~local [args?: no]			;-- signal end of arguments
			
			if all [
				args?
				blk: emit-type-checking symbols/1 spec
			][
				append init blk
				append init (index? symbols) - 1		;-- index of argument for the type-checker
			]
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native words/_body
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec select objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			redirect-to literals [
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			]
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame op
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-get-directive: func [
		path code [block!] /local obj ctx blk
	][
		unless path? path [
			throw-error ["invalid #get argument:" spec]
		]
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 2
		blk: [red/word/get-in (decorate-exec-ctx ctx) (get-word-index/with last path ctx)]
		insert code compose blk
	]
	
	process-in-directive: func [
		path word code [block!] /local obj ctx blk
	][
		if any [not path? path not any-word? :word][
			throw-error ["invalid #in argument:" mold path mold :word]
		]
		append path word
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 3
		blk: [red/object/get-word (decorate-exec-ctx ctx) (get-word-index/with word ctx)]
		insert code compose blk
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc form load-cache %version.r
				comp-expression
				true
			]
			#build-date [
				change pc mold now
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
# Cleans up the data needed for the hummingbird migration project. 
# Only needs to be done once with the raw files sent from FAL
# files in "eBird_checklists_2008-2014
# SRS 25 Feb 2015

library(chron)
library(tools)


#path to files
filepath = "/home/sarah/Dropbox/Hummingbirds/hb_migration_data/ebird_raw/eBird_checklists_2008-2014/"
writepath = "/home/sarah/Dropbox/Hummingbirds/hb_migration_data/ebird_raw/eBird_checklists_2008-2014/aggregated_by_species/"


#----------------------------------------------------FUNCTIONS
GroupDuplicates = function(humdat) { 
  #gets rid of duplicate records that are part of the same group. 
  #Takes only the first record to move to analysis, keeps all single records that are not part of a group.
  gid = sort(unique(humdat$GROUP_ID))
  #gid = gid[which(gid!=NA)]
  
  #open start a new dataframe with same columns as the main dataframe
  keep = humdat[1,]
  out = 0
  
  for (g in 1:length(gid)){
    out = out + 1
    tmp = humdat[which(humdat$GROUP_ID == gid[g]),]
    #record the first line of the data (assume the group has the same information)
    if (nrow(tmp) == 1) { 
      keep[out,] = tmp
    }
    else{
      keep[out,] = tmp[1,]
    }
  }
  
  keepnongroup = humdat[which(is.na(humdat$GROUP_ID)),]
  keep = rbind(keep, keepnongroup)
  return(keep)
}


#------------------------------------------------ AGGREGATE THE FILES
files = list.files(path = filepath, pattern = "eBird_checklists_*", recursive=TRUE, full.names=TRUE)

for (f in 1:length(files)){
  data = read.table(files[f], header=TRUE, sep="\t", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  #really ugly regex to pull month from filename
  MONTH = as.numeric(sub("_20[0-9][0-9]", "", sub("eBird_checklists_", "", basename(file_path_sans_ext(files[f])))))
  MONTH = rep(MONTH, nrow(data))
  data = cbind(data, MONTH)
  
  if (f == 1) {
    agg_data = data
  }
  else{
    agg_data = rbind(agg_data, data)
  }
  print (paste("file", f, "is completed:", basename(file_path_sans_ext(files[f]))))
}

# print the species names
unique(agg_data$SCI_NAME)

#put migratory species in separate datafiles
bchu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Archilochus alexandri"),])
ruhu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Selasphorus rufus"),])
bthu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Selasphorus platycercus"),])
rthu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Archilochus colubris"),])
cahu = GroupDuplicates(agg_data[which(agg_data$SCI_NAME == "Selasphorus calliope"),])

#write the files to the folder for output
write.table(bchu, file = paste(writepath,"bchu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(ruhu, file = paste(writepath,"ruhu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(bthu, file = paste(writepath,"bthu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(rthu, file = paste(writepath,"rthu08-14.txt", sep=""), row.names=FALSE, sep=",")
write.table(cahu, file = paste(writepath,"cahu08-14.txt", sep=""), row.names=FALSE, sep=",")

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")

     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          pch = 21,
          bg = "navy",
          col = "navy",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     xarea <- c(Day.Index, rev(Day.Index))
     yarea <- c(Pageviews, rep(0, nrow(data)))
     polygon(xarea, yarea, col = rgb(0.3, 0.8, 1, 0.5), border=NA)     
     
     abline(a = 100, 
            b = 0,
            col = "gray")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          col = "blue",
          pch = 21,
          bg = "navy",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     abline(a = 100, 
            b = 0,
            col = "gray")
     
     xarea <- c(Day.Index, rev(Day.Index))
     yarea <- c(Pageviews, rep(0, nrow(data)))
     polygon(xarea, yarea, col = "light blue")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          col = "blue",
          main = "Google Analytics",
          ylim = c(0, 200)) 
     
     abline(a = 100, 
            b = 0,
            col = "gray")
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b",
          col = "blue",
          main = "Google Analytics",
          ylim = c(0, 200)) 
})

data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")

with(data, {
     Day.Index <- as.Date(Day.Index, format="%m/%d/%Y")
     
     plot(Day.Index, 
          Pageviews,
          xlab = "Date",
          type = "b")
})

# data <- read.csv("~/workspace/data/ga-hoolihan.csv", sep=",")
data <- read.csv("~/workspace/data/ga2-hoolihan.csv", sep=",")
data$Day.Index <- as.Date(data$Day.Index, format="%m/%d/%Y")

plot(data$Day.Index, 
     data$Pageviews,
     xlab = "Date",
     type = "b")

#' General-purpose data munging
#'
#' One can use \code{munge} to take a \code{data.frame}, apply a given set
#' of transformations, and persistently store the operations on
#' the \code{data.frame}, ready to run on a future \code{data.frame}.
#'
#' @param dataframe a data set to operate on.
#' @param ... usually a list specifying the necessary operations (see
#'    examples).
#' @param stagerunner logical or list. Whether to run the munge procedure or
#'    return the parametrizing stageRunner object (see package stagerunner).
#'    If a list, one can specify \code{remember = TRUE} to pass to the
#'    stageRunner initializer.
#' @param train_only logical. Whether or not to leave the \code{trained}
#'    parameter on each mungebit to \code{TRUE} or \code{FALSE} accordingly.
#'    For example, if \code{stagerunner = TRUE} and we are planning to re-use
#'    the stagerunner for prediction, it makes sense to leave the mungebits
#'    untrained. (Note that this will prevent one from being able to run the
#'    predict functions!)
#' @return data.frame that has had the specified operations applied to it,
#'    along with an additional property \code{mungepieces} that records
#'    the history of applied functions. These can be used to reproduce
#'    the transformations on e.g., a dataset that needs to have a
#'    prediction run.
#' @export
#' @examples
#' \dontrun{
#' iris2 <- munge(iris,
#'   list(column_transformation(function(x) 2 * x), 'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#'
#' iris2 <- munge(iris,
#'    # train function & predict function
#'    list(c(column_transformation(function(x) 2 * x),
#'         column_transformation(function(x) 3 * x)),
#'    # arguments to pass to transformation, i.e. column names in this case
#'    'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#' iris3 <- munge(iris, attr(iris2, 'mungepieces'))
#' # used transformations ("mungepieces") stored on iris2 and apply to iris3.
#' # They will remember that they've been trained already and run the
#' # prediction routine instead of the training routine. Note the above is
#' # also equivalent to the shortcut: munge(iris, iris2)
#' stopifnot(iris3[['Sepal.Length']] == iris[['Sepal.Length']] * 3)
#' }
munge <- function(dataframe, ..., stagerunner = FALSE, train_only = FALSE) {
  mungepieces <- list(...)
  if (length(mungepieces) == 0) return(dataframe)

  plane <- if (is.environment(dataframe)) dataframe else mungeplane(dataframe)

  if (is.data.frame(mungepieces[[1]]))
    mungepieces[[1]] <- attr(mungepieces[[1]], 'mungepieces')
  else if (is(mungepieces[[1]], 'tundraContainer'))
    mungepieces[[1]] <- mungepieces[[1]]$munge_procedure

  # If mungepieces[[1]] is of the form
  # list(list|mungepiece|function, list|mungepiece|function, ...)
  # just put it into mungepieces. This is so munge can be called as either
  # munge(dataframe, list(...)) or munge(dataframe, ...)
  if (length(mungepieces) == 1 && is.list(mungepieces[[1]]) &&
      all(unlist(lapply(mungepieces[[1]],
        function(x) is.mungepiece(x) || is.mungebit(x) || is.list(x) || is.function(x))))) {
      mungepieces <- mungepieces[[1]]
  }

  mungepieces <- lapply(mungepieces, parse_mungepiece,
                        train_only = !identical(train_only, FALSE))

  # order matters, do not parallelize!
  stages <- lapply(mungepieces, function(piece) {
    force(piece); function(env) piece$run(env)
  })
  stages <- append(stages, list(function(env) {
    # For now, store the mungepieces on the dataframe
    if (length(mungepieces) > 0)
      attr(env$data, 'mungepieces') <- append(attr(env$data, 'mungepieces'), mungepieces)
  }))
  names(stages)[length(stages)] <- "(Internal) Store munge procedure on dataframe"

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) require(stagerunner)
  remember <- if ('remember' %in% names(stagerunner)) stagerunner$remember else FALSE
  runner <- stageRunner$new(as.environment(plane), stages, remember = remember)

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) runner
  else {
    runner$run()
    plane$data
  }
}

require(ggplot2)
require(grid)
require(gtable)
require(gridExtra) # just for multiplot demos.

testplot=(ggplot(mtcars, aes(wt, hp))
	+geom_point())

grid.arrange(testplot, mirror.ticks(testplot))

# The reason I did this in the first place: 
# My advisor prefers INWARD-facing ticks on all sides.
testplot.fancy=(ggplot(mtcars, aes(wt, hp, color=factor(cyl)))
	+geom_point()
	+theme_bw()
	+theme(
		panel.grid.major = element_blank(), 
			panel.grid.minor = element_blank(), 
			axis.ticks.length = unit(-0.25 , "cm"),
			axis.ticks.margin = unit(0.5 , "cm")))

grid.arrange(testplot.fancy, mirror.ticks(testplot.fancy))mirror.ticks = function(ggobj, allPanels=FALSE){
	# Given a ggplot object with axes on the bottom and left, 
	# add matching axes on the top and right.
	# For a multipanel figure: 
	# if allPanels=F, mirrors ticks to the other end of the row/column. 
	# allPanels=T *not yet implemented*, 
	# when done it will mirror ticks from B->T and L->R within EACH panel...
	# But think about whether that's really what you want! 
	# The last thing most multipanel plots need is more tick marks.

	require(gtable)
	
	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	ggobj = ggplotGrob(ggobj)

	panel_extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax_x = rtax$children$axis$grobs[[rttick]]$x
		rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
		class(rtax_x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax_x

		topax_y = topax$children$axis$grobs[[toptick]]$y
		topax_y = sapply(topax_y, swaptick, simplify=FALSE)
		class(topax_y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax_y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj, allPanels=FALSE){
	# Given a ggplot object with axes on the bottom and left, 
	# add matching axes on the top and right.
	# For a multipanel figure: 
	# if allPanels=F, mirrors ticks to the other end of the row/column. 
	# allPanels=T *not yet implemented*, 
	# when done it will mirror ticks from B->T and L->R within EACH panel...
	# But think about whether that's really what you want! 
	# The last thing most multipanel plots need is more tick marks.

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax_x = rtax$children$axis$grobs[[rttick]]$x
		rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
		class(rtax_x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax_x

		topax_y = topax$children$axis$grobs[[toptick]]$y
		topax_y = sapply(topax_y, swaptick, simplify=FALSE)
		class(topax_y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax_y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax_x = rtax$children$axis$grobs[[rttick]]$x
		rtax_x = sapply(rtax_x, swaptick, simplify=FALSE)
		class(rtax_x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax_x

		topax_y = topax$children$axis$grobs[[toptick]]$y
		topax_y = sapply(topax_y, swaptick, simplify=FALSE)
		class(topax_y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax_y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax.x = rtax$children$axis$grobs[[rttick]]$x
		rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
		class(rtax.x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax.x

		topax.y = topax$children$axis$grobs[[toptick]]$y
		topax.y = sapply(topax.y, swaptick, simplify=FALSE)
		class(topax.y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax.y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=cur_panel$t,
			l=cur_panel$l,
			r=cur_panel$r,
			b=cur_panel$b,
			z=cur_panel$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

		rttxt = axgrep(rtax$children$axis, "text")
		toptxt = axgrep(topax$children$axis, "text")
		rttick = axgrep(rtax$children$axis, "ticks")
		toptick = axgrep(topax$children$axis, "ticks")

		rtax$children$axis$grobs[[rttxt]]$label = NULL
		topax$children$axis$grobs[[toptxt]]$label = NULL

		rtax.x = rtax$children$axis$grobs[[rttick]]$x
		rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
		class(rtax.x) = c("unit.list", "unit")
		rtax$children$axis$grobs[[rttick]]$x = rtax.x

		topax.y = topax$children$axis$grobs[[toptick]]$y
		topax.y = sapply(topax.y, swaptick, simplify=FALSE)
		class(topax.y) = c("unit.list", "unit")
		topax$children$axis$grobs[[toptick]]$y = topax.y

		ggobj = gtable_add_grob(
			x=ggobj,
			grobs=list(rtax, topax),
			t=panel.extents$t,
			l=panel.extents$l,
			r=panel.extents$r,
			b=panel.extents$b,
			z=panel.extents$z,
			name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	axes = gtable_filter(ggobj, "axis", trim=FALSE)
	nulls = sapply(axes$grobs, function(x)any(class(x) == "zeroGrob"))
	axis_extents = axes$layout

	for(i in 1:nrow(panel_extents)){
		cur_panel = panel_extents[i,]
		cur_axes = match.axes(cur_panel)
		rtax = axes$grobs[[cur_axes[1]]]
		topax = axes$grobs[[cur_axes[2]]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	}
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout
	is_toprow = (panel_extents$b == min(panel_extents$b))
	is_rtcol = (panel_extents$l == max(panel_extents$l))

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	match.axes = function(panel){
		# Find *left* axes in same row by matching *bottom* extent, 
		# find *bottom* axes in same column by matching *left* extent.
		lax =  which(axis_extents$b == panel$b & !nulls)
		bax = which(axis_extents$l == panel$l & !nulls)
		

		# FIXME: How to efficiently handle all these cases?
		# 1 panel bl->bltr
		# multipanel shared axes -> mirror to other end of row/col
		# multipanel axes differ -> mirror to... same panel?

		# may be able to assume null axes -> treat as same across row/col

		if(length(lax) > 1 || length(bax) > 1){
			# Multiple axes in this row/col, e.g. facet_wrap(..., scales="free")
			# *should* be safe to handle lax>1 and bax>1 identically, right?
			lax = which(axis_extents$b == panel$b & axes$layout$l == panel$l-1)
			bax = which(axis_extents$l == panel$l & axes$layout$b == panel$b+1)
		}
		if(length(lax) == 1 && length(bax) == 1){
			return(c(lax[[1]], bax[[1]]))
		}else{
			stop("Can't match axes to panel!")
		}	
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	swaptick = function(tick){
	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL


	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
## Creates RcppArmadillo S3 object export within R
avar = function(x, ...) UseMethod("avar")

avar.default = function(x, ...) {
  x = as.vector(x)
  av = .Call('GMWM_avar_fixed_arma', PACKAGE = 'GMWM', x)
  av$adev = sqrt(av$allan)
  av$lci = av$adev - av$errors*av$adev
  av$uci = av$adev + av$errors*av$adev
  class(av) = "avar"
  av
}

print.avar = function(x, ...) {
  cat("\n Clusters: \n")
  print(x$clusters, digits=5)
  cat("\n Allan Variances: \n")
  print(x$allan, digits=5)
  cat("\n Errors: \n")
  print(x$errors, digits=5)
}

plot.avar = function(x, ...){
  plot(x$clusters, x$adev,log="xy",
       xlab=expression("Scale " ~ tau),
       ylab=expression("Allan Deviation " ~ phi[tau]),
       main=expression(log(tau) ~ " vs. " ~ log(phi[tau]))
  )
  lines(x$clusters, x$adev, type="l")
  lines(x$clusters, x$lci, type="l", col="grey", lty=2)
  lines(x$clusters, x$uci, type="l", col="grey", lty=2)
}

summary.avar = function(x, ...) {
  out_matrix = matrix(0, nrow = length(x$clusters), ncol = 6)
  colnames(out_matrix) = c("Time", "AVAR", "ADEV", "Lower CI", "Upper CI", "Error")
  out_matrix[,"Time"] = x$clusters
  out_matrix[,"AVAR"] = x$allan
  out_matrix[,"ADEV"] = x$adev
  out_matrix[,"Lower CI"] = x$lci
  out_matrix[,"Upper CI"] = x$uci
  out_matrix[,"Error"] = x$errors
  
  class(x) = "summary.avar"
  out_matrix
}

print.summary.avar = function(x, ...) {
  print(x)
  invisible(x)
}mirror.ticks = function(ggobj){
	# Given a one-panel ggplot object with axes on the bottom and left,  
	# add matching axes on the top and right.
	# TODO: Make work with multi-panel plots by passing in panel number
	# 	(panel-1, panel-2, etc). Note "axis_l-1" vs 1-panel "axis-l").

	require(gtable)
	
	ggobj = ggplotGrob(ggobj)

	panel.extents = gtable_filter(ggobj, "panel", trim=FALSE)$layout

	rtax = gtable_filter(ggobj, "axis-l")$grobs[[1]]
	topax = gtable_filter(ggobj, "axis-b")$grobs[[1]]

	axgrep = function(gtab, pattern){
			which(sapply(gtab$grobs, function(x)grepl(pattern, x$name)))}

	rttxt = axgrep(rtax$children$axis, "text")
	toptxt = axgrep(topax$children$axis, "text")
	rttick = axgrep(rtax$children$axis, "ticks")
	toptick = axgrep(topax$children$axis, "ticks")

	rtax$children$axis$grobs[[rttxt]]$label = NULL
	topax$children$axis$grobs[[toptxt]]$label = NULL

	# Tick coordinates are encoded as 1npc for the end on the axis line 
	# 	and 1npc-axis.tick.length for the other end. 
	# We'll move ticks to the other side of the line by flipping the sign
	# 	of the subtraction.
	swaptick = function(tick){
		if(inherits(tick, "unit.arithmetic")){
			tick[[3]] = unit(
				-c(tick[[3]]), # drop unit class and invert bare numeric values
				attr(tick[[3]], "unit")) # add original unit class back on
			return(tick)
		} else {
			return(tick)
		}
	}

	rtax.x = rtax$children$axis$grobs[[rttick]]$x 
	rtax.x = sapply(rtax.x, swaptick, simplify=FALSE)
	class(rtax.x) = c("unit.list", "unit")
	rtax$children$axis$grobs[[rttick]]$x = rtax.x
	
	topax.y = topax$children$axis$grobs[[toptick]]$y 
	topax.y = sapply(topax.y, swaptick, simplify=FALSE)
	class(topax.y) = c("unit.list", "unit")
	topax$children$axis$grobs[[toptick]]$y = topax.y

	ggobj = gtable_add_grob(
		x=ggobj, 
		grobs=list(rtax, topax), 
		t=panel.extents$t,
		l=panel.extents$l,
		r=panel.extents$r,
		b=panel.extents$b, 
		z=panel.extents$z, 
		name=c("axis-r", "axis-t"))
	return(ggobj)
}
library(ggplot2)
library(devtools) # for file downloads from Github
library(grid)
library(gtable)

source("ggthemes.r")
source_url("https://raw.githubusercontent.com/infotroph/ggplot-ticks/master/mirror.ticks.r")

carplot = (ggplot(mtcars, aes(wt, mpg))
	+geom_point()
	+geom_smooth(se=FALSE)
	+theme_ggEHD())

# Note that mirror.ticks converts the plot from a ggplot object 
# to a gtable object. Don't call it until you've finished modifying 
# the rest of the plot.

plot(mirror.ticks(carplot))theme_ggEHD = function(base_size=18, ...){
	(theme_bw(base_size=base_size) %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		rect = element_rect(size=rel(0.75)),
		line = element_line(size=rel(1)),
		axis.ticks.length = unit(-(base_size*0.5), "points"),
		axis.ticks.margin = unit((base_size*1.5), "points"),
		plot.margin = unit(base_size*c(1,1,1,1), "points"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=base_size,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}theme_ggEHD = function(base_size=18, ...){
	(theme_bw(base_size=base_size) %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-(base_size*0.75), "points"),
		axis.ticks.margin = unit((base_size*1.5), "points"),
		plot.margin = unit(base_size*c(1,1,1,1), "points"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=base_size,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}theme_ggEHD = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		plot.margin = unit(c(1,1,1,1), "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title.x=element_text(vjust=-1),
		axis.title.y=element_text(vjust=2),
		aspect.ratio=0.75,
		...
	))
}theme_ggEHD = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title=element_text(vjust=0.3),
		aspect.ratio=0.75,
		...
	))
}getPage2Plots = function(updateProgress = NULL,cancer, gene, sampleSelection) {
  
  if (gene == "")
  {
    return()
  }
  if (is.null(gene))
  {
    return()
  }
  
	if (sampleSelection == 1) {
		#priorDetails = tcgaResults[[cancer]]$prioritize.details
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = tcga.cna[[cancer]][[1]]
		acgh.group2 = tcga.mn.cna[[cancer]][[1]]
		achilles.ut = tcgaResultsAT[[cancer]][2]
		achilles.lt = tcgaResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#56B4E9")
		lab.group1="Tumors" 
		lab.group2="Normals"
		pvalue=TRUE
		cls = tcgaResults[[cancer]]$cls
	} else if (sampleSelection == 2) {
	  #priorDetails = ccleResults[[cancer]]$prioritize.details
		priorDetails = ccleResultsPrioDetails[[cancer]]
		exprs.group1 = ccle.exprs.combat[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = ccle.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.mn.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#009E73", "#56B4E9")
		lab.group1="Cell lines" 
		lab.group2="Normals"
		pvalue=TRUE
		cls = ccleResults[[cancer]]$cls
	} else {
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs.combat[[cancer]][[1]]
		exprs.group2 = ccle.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth.combat[[cancer]]
		#meth.group2 = tcga.mn.meth.combat[[cancer]]
		acgh.group1 = tcga.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#009E73")
		lab.group1="Tumors" 
		lab.group2="Cell lines"
		pvalue=FALSE
		cls = tcgaResults[[cancer]]$cls
	}
	#meth.anno = infinium450.probe.ann
  if (is.element(gene,rownames(achilles)))
  {
   achls = achilles[gene, cls]    
  }else{
    achls = NULL
  }
	#achls = achilles
	
	plots = plotGene(gene, priorDetails, samples=NULL, 
		 	 exprs.group1, exprs.group2, 
		 	 #meth.group1, meth.group2, meth.anno, 
		 	 acgh.group1, acgh.group2, 
		 	 achls, achilles.ut, achilles.lt, 
		 	 lab.group1=lab.group1, lab.group2=lab.group2, 
		 	 color.palette=color.palette,
		 	 size=4, width=0.2, pvalue=pvalue)
# 	if (sampleSelection != 1) {
# 		plots[["methylation"]] = NULL
# 	}
	if (sampleSelection == 3) {
		plots[["achilles"]] = NULL
	}
	
	plots
}
theme_ggEHD = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title=element_text(vjust=0.3),
		...
	))
}library(rjson)
library(RCurl)

#' Connect to the AmCAT API
#'
#' Connect to the AmCAT API and requests a temporary (24h) authentication token that will be stored in the output
#' If username and password are not given, a file ~/.amcatauth will be read, which should be a csv file with
#' columns host (may be *), username, password. If the file cannot be read, username will be taken from $USER
#' and the user will be prompted for the password.
#' 
#' @param host the hostname, e.g. http://amcat.vu.nl or http://localhost:8000
#' @param username the username to login with, e.g. 'amcat'. 
#' @param passwd the password to login with, e.g. 'amcat'
#' @param token an existing token to authenticate with. If given, username and password are not used and the token is not tested
#' @param disable_ipv6. If True, only use ipv4 resolving (faster if ipv6 causes timeout). Defaults to true, but this may change in the future.
#' @return A list with authentication information that is used by the other functions in this package
#' @export
amcat.connect <- function(host, username=NULL, passwd=NULL, token=NULL, disable_ipv6=TRUE) {
  opts = if (disable_ipv6) list(ipresolve=1) else list()
  
  if (is.null(token)) {
    if (is.null(passwd)) { # try amcatauth file
      a = tryCatch(.readauth(host), error=function(e) warning("Could not read ~/.amcatauth"))
      if (!is.null(a)) {
        username = a$username
        passwd = a$password
      }
    }
    if (is.null(username)) { # try USER variable
      username = Sys.getenv("USER")
      if (username == '') { # ask
        cat(paste("Please enter the username for", host, "\n"))
        username=readline()
      }
    }
    if (is.null(passwd)) { #ask
      cat(paste("Please enter the password for ",username,"@", host, " (or create a ~/.amcatauth file) \n", sep=""))
      passwd=readline()
    }
    # get auth token
    url = paste(host, '/api/v4/get_token', sep='')
    
    res = tryCatch(postForm(url, username=username, password=passwd, .checkParams=F, .opts=opts), 
                   error=function(e) stop(paste("Could not get token from ",
                                                 username,":",passwd,"@", host,
                                                 " please check host, username and password. Error: ", e, sep="")))
    token = fromJSON(res)$token
  }
  list(host=host, token=token, opts=opts)
}

#' Get authentication info from ~/.amcatauth file
.readauth <- function(host) {
  if (!file.exists("~/.amcatauth")) return()
  rows = read.csv("~/.amcatauth", header=F, stringsAsFactors=F)
  colnames(rows) <- c("host", "username", "password")
  r = rows[rows$host == '*' | rows$host == host,]
  if (nrow(r) > 0) list(username=r$username[1], password=r$password[1]) 
}


#' Retrieve a single URL from AmCAT with authentication and specified filters (GET or POST) 
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param path the path of the url to retrieve (using the host from conn)
#' @param filters a named vector of filters, e.g. c(project=2, articleset=3)
#' @param post use HTTP POST instead of GET
#' @return the raw result
#' @export
amcat.getURL <- function(conn, path, filters=NULL, post=FALSE, post_options=list(), error_unless_200=TRUE) {
  httpheader = c(Authorization=paste("Token", conn$token))
  url = parse_url(conn$host)
  url$path = paste(path, sep="/")
  h = getCurlHandle()
  # strip NULL filters
  for (n in names(filters)) if (is.null(filters[[n]])) filters[[n]] <- NULL
  if (!post) {
    # convert list(a=c(1,2)) to list(a=1, a=2). From: http://stackoverflow.com/a/22346656
    url$query = structure(do.call(c, lapply(filters, function(z) as.list(z))), names=rep(names(filters), sapply(filters, length)))
    
    # build GET url query
    url = build_url(url)
    message("GET ", url)
    result = getURL(url, httpheader=httpheader, .opts=conn$opts, curl=h)
    if (getCurlInfo(h)$response.code != 200){
      if (error_unless_200) stop("Unexpected Response Code ", getCurlInfo(h)$response.code, "\n", result)
      return(NULL)
    }
    result
  } else {  
    
    post_opts = modifyList(conn$opts, list(httpheader=httpheader))
    post_opts = modifyList(post_opts, post_options)
    postForm(build_url(url), .params=filters, .opts=post_opts)
  }
}

#' Get and rbind pages from the AmCAT API
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param path the path of the url to retrieve (using the host from conn)
#' @param filters: a named vector of filters, e.g. c(project=2, articleset=3)
#' @param post use HTTP POST instead of GET
#' @param page: the page number to start retrieving
#' @param page_size: the number of rows per page
#' @param max_page: the page number to stop retrieving at, if given
#' @return dataframe 
#' @export
amcat.getpages <- function(conn, path, format='csv', page=1, page_size=1000, filters=NULL, post=FALSE, max_page=NULL) {
  filters = c(filters, page_size=page_size, format=format)
  result = data.frame()
  while (TRUE) {
    if (!is.null(max_page)) if (page > max_page) break
    page_filters = c(filters, page=page)
    subresult = amcat.getURL(conn, path, page_filters, post=post)
    if (subresult == "") break
    subresult = .amcat.readoutput(subresult, format=format)
    result = rbind(result, subresult)
    if(nrow(subresult) < page_size) break
    page = page + 1
  }
  result
}

#' Get objects from the AmCAT API
#'
#' Get a table of objects from the AmCAT API, e.g. projects, sets etc.
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param resource the name of the resource, e.g. 'projects'. If it is of length>1, a path a/b/c/ will be created (e.g. c("projects",1,"articlesets"))
#' @param ... Other options to pass to \code{\link{amcat.getpages}}, e.g. page_size, format, and filters
#' @return A dataframe of objects (rows) by properties (columns)
#' @export
amcat.getobjects <- function(conn, resource, ...) {
  if (length(resource) > 1) resource = paste(c(resource, ""), collapse="/")
  path = paste('api', 'v4', resource, sep='/')
  amcat.getpages(conn, path, ...)
}

#' Internal call to check GET results and parse as csv or json
.amcat.readoutput <- function(result, format){
  if (result == '401 Unauthorized')
    stop("401 Unauthorized")
  if (format == 'json') {
    result = fromJSON(result)
    
  } else  if (format == 'csv') {
    con <- textConnection(result)
    result = tryCatch(read.csv(con), 
                      error=function(e) data.frame())
  }
  result
}

#' Run an action from the AmCAT API
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param action the name of the action
#' @param format the format to request, e.g. csv or json
#' @param ... any additional (e.g. action-specific) arguments to pass to the action API
#' @return A dataframe containing the result of the action [WvA: shouldn't that depend on the action??]
#' @export
amcat.runaction <- function(conn, action, format='csv', ...) {
  resource = 'api/action'
  url = paste(conn$host, resource, action, sep="/")
  url = paste(url, '?format=', format, sep="")
  message("Running action at ", url)
  httpheader = c(Authorization=paste("Token", conn$token))
  result = postForm(url, ..., .opts=list(httpheader=httpheader))
  
  if (result == '401 Unauthorized')
    stop("401 Unauthorized")
  if (format == 'json') {
    result = fromJSON(result)
  } else  if (format == 'csv') {
    con <- textConnection(result)
    result = read.csv2(con)
  }
  result
}

#' Get article metadata from AmCAT
#'
#' Uses the \code{\link{amcat.getobjects}} function to retrieve article metadata, and applies some
#' additional postprocessing, e.g. to convert the data to Date objects.
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param set the article set id to retrieve
#' @param filters additional filters, e.g. list(medium=1)
#' @param columns the names of columns to retrieve
#' @param time if true, parse the date as POSIXct datetime instead of Date
#' @param dateparts if true, add date parts (year, month, week)
#' @param medium_names if true, retrieve medium names and turn medium column into a factor
#' @param ... additional arguments are passed to \code{\link{amcat.getpages}}. Useful arguments include page_size, page (starting page) and maxpage (end page)
#' @return A dataframe containing the articles and the selected columns
#' @export
amcat.getarticlemeta <- function(conn, set, filters=list(), columns=c('id','date','medium','length'), time=F, dateparts=F, medium_names=T, ...){
  filters[['articleset']] = set 
  result = amcat.getobjects(conn, "articlemeta", filters=filters, ...)
  if(length(columns > 0)) result = result[,columns]
  if ("date" %in% names(result)) {
    result$date = (if(time == T) as.POSIXct(result$date, format='%Y-%m-%d %H:%M:%S') 
                   else as.Date(result$date, format='%Y-%m-%d'))
  }
  if (dateparts) {
    result$year = as.Date(format(result$date, '%Y-1-1'))
    result$month = as.Date(format(result$date, '%Y-%m-1'))
    result$week = as.Date(paste(format(result$date, '%Y-%W'),1), '%Y-%W %u')
  }
  if (medium_names) {
    media = unique(result$medium)
    # make filter from names by adding names (pk=)
    names(media) = rep("pk", length(media))
    media = amcat.getobjects(conn, "medium", filters=media)
    result$medium = factor(result$medium, levels=media$id, labels=media$name)
  }
  return(result)
}


#' Add articles to an article set
#' 
#' Add the given article ids to a new or existing article set
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param project the project to add the articles to
#' @param articles a vector of article ids
#' @param articleset the article set id of an existing set
#' @param articleset.name the name for a new article set
#' @param articleset.provenance a provenance text for a new article set
#' @return The articleset id of the new or existing article set
#' @export
amcat.add.articles.to.set <- function(conn, project, articles, articleset=NULL,
                                      articleset.name=NULL, articleset.provenance=NULL) {
  if (is.null(articleset)) {
    if (is.null(articleset.name)) 
      stop("Provide articleset or articleset.name")
    path = paste("api", "v4", "projects",project, "articlesets", "?format=json", sep="/")
    if (is.null(articleset.provenance)) 
      articleset.provenance=paste("Uploaded", length(articles), "articles from R on", format(Sys.time(), "%FT%T"))
    r = amcat.getURL(conn, path, filters=list(name=articleset.name, provenance=articleset.provenance), post=TRUE) 
    
    articleset = fromJSON(r)$id
    message("Created articleset ", articleset, ": ", articleset.name," in project ", project)
  }
  if (!is.null(articles)) {
    idlist = lapply(articles, function(x) list(id=x))
    url = paste(conn$host, "api", "v4", "projects",project, "articlesets", articleset, "articles", "", sep="/")
    
    resp = POST(url, body=toJSON(idlist), content_type_json(), accept_json(), add_headers(Authorization=paste("Token", conn$token)))
    if (resp$status_code != 201) stop("Unexpected status: ", resp$status_code, "\n", content(resp, type="text/plain"))
    content(resp)
  }
  articleset
}

#' Upload new articles to AmCAT
#' 
#' Upload articles into a given project and article set, or into a new article set if the articleset argument is character
#' All arguments headline, medium etc. should be either of the same length as text, or of length 1
#' All factor arguments will be converted to character using as.character
#' For date, please provide either a string in ISO notatoin (i.e. "2010-12-31" or "2010-12-31T23:59:00")
#' or a variable that can be converted to string using format(), e.g. Date, POSIXct or POSIXlt. 
#' The articles will be uploaded in batches of 100. 
#' 
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param project the project to add the articles to
#' @param articleset the article set id of an existing set, or the name of a new set to create
#' @param text the text of the articles to upload
#' @param headline the headlines of the articles to upload
#' @param medium the medium of the articles to upload. 
#' @param provenance if articleset is character, an optional provenance string to store with the new set
#' @param ... and additional fields to upload, e.g. author, byline etc. 
#' @export
amcat.upload.articles <- function(conn, project, articleset, text, headline, date, medium, provenance=NULL, ...) {
  
  n = length(text)
  if (is.character(articleset)) {
    if (is.null(provenance)) provenance=paste("Uploaded", n, "articles using R function amcat.upload.articles")
    articleset = amcat.add.articles.to.set(conn, project, articles=NULL, articleset.name=articleset, articleset.provenance=provenance) 
  }
  
  if (!is.character(date)) date = format(date, "%Y-%m-%dT%H:%M:%S")
  fields = data.frame(headline=headline, text=text, date=date, medium=medium, ...)
  # make sure all fields have correct length
  for (f in names(fields)) {
    if (is.factor(fields[[f]])) fields[[f]] = as.character(fields[[f]])
    if (length(fields[[f]]) == 1) fields[[f]] = rep(fields[[f]], n)
    if (length(fields[[f]]) != n) stop(paste("Field", f, "has incorrect length:", length(fields[[f]]), "should be 1 or ", n))
  }
  
  # not very efficient, but probably not the bottleneck
  chunks = split(fields, ceiling((1:n)/100))
  for(chunk in chunks) {
    json_data = vector("list", nrow(chunk))
    for (i in seq_along(json_data)) {
      json_data[[i]] = unlist(lapply(chunk, function(x) x[i]))
    }
    json_data = toJSON(json_data)
    message("Uploading ", nrow(chunk), " articles to set ", articleset)
    
    url = paste(conn$host, "api", "v4", "projects",project, "articlesets", articleset, "articles", "", sep="/")
    
    resp = POST(url, body=json_data, content_type_json(), accept_json(), add_headers(Authorization=paste("Token", conn$token)))
    if (resp$status_code != 201) stop("Unexpected status: ", resp$status_code, "\n", content(resp, type="text/plain"))
  }
  invisible(articleset)
}
theme_delucia = function(...){
	(theme_bw() %+% theme(
		panel.grid.major = element_blank(),
		panel.grid.minor = element_blank(),
		axis.ticks.length = unit(-0.75, "lines"),
		axis.ticks.margin = unit(1.5, "lines"),
		text=element_text( # Can we inherit some of these?
			family="",
			face="plain",
			size=18,
			hjust=0.5,
			vjust=0.5,
			angle=0),
		axis.title=element_text(vjust=0.3),
		...
	))
}REBOL [
	Title:   "Information extractor from Red runtime source code"
	Author:  "Nenad Rakocevic"
	File: 	 %extractor.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Notes: {
		These utility functions extract types ID and function definitions from Red
		runtime source code and make it available to the compiler, before the Red runtime
		is actually compiled.
		
		This procedure is required during bootstrapping, as the REBOL compiler can't
		examine loaded Red data in memory at runtime.
	}
]

context [
	definitions: make block! 100
	data: load-cache %runtime/macros.reds
	
	extract-defs: func [type [word!] /local list index][
		list: select data type
		
		index: 0
		forall list [
			if set-word? list/1 [
				list/1: to word! list/1
				index: list/2
			]
			if word? list/1 [
				repend definitions [list/1 index]
				index: index + 1
			]
		]
	]
	
	extract-defs 'datatypes!
	extract-defs 'actions!
	extract-defs 'natives!
	
	data: none
]#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and 
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/", 
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#' 
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    if (is.element('output', names(object))) {
      if (is.element("data", names(object$output$options))) {
        data_restore_on_exit <- object$output$options$data
        on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
        object$output$options$data <- NULL
      }
      if (is.element("label", names(object$output$options))) {
        label_restore_on_exit <- object$output$options$label
        on.exit(object$output$options$label <- label_restore_on_exit, add = TRUE)
        object$output$options$label <- NULL
      }
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

 # TODO: (RK) Read default_options in from config, so a user can
 # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- list(data = switch(1 + is.element("data", names(object$output$options)), 
                              NULL, object$output$options$data), 
                label = switch(1 + is.element("label", names(object$output$options)), 
                               NULL, object$output$options$label))

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
#library("teradataR")
library("RODBC")
library("dplyr")
library("assertthat")


#con <- tdConnect(dsn, uid = uid, pwd = pwd, database = database)
#a <- td.data.frame(test_table)
# tdQuery('select count(*) from airlines')
#tdClose()

#a1 <- as.td.data.frame(a, tableName = "airlines", database = "")

st <- src_teradata(host = dsn, user = uid, password = pwd, dbname = "")
a <- tbl(st, "airlines")

copy_nycflights13(st)
#copy_nycflights13(src_teradata(host = dsn, user = uid, password = pwd))
#copy_lahman(src_teradata(host = dsn, user = uid, password = pwd))

getS3method("collapse","tbl_sql")

a <- td.table(st$con,table = "airlines",database = "")

collapse(select(a))

a <- tbl(st, "airlines")
#library("teradataR")
# library("RODBC")
# library("dplyr")
# library(data.table)
# library("assertthat")


#' td.table - a R reference to Teradata table
td.table <- function(con, table, database = "") {
  if (missing(database) || is.null(database) || nchar(database) == 0) {
    obj <- gettextf("\"%s\"", table)
  } else obj <- gettextf("\"%s\".\"%s\"", database, table)
  query <- gettextf("SELECT * FROM %s SAMPLE 0", obj)
  res <- try(sqlQuery(con, query))
  if (is.null(attr(res, "class"))) {
    res <- data.table()
    attr(res, "totalRows") <- 0
    warning("Teradata table not found.  Result is empty data frame.")
  } else {
    query <- sprintf("SELECT CAST(COUNT(*) AS FLOAT) FROM %s", obj)
    res2 <- try(sqlQuery(con, query))
    attr(res, "totalRows") <- as.numeric(res2)
  }
  attr(res, "class") <- "td.table"
  attr(res, "tableName") <- table
  if (!is.null(database) && !missing(database) && nchar(database) > 0) {
    attr(res, "database") <- database
  } else {
    res2 <- try(sqlQuery(con, "SELECT DATABASE"))
    if (!is.null(attr(res2, "class")))
      attr(res, "database") <- as.character(res2[[1]])
  }
  return(res)
}

#' A src_teradata based on ODBC
#' @import RODBC
#' @export
#' @example
#' src_teradata(host = dsn, user = uid, password = pwd)
src_teradata <- function(host = NULL, dbname = NULL, port = NULL, user = NULL, password = NULL,  ...) {
  tdConnection <- NULL
  dsn <- host
  uid <- user
  pwd <- password
  database <- dbname

  # code adapted from teradataR's tdConnect function
  st <- paste0("DSN=", dsn)
  if (nchar(uid))
    st <- paste0(st, ";UID=", uid)
  if (nchar(pwd))
    st <- paste0(st, ";PWD=", pwd)
  if (nchar(database))
    st <- paste0(st, ";Database=", database)
  tdConnection <- odbcDriverConnect(st, ...)

  src <- src_sql("teradata", tdConnection)
  attr(src, "database") <- database
  #class(src$con) <- c(class(src$con),"tbl_sql")
  class(src) <- c(class(src),"tbl_sql")
  src
}

#' @export
src_desc.src_teradata <- function(xx) {
  x <- xx[[1]]
  # code taken from print.odbc of the RODBC package
  con <- strsplit(attr(x, "connection.string"), ";", fixed = TRUE)[[1L]]
  case <- paste("case=", attr(x, "case"), sep = "")
  cat("RODBC Connection ", as.vector(x), "\nDetails:\n  ", sep = "")
  cat(case, con, sep = "\n  ")
  invisible(x)
}

#' @export
db_list_tables.RODBC <- function(con) {
  sqlTables(con)
}

db_list_tables.src_teradata <- db_list_tables.RODBC

#' @export
db_has_table.RODBC <- function(con, table) {
  tmp <- sqlTables(con)$TABLE_NAME
  table %in% tmp
}

db_has_table.src_teradata <- db_has_table.RODBC

sql_escape_ident.RODBC <- function (con, x) {
  sql_quote(x, "\"")
}


#' @export
tbl.src_teradata <- function(src, from, ...) {
  tbl_sql("teradata", src = src, from = from, ...)
}

tbl.RODBC <- tbl.src_teradata

db_query_fields.RODBC <- function(con, sql,...) {
  RODBC::sqlColumns(con, sql ,...)$COLUMN_NAME
}

sql_select.RODBC <- dplyr:::sql_select.DBIConnection

query.RODBC <- function(con, sql, vars) {
  RODBC::sqlQuery(con, sql)
}

#' @import assertthat
copy_to.src_teradata <- function(dest, df, name = deparse(substitute(df)), database = attr(dest,"database"), ...) {
  # dest is expected to have a $con which should be the output of
  # src_teradata ZJ: worry about the dest part later as I need to totally
  # rip up the teradataR to do that
  assert_that(is.data.frame(df), is.string(name))

  x <- df
  # the below code is adapted from tdSave of the teradataR package tdSave(df, name)
  if (inherits(x, "td.data.frame") | inherits(x, "td.table")) {
    return(x)
  } else if (inherits(x, "data.frame")) {
    tablename <- name
    if (nchar(tablename) > 0)
      tbl <- tablename
    else
      tbl <- deparse(substitute(x))
    if (class(dest$con) == "RODBC") {
      # drop the table first if it already exists
      if(db_has_table(dest$con,tbl)) {
        if(nchar(database))
          sqlQuery(dest$con, sprintf("drop table %s.%s",database,tbl))
        else
          sqlQuery(dest$con, sprintf("drop table %s",tbl))
      }
      
      # zJ: it would be disaster if the nrows is large and the first column has only a few values
      # aim to have each column on less than 10k
      # manually create a id
      if (any(table(x[[1]]) > 10000)) {
        x <- cbind(rep(1:(nrow(x)/10000), length.out = nrow(x)), x)
      }
      
      if(nchar(database))
        sqlSave(dest$con, x, tablename = paste0(database,".", tbl))
      else
        sqlSave(dest$con, x, tablename = tbl)

      return(td.table(dest$con,table = tbl, database ))
    }
  }
}
getPage2Plots = function(updateProgress = NULL,cancer, gene, sampleSelection) {
  
  if (gene == "")
  {
    return()
  }
  if (is.null(gene))
  {
    return()
  }
  
	if (sampleSelection == 1) {
		#priorDetails = tcgaResults[[cancer]]$prioritize.details
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = tcga.cna[[cancer]][[1]]
		acgh.group2 = tcga.mn.cna[[cancer]][[1]]
		achilles.ut = tcgaResultsAT[[cancer]][2]
		achilles.lt = tcgaResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#56B4E9")
		lab.group1="Tumors" 
		lab.group2="Normals"
		pvalue=TRUE
	} else if (sampleSelection == 2) {
	  #priorDetails = ccleResults[[cancer]]$prioritize.details
		priorDetails = ccleResultsPrioDetails[[cancer]]
		exprs.group1 = ccle.exprs.combat[[cancer]][[1]]
		exprs.group2 = tcga.mn.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth[[cancer]]
		#meth.group2 = tcga.mn.meth[[cancer]]
		acgh.group1 = ccle.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.mn.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#009E73", "#56B4E9")
		lab.group1="Cell lines" 
		lab.group2="Normals"
		pvalue=TRUE
	} else {
		priorDetails = tcgaResultsPrioDetails[[cancer]]
		exprs.group1 = tcga.exprs.combat[[cancer]][[1]]
		exprs.group2 = ccle.exprs.combat[[cancer]][[1]]
		#meth.group1 = tcga.meth.combat[[cancer]]
		#meth.group2 = tcga.mn.meth.combat[[cancer]]
		acgh.group1 = tcga.cna.combat[[cancer]][[1]]
		acgh.group2 = ccle.cna.combat[[cancer]][[1]]
		achilles.ut = ccleResultsAT[[cancer]][2]
		achilles.lt = ccleResultsAT[[cancer]][1]
		color.palette=c("#E69F00", "#009E73")
		lab.group1="Tumors" 
		lab.group2="Cell lines"
		pvalue=FALSE
	}
	#meth.anno = infinium450.probe.ann
  if (is.element(gene,rownames(achilles)))
  {
    achls = achilles[gene,]    
  }else{
    achls = NULL
  }
	#achls = achilles
	
	plots = plotGene(gene, priorDetails, samples=NULL, 
		 	 exprs.group1, exprs.group2, 
		 	 #meth.group1, meth.group2, meth.anno, 
		 	 acgh.group1, acgh.group2, 
		 	 achls, achilles.ut, achilles.lt, 
		 	 lab.group1=lab.group1, lab.group2=lab.group2, 
		 	 color.palette=color.palette,
		 	 size=4, width=0.2, pvalue=pvalue)
# 	if (sampleSelection != 1) {
# 		plots[["methylation"]] = NULL
# 	}
	if (sampleSelection == 3) {
		plots[["achilles"]] = NULL
	}
	
	plots
}
.onAttach <- function(...) {
  if (!isTRUE(getOption("syberia.silent"))) {
    packageStartupMessage(paste0("Loading ", director:::colourise('Syberia', 'red'), "...\n"))
  }
  browser()
  # TODO: (RK) Find syberia project off getwd() and call syberia_project().
}

.onAttach <- function(...) {
  if (!isTRUE(getOption("syberia.silent"))) {
    packageStartupMessage(paste0("Loading ", director:::colourise('Syberia', 'red'), "...\n"))
  }

  # TODO: (RK) Find syberia project off getwd() and call syberia_project().
}


#' Cast data.frame to sparse matrix
#' 
#' Create a sparse matrix from matching vectors of row indices, column indices and values
#' 
#' @param rows a vector of row indices: [i,]
#' @param columns a vector of column indices: [,j]
#' @param values a vector of the values for each (non-zero) cell: [i,j] = value
#' @return a sparse matrix of the dgTMatrix class (\code{\link{Matrix}} package) 
#' @export
cast.sparse.matrix <- function(rows, columns, values=NULL) {
  if(is.null(values)) values = rep(1, length(rows))
  d = data.frame(rows=rows, columns=columns, values=values)
  if(nrow(d) > nrow(unique(d[,c('rows','columns')]))){
    message('(Duplicate row-column matches occured. Values of duplicates are added up)')
    d = aggregate(values ~ rows + columns, d, FUN='sum')
  }
  unit_index = unique(d$rows)
  char_index = unique(d$columns)
  sm = spMatrix(nrow=length(unit_index), ncol=length(char_index),
                match(d$rows, unit_index), match(d$columns, char_index), d$values)
  rownames(sm) = unit_index
  colnames(sm) = char_index
  sm
}

#' Create a document term matrix from a list of tokens
#' 
#' Create a \code{\link{DocumentTermMatrix}} from a list of document ids, terms, and frequencies. 
#' 
#' @param documents a vector of document names/ids
#' @param terms a vector of words of the same length as documents
#' @param freqs a vector of the frequency a a term in a document
#' @return a document-term matrix  \code{\link{DocumentTermMatrix}}
#' @export
dtm.create <- function(documents, terms, freqs=rep(1, length(documents))) {
  # remove NA terms
  d = data.frame(ids=documents, terms=terms, freqs=freqs)
  if (sum(is.na(d$terms)) > 0) {
    warning("Removing ", sum(is.na(d$terms)), "rows with missing term names")
    d = d[!is.na(d$terms), ]
  }
  sparsemat = cast.sparse.matrix(rows=d$ids, columns=d$terms, values=d$freqs)
  as.DocumentTermMatrix(sparsemat, weighting=weightTf)
}

#' Compute some useful corpus statistics for a dtm
#' 
#' Compute a number of useful statistics for filtering words: term frequency, idf, etc.
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
term.statistics <- function(dtm) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]    # get rid of empty rows/columns
  vocabulary = colnames(dtm)
  data.frame(term = vocabulary,
             characters = nchar(vocabulary),
             number = grepl("[0-9]", vocabulary),
             nonalpha = grepl("\\W", vocabulary),
             termfreq = col_sums(dtm),
             docfreq = col_sums(dtm > 0),
             reldocfreq = col_sums(dtm > 0) / nDocs(dtm),
             tfidf = tapply(dtm$v/row_sums(dtm)[dtm$i], dtm$j, mean) * log2(nDocs(dtm)/col_sums(dtm > 0)))
}

#' Compute the chi^2 statistic for a 2x2 crosstab containing the values
#' [[a, b], [c, d]]
chi2 <- function(a,b,c,d) {
  ooe <- function(o, e) {(o-e)*(o-e) / e}
  tot = 0.0 + a+b+c+d
  a = as.numeric(a)
  b = as.numeric(b)
  c = as.numeric(c)
  d = as.numeric(d)
  (ooe(a, (a+c)*(a+b)/tot)
   +  ooe(b, (b+d)*(a+b)/tot)
   +  ooe(c, (a+c)*(c+d)/tot)
   +  ooe(d, (d+b)*(c+d)/tot))
}

#' Compare two corpora
#' 
#' Compare the term use in corpus dtm with a refernece corpus dtm.ref, returning relative frequencies
#' and overrepresentation using various measures
#' 
#' @param dtm.x the main document-term matrix
#' @param dtm.y the 'reference' document-term matrix
#' @param smooth the smoothing parameter for computing overrepresentation
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
corpora.compare <- function(dtm.x, dtm.y, smooth=.001) {
  freqs = term.statistics(dtm.x)[, c("term", "termfreq")]
  freqs.rel = term.statistics(dtm.y)[, c("term", "termfreq")]
  f = merge(freqs, freqs.rel, all=T, by="term")    
  f[is.na(f)] = 0
  f$relfreq.x = f$termfreq.x / sum(freqs$termfreq)
  f$relfreq.y = f$termfreq.y / sum(freqs.rel$termfreq)
  f$over = (f$relfreq.x + smooth) / (f$relfreq.y + smooth)
  f$chi = chi2(f$termfreq.x, f$termfreq.y, sum(f$termfreq.x) - f$termfreq.x, sum(f$termfreq.y) - f$termfreq.y)
  f
}

#' Plot a word cloud from a dtm
#' 
#' Compute the term frequencies for the dtm and plot a word cloud with the top n topics
#' You can either supply a document-term matrix or provide terms and freqs directly
#' (in which case this is an alias for wordcloud::wordcloud with sensible defaults)
#' 
#' @param dtm the document-term matrix
#' @param nterms the amount of words to plot (default 100)
#' @param freq.fun if given, will be applied to the frequenies (e.g. sqrt)
#' @param terms the terms to plot, ignored if dtm is given
#' @param freqs the frequencies to plot, ignored if dtm is given
#' @param scale the scale to plot (see wordcloud::wordcloud)
#' @param min.freq the minimum frquency to include (see wordcloud::wordcloud)
#' @param rot.per the percentage of vertical words (see wordcloud::wordcloud)
#' @param pal the colour model, see RColorBrewer
#' @export
dtm.wordcloud <- function(dtm=NULL, nterms=100, freq.fun=NULL, terms=NULL, freqs=NULL, scale=c(6, .5), min.freq=1, rot.per=.15, pal=brewer.pal(6,"YlGnBu")) {
  if (!is.null(dtm)) {
    t = term.statistics(dtm)
    t = t[order(t$termfreq, decreasing=T), ]
    terms = t$term
    freqs = t$termfreq
  }
  if (!is.null(nterms)) {
    terms = terms[1:nterms] 
    freqs = freqs[1:nterms]
  }
  if (!is.null(freq.fun)) freqs = freq.fun(freqs)
   
  if (is.null(terms) | is.null(freqs)) stop("Please provide dtm or terms and freqs")
  wordcloud(terms, freqs, 
          scale=scale, min.freq=min.freq, max.words=Inf, random.order=FALSE, 
          rot.per=rot.per, colors=pal)
}REBOL [
    Title:   "Builds a set of Red & Red/System Tests to run on an ARM host"
	File: 	 %build-arm-tests.r
	Author:  "Peter W A Wood"
	Version: 0.2.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; This script must be run from the Red/red/tests dir

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

;; use win-call if running Rebol 2.7.8 under Windows
if all [
    system/version/4 = 3
    system/version/3 = 8              
][
		do %../quick-test/call.r					               
		set 'call :win-call
]

;; process arguments (if any)
target: none
if system/script/args  [
    target: second parse system/script/args " "
	if not any [
	    target = "Linux"
	    target = "Android"
	    target = "RPi"
	    target = "Darwin"
	][
	    target: none
	]
]

;; if no target supplied, ask the user
unless target [
    target: ask {
        Choose ARM target:
        1) Linux
        2) Android
        3) Linux armhf
        => }
    target: pick ["Linux-ARM" "Android" "RPi"] to-integer target
]

;; make the Arm dir if needed
arm-dir: clean-path %../quick-test/runnable/arm-tests/red/
make-dir/deep arm-dir

;; empty the Arm dir
foreach file read arm-dir [delete join arm-dir file]

;; build the test files
do %source/units/run-all-init.r

;; compile the tests into to runnable/arm-tests/red
output: copy ""
foreach file [
    "run-all-comp1.red"
    "run-all-comp2.red"
    "run-all-interp.red"
][
    test-file: join %source/units/auto-tests/ file
    exe: replace file ".red" ""
    exe: to-local-file join arm-dir exe
    cmd: join "" [  to-local-file system/options/boot " -sc "
        to-local-file clean-path %../red.r
        " -t " target " -o " exe " "
    	to-local-file test-file	
    ]
    clear output
    call/output cmd output
    print output
]

;; copy the bash script and mark it as executable
runner: arm-dir/run-all.sh
write/binary runner trim/with read/binary %run-all.sh "^M"
if system/version/4 <> 3 [
	set-modes runner [
	  owner-execute: true
	  group-execute: true
	  world-execute: true
	]
]

;; tidy up
system/options/quiet: store-quiet-mode

print ["Red/System ARM tests built in" arm-dir]  
REBOL [
	Title:   "Builds and Runs All Red and Red/System Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.3.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; function to find and run-tests
run-all-script: func [
	dir [file!]
	file [file!]
][
	qt/tests-dir: system/script/path/:dir
  	foreach line read/lines dir/:file [
  		if any [
			find line "===start-group"
  	  		find line "--run-"
  		][
  			do line
  		]
  	]
]

batch-mode: false
each-mode: false
binary?: false
args: any [system/script/args system/options/args]
if args  [
	;; should we run non-interactively?
	batch-mode: find system/script/args "--batch"
	
	;; should we run each file individually?
	each-mode: find system/script/args "--each"

	;; should we use the binary compiler?
	args: parse system/script/args " "
	if find system/script/args "--binary" [
		binary?: true
		bin-compiler: select args "--binary"
		if any [
			bin-compiler = "--batch"
			bin-complier = "--each"
		][
			bin-compiler: none								;; use default
		]
		if bin-compiler [						
			if not attempt [exists? to file! bin-compiler] [
				either batch-mode [
					write %quick-test/quick-test.log "Invalid compiler path"
					quit/return 1
				][
					print "Invalid compiler path supplied"
					print args
					print ""
					halt
				]
			]
		]
	
	]
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true
store-current-dir: what-dir

do %quick-test/quick-test.r
qt/tests-dir: clean-path %/tests/

if binary? [
	qt/binary?: binary?
	if bin-compiler [qt/bin-compiler: bin-compiler]
]

qt/tests-dir: clean-path %system/tests/
do %system/tests/source/units/make-red-system-auto-tests.r

qt/tests-dir: clean-path %tests/
do %tests/source/units/run-all-init.r

***start-run-quiet*** "Complete Red Test Suite"

do %tests/source/units/run-all-extra-tests.r

either each-mode [
    do %tests/source/units/auto-tests/run-each-comp.r
    do %tests/source/units/auto-tests/run-each-interp.r
][
    --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
    --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
    --run-test-file-quiet %source/units/auto-tests/run-all-interp.red    
]
qt/script-header: "Red/System []"
qt/tests-dir: clean-path %system/tests/ 
run-all-script %system/tests/ %run-all.r

do %tests/source/units/run-all-final.r# Function 'NormMax'
# Killian Martin--Horgassan
# 19-02-2015

# Generates the list of maxima [M_1, ..., M_n] of the list of
# i.i.d random variables [X_1,...,X_n]. Plots the M_i against 
# the i.

# Arguments :
# - N     : number of r.v. X_i
# - DIST  : a vector of N pseudo-random numbers from a certain 
#			distribution.
# RETURNS the list of maxima

NormMax <- function(N = 10000, DIST = rnorm(10000,0,1)) {
 	ListX   <- DIST
 	ListMax <- rep(0,N)
 	
 	# Computes the list of the M_i
 	for (i in 1:length(ListMax)) {
 		ListMax[i] <- max(ListX[1:i])
 	}
 	
 	# Plots the 1-D scatter plot of the M_i
 	title_1 <- "1-D scatter plot of the maxima"
 	xlabel_1 <- expression(M[i])
 	stripchart(ListMax, xlab = xlabel_1, main = title_1)
 	
 	# Opens a new graphic window
 	quartz()
 	
 	# Plots the M_i against the i
 	title_2 <- "Maxima as a function of the time steps"
 	xlabel_2 <- "Time step"
 	ylabel_2 <- "Maximum"
 	plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =
 			title_2)
 	
 	# Opens a new graphic windows
 	quartz()
 	
 	# Plot the 1-D scatter plot of the M_i and the M_i against the
 	# i together in a grid.
 	par(mfrow = c(1,2))
 	
 	stripchart(ListMax, xlab = xlabel_1, main = title_1)
    plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =
 			title_2, pch = 4)
 	points(1:N,sqrt(log(1:N)),col="cyan", pch = 3)
 	legend(x="bottomright",y=NULL,c("Maxima",
 		expression("sqrt(log(n))")), col = c("black","cyan"),
 		bty="o", pch = c(4,3))
 		
 	# Exports the plots to a JPEG file
 	pdf(file = "graphIntroTask.pdf", width = 10, height = 8)
	par(mfrow = c(1,2))
 	stripchart(ListMax, xlab = xlabel_1, main = title_1)
    plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =
 			title_2, pch = 4)
 	points(1:N,sqrt(log(1:N)),col="cyan", pch = 3)
 	legend(x="bottomright",y=NULL,c("Maxima",
 		expression("sqrt(log(n))")), col = c("black","cyan"),
 		bty="o", pch = c(4,3))
 	dev.off()
 	
 	return(ListMax)
 }REBOL [
  Title:   "Simple testing framework for Red and Red/System programs"
	Author:  "Peter W A Wood"
	File: 	 %quick-test.r
	Version: 0.12.0
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

comment {
	This script makes some assumptions about the directory structure in which 
	files are stored. They are:
    	this script is stored in Red/quick-test/
    	the Red & Red/System compiler is stored in Red/
    	the default dir for tests is Red/system/tests/
    	
    	The default test dirs can be overriden by setting qt/tests-dir before
    	tests are processed
    	The default script header for code supplied as string is Red [], this 
    	can be overriden by setting qt/script-header
    	The default location of the compiler binary is Red/build/bin, this can
    	be overriden by setting qt/bin-compiler
}

qt: make object! [
  
  ;;;;;;;;;;; Setup ;;;;;;;;;;;;;;
  ;; set the base-dir to ....Red/
  base-dir: system/script/path
  base-dir: copy/part base-dir find base-dir "quick-test"
  ;; set the red/system runnable dir
  runnable-dir: dirize base-dir/quick-test/runnable
  ;; set the default base dir for tests
  tests-dir: dirize base-dir/system/tests
  
  ;; set the version number
  version: system/script/header/version
  
  ;; switch for binary compiler usage
  binary?: false

  ;; check if call-show? is enabled for call
  either (not value? 'call-show?) [call-show?: 'wait] [call-show?: 'show]
  call*: to path! 'call
  append call* :call-show?
  append call* 'output
  
  ;; default binary compiler path
  bin-compiler: base-dir/build/bin/red
  
  ;; default script header to be inserted into code supplied in string form
  script-header: "Red []"
  
  ;; set temporary files names
  ;;  use Red/quick-test/runnable for temp files
  comp-echo: runnable-dir/comp-echo.txt
  comp-r: runnable-dir/comp.r
  test-src-file: runnable-dir/qt-test-comp.red
  
  ;; set log file 
  log-file: join system/script/path "quick-test.log"

  ;; make runnable directory if needed
  make-dir runnable-dir
  
  ;; windows ?
  windows-os?: system/version/4 = 3
  
  ;; use Cheyenne call with REBOL v2.7.8 on Windows (re: 'call bug on Windows 7)
  if all [
    windows-os?
    system/version/3 = 8              
  ][
		do %call.r					               
		set 'call :win-call
	]
	
	;; script header parse rules - assumes parsing without /all
	red?: false
	red-header: ["red" any " " "[" to end (red?: true)]
	red-system-header: ["red/system" any " " "[" to end (red?: false)]
	red?-rule: [(red?: false) any [red-system-header | red-header | skip]]
	script-header-rule: [
		(no-script-header?: true) 
		any [ 
				[["red/system" | "red"] any " " "[" (no-script-header?: false)]
			|
				skip
		]
	]

	;;;;;;;;; End Setup ;;;;;;;;;;;;;;
  
  comp-output: copy ""                 ;; output captured from compile
  output: copy ""                      ;; output captured from pgm exec
  exe: none                            ;; filepath to executable
  source-file?: true                   ;; true = running  test file
                                       ;; false = runnning test script
				  

  summary-template: ".. - .................................................. / "
  
  data: make object! [
    title: copy ""
    no-tests: 0
    no-asserts: 0
    passes: 0
    failures: 0
    reset: does [
      title: copy ""
      no-tests: 0
      no-asserts: 0
      passes: 0
      failures: 0
    ]
  ]
  
  file: make data []
  test-run: make data []
  _add-file-to-run-totals: does [
    test-run/no-tests: test-run/no-tests + file/no-tests
    test-run/no-asserts: test-run/no-asserts + file/no-asserts
    test-run/passes: test-run/passes + file/passes
    test-run/failures: test-run/failures + file/failures
  ]
  _signify-failure: does [
    ;; called when a compiler or runtime error occurs
    file/failures: file/failures + 1           
    file/no-tests: file/no-tests + 1
    file/no-asserts: file/no-asserts + 1
    test-run/failures: test-run/failures + 1           
    test-run/no-tests: test-run/no-tests + 1
    test-run/no-asserts: test-run/no-asserts + 1
  ]
  
  ;; group data
  group-name: copy ""
  group?: false
  group-name-not-printed: true
  _init-group: does [
    group?: false
    group-name-not-printed: true
    group-name: copy ""
  ]
  
  ;; test data
  test-name: copy ""
  _init-test: does [
    test-name: copy ""
  ]
  
  ;; print diversion function
  _save-print: :print
  print-output: copy ""
  _quiet-print: func [val] [
    append print-output join "" [reduce val "^/"]
  ]
        
  	compile: func [
  		src [file!]
  		/bin
  		/lib
  	  		target [string!]	
  	  	/local
  	  		comp                          	;; compilation script
  	  		cmd                           	;; compilation cmd
  	  		exe								;; executable name
  ][
    clear comp-output
    
    ;; workout executable name
    either find/last/tail src "/" [
      exe: copy find/last/tail src "/"
    ][
      exe: copy src
    ]
    exe: copy/part exe find exe "."
    either lib [
      switch/default target [
        "Windows"	[exe: join exe [".dll"]]
        "Darwin"   	[exe: join exe [".dylib"]]
      ][
      	  exe: join exe [".so"]
      ]
      exe
    ][     
      if windows-os? [
        exe: join exe [".exe"]
      ]
    ]
    
    ;; find the path to the src
    if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    
    ;; red/system or red
    red?: false
    parse read src red?-rule
 
    ;; compose and write compilation script
    either binary? [
    	if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    	either lib [
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe
    					  " -dlib -t " target " "
    					  to-local-file src
    		]
    	][
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe " "
    					  to-local-file src	
    		]  		
    	]
    	comp-output: make string! 1024
    	do call* cmd comp-output
    ][
    	comp: mold compose/deep [
    	  REBOL []
    	  halt: :quit
    	  echo (comp-echo)
    	  do/args (reduce base-dir/red.r) (join " -o " [
    	  	  	  reduce runnable-dir/:exe " ###lib###***src***" 
    	  ])
    	]
    	either lib [
    		replace comp "###lib###" join "-dlib -t " [target " "]
    	][
    		replace comp "###lib###" ""
    	]
    
    	replace comp "***src***"  clean-path src
    	write comp-r comp

    	;; compose command line and call it
    	cmd: join to-local-file system/options/boot [" -sc " comp-r]
    	do call* cmd make string! 1024	;; redirect output to anonymous
    											;; buffer
    ]
    
    ;; collect compiler output & tidy up
    if exists? comp-echo [
    	comp-output: read comp-echo
    	delete comp-echo
    ]
    if exists? comp-r [delete comp-r]
    either compile-ok? [
      exe
    ][
      none
    ]    
  ]
  
  compile-and-run: func [src /error /pgm] [
    source-file?: true
    either exe: compile src [
      either error [
        run/error  exe
      ][
      	  either pgm [
      	  	  run/pgm exe
      	  ][
      	  	  run exe
      	  ]
      ]
    ][
      compile-error src
      output: "Compilation failed"
    ]
  ]
    
  compile-and-run-from-string: func [src /error] [
    source-file?: false
    either exe: compile-from-string src [
      either error [
        run/error  exe
      ][
        run exe
      ]
    ][
      
      compile-error "Supplied source"
      output: "Compilation failed"
    ]
  ]
  
  compile-dll: func [
    lib-src [file!]
    target	[string!]
    /local
    	dll
  ][
    ;; compile the lib into the runnable dir
    if not dll: compile/lib lib-src target [
      compile-error lib-src
      output: "Lib compilation failed"  
    ]
    dll
  ]
  
  compile-from-string: func [src][
    ;-- add a default header if not provided
    parse src script-header-rule
    if no-script-header? [
    	insert src join script-header "^/"
    ]
    write test-src-file src
    compile test-src-file                  ;; returns path to executable or none
  ]
  
  compile-error: func [
    src [file! string!]
  ][
    print join "^/" [src " - compiler error^/"]
    print comp-output
    print newline
    clear output                           ;; clear the output from previous test
    _signify-failure
  ]
  
  compile-ok?: func [] [
    either find comp-output "output file size :" [true] [false]
  ] 
  
  compile-run-print: func [src [file!] /error][
  	  either error [
  	  	  compile-and-run/error src
  	  ][
  	  	  compile-and-run src
    ]
    if output <> "Compilation failed" [print output]
  ]
  
  compiled?: func [
    src [string!]
  ][
    exe: compile-from-string src
    clean-compile-from-string
    qt/compile-ok?
  ]
  
  run: func [
    prog [file!]
    ;;/args                         ;; not yet needed
      ;;parms [string!]             ;; not yet needed
    /error                          ;; run time error expected
    /pgm							;; a program not a test
    /local
    exec [string!]                  ;; command to be executed
  ][
    exec: to-local-file runnable-dir/:prog
    ;;exec: join "" compose/deep [(exec either args [join " " parms] [""])]
    clear output
    do call* exec output
    if all [red? windows-os?] [output: qt/utf-16le-to-utf-8 output]
    if all [
      source-file?
      not pgm
      any [
      	  all [
      	   none <> find output "Runtime Error"
      	   not error
      	  ]
      	  none = find output "Passed"
      ]
    ][	
    print "signify failure"
      _signify-failure
    ]
  ]
  
  run-unit-test: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd make string! 1024
  ]
  
  run-unit-test-quiet: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    test-name: find/last/tail src "/"
    test-name: copy/part test-name find test-name "."
    prin [ "running " test-name #"^(0D)"]
    clear output
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd output
    if find output "Error:" [_signify-failure]
    add-to-run-totals
    write/append log-file output
    file/title: test-name
    replace file/title "-test" ""
    _print-summary file
  ]
  
  run-script: func [
    src [file!]
    /local
     filename                     ;; filename of script 
     script                       ;; %runnable/filename
  ][
    if not filename: copy find/last/tail src "/" [filename: copy src]
    script: runnable-dir/:filename
    write to file! script read join tests-dir [src]
    if error? try [do script] [_signify-failure]
  ]
  
  run-script-quiet: func [
  	src [file!]
  ][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-script src
    add-to-run-totals
    print: :_save-print
    write/append log-file print-output
    _print-summary file
  ]
  
  run-test-file: func [
  	src [file!]
  ][
    file/reset
    unless file/title: find/last/tail to string! src "/" [file/title: src]
    replace file/title "-test.reds" ""
    replace file/title "-test.red" ""
    compile-run-print src
    add-to-run-totals
  ]
  
  run-test-file-quiet: func [
  	src [file!]
  	][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-test-file src
    print: :_save-print
    write/append log-file print-output
    _print-summary file
    output: copy ""
  ]
  
  add-to-run-totals: func [
    /local
      tests
      
      asserts
      passes
      failures
      rule
      digit
      number
  ][
    digit: charset [#"0" - #"9"]
    number: [some digit]
    ws: charset [#"^-" #"^/" #" "]
    whitespace: [some ws]
    rule: [
      thru "Number of Tests Performed:" whitespace copy tests number
      thru "Number of Assertions Performed:" whitespace copy asserts number
      thru "Number of Assertions Passed:" whitespace copy passed number
      thru "Number of Assertions Failed:" whitespace copy failures number
      to end
    ]
    if parse/all output rule [
      file/no-tests: file/no-tests + to integer! tests
      file/no-asserts: file/no-asserts + to integer! asserts
      file/passes: file/passes + to integer! passed
      file/failures: file/failures + to integer! failures
      _add-file-to-run-totals
    ]
  ]
  
  _start: func [
    data [object!]
    leader [string!]
    title [string!]
  ][
    print [leader title]
    data/title: title
    data/no-tests: 0
    data/no-asserts: 0
    data/passes: 0
    data/failures: 0
    _init-group
  ]

  start-test-run: func [
    title [string!]
  ][
    _start test-run "***Starting***" title
    prin newline
  ]
  
  start-test-run-quiet: func [
    title [string!]
      ][
    _start test-run "" title
    prin newline
    write log-file rejoin ["***Starting*** " title newline]
  ]
  
  start-file: func [
    title [string!]
  ][
    _start file "~~~started test~~~" title
  ]
  
  start-group: func[
    title [string!]
  ][
   group-name: title
   group?: true
  ]
  
  start-test: func[
    title [string!]
  ][
    _init-test
    test-name: title
    file/no-tests: file/no-tests + 1
  ]
    
  assert: func [
    assertion [logic!]
  ][
    file/no-asserts: file/no-asserts + 1
    either assertion [
      file/passes: file/passes + 1
    ][
      file/failures: file/failures + 1
      if group? [
        if group-name-not-printed [
          print ""
          print ["===group===" group-name]
        ]
      ]
      print ["---test---" test-name "FAILED**************"]
    ]
  ]
  
  assert-msg?: func [msg][
    assert found? find qt/comp-output msg
  ]
  
  assert-printed?: func [msg] [
    assert found? find qt/output msg
  ]
  
  clean-compile-from-string: does [
    if exists? test-src-file [delete test-src-file]
    if all [exe exists? exe][delete exe]
]
  
  end-group: does [
    _init-group
  ]
  
  _end: func [
    data [object!]
    leader [string!]
  ][
    print [leader data/title]
    print ["No of tests  " data/no-tests]
    print ["No of asserts" data/no-asserts]
    print ["Passed       " data/passes]
    print ["Failed       " data/failures]
    if data/failures > 0 [print "***TEST FAILURES***"]
    print ""
  ]
  
  end-file: func [] [
    _end file "~~~finished test~~~" 
    _add-file-to-run-totals
  ]
  
  end-test-run: func [] [
      print ""
    _end test-run "***Finished***"
  ]
  
  end-test-run-quiet: func [] [
    print: :_quiet-print
    print-output: copy ""
    end-test-run
    print: :_save-print
    write/append log-file print-output
    prin newline
    _print-summary test-run
  ]
  
  _print-summary: func [
    data [object!]
    /local
      print-line
  ][
    print-line: copy summary-template
    print-line: skip print-line 5
    remove/part print-line length? data/title
    insert print-line data/title
    print-line: skip tail print-line negate (3 + length? mold data/passes)
    remove/part print-line length? mold data/passes
    insert print-line data/passes
    append print-line data/no-asserts
    print-line: head print-line
    either data/no-asserts = data/passes [
      replace print-line ".." "ok"
    ][
      replace/all print-line "." "*"
      append print-line " **"
    ]
    print print-line
  ]
  
  make-if-needed?: func [
    {This function is used by the Red run-all scripts to build the auto files
     when necessary.} 
    auto-test-file [file!]
    make-file [file!]
    /lib-test
    /local
      stored-length   ; the length of the make... .r file used to build auto tests
      stored-file-length
      digit
      number
      rule
  ][
    auto-test-file: join tests-dir auto-test-file
    make-file: join tests-dir make-file
    
    stored-file-length: does [
      parse/all read auto-test-file rule
      stored-length
    ]
    digit: charset [#"0" - #"9"]
    number: [some digit]
    rule: [
      thru ";make-length:" 
      copy stored-length number (stored-length: to integer! stored-length)
      to end
    ]
    
    if not exists? make-file [return]
   
    if any [
      not exists? auto-test-file
      stored-file-length <> length? read make-file
      0:00 < difference modified? make-file modified? auto-test-file
    ][
      print ["Making" auto-test-file " - it will take a while"]
      do make-file
    ]
  ]
  
  setup-temp-files: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    comp-echo: join runnable-dir ["comp-echo" f ".txt"]
  	comp-r: join runnable-dir ["comp" f ".r"]
  	test-src-file: join runnable-dir ["qt-test-comp" f ".red"]
  ]
  
  delete-temp-files: does [
  	  if exists? comp-echo [delete comp-echo]
  	  if exists? comp-r [delete comp-r]
  	  if exists? test-src-file [delete test-src-file]  
  ]
  
  seperate-log-file: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    log-file: join base-dir ["quick-test/quick-test" f ".log"]
  ]
  
  utf-16le-to-utf-8: func [
    {Translates a utf-16LE encoded string to an utf-8 encoded one
     the algorithm is copied from lexer.r                         }
    in-str [string!]
    /local
      out-str
      code
  ][
   out-str: copy ""
   foreach [low high] to binary! in-str [
     code: high * 256 + low
     case [
       code <= 127  [
         append out-str to char! code					            ;-- c <= 7Fh
       ]
       code <= 2047 [							                        ;-- c <= 07FFh
         append out-str join "" [ 
           to char! ((shift code 6) and #"^(1F)" or #"^(C0)")
					 to char! ((code and #"^(3F)") or #"^(80)")
				 ]
			 ]
			 code <= 65535 [					                         		;-- c <= FFFFh
			   append out-str join "" [
			     to char! ((shift code 12) and #"^(0F)" or #"^(E0)")
			     to char! ((shift code 6) and #"^(3F)" or #"^(80)")
			     to char! (code and #"^(3F)" or #"^(80)")
			   ]
			 ]
			 code <= 1114111 [						                        ;-- c <= 10FFFFh
			   append out-str join "" [
			     to char! ((shift code 18) & ^"(07)" or #"^(F0)")
					 to char! ((shift code 12) and #"^(3F)" or #"^(80)")
					 to char! ((shift code 6)  and #"^(3F)" or #"^(80)")
					 to char! (code and #"^(3F)" or #"^(80)")
				 ]
			 ]                         ;-- Codepoints above U+10FFFF are ignored"
		 ]
	 ]
   out-str 
  ]
  
  ;; create the test "dialect"
  
  set '***start-run***              :start-test-run
  set '***start-run-quiet***        :start-test-run-quiet
  set '~~~start-file~~~             :start-file
  set '===start-group===            :start-group
  set '--test--                     :start-test
  set '--compile                    :compile
  set '--compile-red                :compile
  set '--compile-dll          		:compile-dll
  set '--compile-this               :compile-from-string
  set '--compile-this-red           :compile-from-string
  set '--compile-and-run            :compile-and-run
  set '--compile-and-run-red        :compile-and-run 
  set '--compile-and-run-this       :compile-and-run-from-string
  set '--compile-and-run-this-red   :compile-and-run-from-string
  set '--compile-run-print          :compile-run-print
  set '--compile-run-print-red      :compile-run-print
  set '--compiled?                  :compiled?
  set '--run                        :run
  set '--add-to-run-totals          :add-to-run-totals
  set '--run-unit-test              :run-unit-test
  set '--run-unit-test-quiet        :run-unit-test-quiet
  set '--run-script                 :run-script
  set '--run-script-quiet           :run-script-quiet
  set '--run-test-file              :run-test-file
  set '--run-test-file-red          :run-test-file
  set '--run-test-file-quiet        :run-test-file-quiet
  set '--run-test-file-quiet-red    :run-test-file-quiet
  set '--assert                     :assert
  set '--assert-msg?                :assert-msg?
  set '--assert-printed?            :assert-printed?
  set '--assert-red-printed?        :assert-printed?
  set '--clean                      :clean-compile-from-string
  set '===end-group===              :end-group
  set '~~~end-file~~~               :end-file
  set '***end-run***                :end-test-run
  set '***end-run-quiet***          :end-test-run-quiet
  set '--setup-temp-files			:setup-temp-files
  set '--delete-temp-files			:delete-temp-files
  set '--seperate-log-file			:seperate-log-file	
]
REBOL [
  Title:   "Simple testing framework for Red and Red/System programs"
	Author:  "Peter W A Wood"
	File: 	 %quick-test.r
	Version: 0.12.0
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

comment {
	This script makes some assumptions about the directory structure in which 
	files are stored. They are:
    	this script is stored in Red/quick-test/
    	the Red & Red/System compiler is stored in Red/
    	the default dir for tests is Red/system/tests/
    	
    	The default test dirs can be overriden by setting qt/tests-dir before
    	tests are processed
    	The default script header for code supplied as string is Red [], this 
    	can be overriden by setting qt/script-header
    	The default location of the compiler binary is Red/build/bin, this can
    	be overriden by setting qt/bin-compiler
}

qt: make object! [
  
  ;;;;;;;;;;; Setup ;;;;;;;;;;;;;;
  ;; set the base-dir to ....Red/
  base-dir: system/script/path
  base-dir: copy/part base-dir find base-dir "quick-test"
  ;; set the red/system runnable dir
  runnable-dir: dirize base-dir/quick-test/runnable
  ;; set the default base dir for tests
  tests-dir: dirize base-dir/system/tests
  
  ;; set the version number
  version: system/script/header/version
  
  ;; switch for binary compiler usage
  binary?: false

  ;; check if call-show? is enabled for call
  if (not value? 'call-show?) [call-show?: 'wait]
  call*: to path! 'call
  append call* :call-show?
  append call* 'output
  
  ;; default binary compiler path
  bin-compiler: base-dir/build/bin/red
  
  ;; default script header to be inserted into code supplied in string form
  script-header: "Red []"
  
  ;; set temporary files names
  ;;  use Red/quick-test/runnable for temp files
  comp-echo: runnable-dir/comp-echo.txt
  comp-r: runnable-dir/comp.r
  test-src-file: runnable-dir/qt-test-comp.red
  
  ;; set log file 
  log-file: join system/script/path "quick-test.log"

  ;; make runnable directory if needed
  make-dir runnable-dir
  
  ;; windows ?
  windows-os?: system/version/4 = 3
  
  ;; use Cheyenne call with REBOL v2.7.8 on Windows (re: 'call bug on Windows 7)
  if all [
    windows-os?
    system/version/3 = 8              
  ][
		do %call.r					               
		set 'call :win-call
	]
	
	;; script header parse rules - assumes parsing without /all
	red?: false
	red-header: ["red" any " " "[" to end (red?: true)]
	red-system-header: ["red/system" any " " "[" to end (red?: false)]
	red?-rule: [(red?: false) any [red-system-header | red-header | skip]]
	script-header-rule: [
		(no-script-header?: true) 
		any [ 
				[["red/system" | "red"] any " " "[" (no-script-header?: false)]
			|
				skip
		]
	]

	;;;;;;;;; End Setup ;;;;;;;;;;;;;;
  
  comp-output: copy ""                 ;; output captured from compile
  output: copy ""                      ;; output captured from pgm exec
  exe: none                            ;; filepath to executable
  source-file?: true                   ;; true = running  test file
                                       ;; false = runnning test script
				  

  summary-template: ".. - .................................................. / "
  
  data: make object! [
    title: copy ""
    no-tests: 0
    no-asserts: 0
    passes: 0
    failures: 0
    reset: does [
      title: copy ""
      no-tests: 0
      no-asserts: 0
      passes: 0
      failures: 0
    ]
  ]
  
  file: make data []
  test-run: make data []
  _add-file-to-run-totals: does [
    test-run/no-tests: test-run/no-tests + file/no-tests
    test-run/no-asserts: test-run/no-asserts + file/no-asserts
    test-run/passes: test-run/passes + file/passes
    test-run/failures: test-run/failures + file/failures
  ]
  _signify-failure: does [
    ;; called when a compiler or runtime error occurs
    file/failures: file/failures + 1           
    file/no-tests: file/no-tests + 1
    file/no-asserts: file/no-asserts + 1
    test-run/failures: test-run/failures + 1           
    test-run/no-tests: test-run/no-tests + 1
    test-run/no-asserts: test-run/no-asserts + 1
  ]
  
  ;; group data
  group-name: copy ""
  group?: false
  group-name-not-printed: true
  _init-group: does [
    group?: false
    group-name-not-printed: true
    group-name: copy ""
  ]
  
  ;; test data
  test-name: copy ""
  _init-test: does [
    test-name: copy ""
  ]
  
  ;; print diversion function
  _save-print: :print
  print-output: copy ""
  _quiet-print: func [val] [
    append print-output join "" [reduce val "^/"]
  ]
        
  	compile: func [
  		src [file!]
  		/bin
  		/lib
  	  		target [string!]	
  	  	/local
  	  		comp                          	;; compilation script
  	  		cmd                           	;; compilation cmd
  	  		exe								;; executable name
  ][
    clear comp-output
    
    ;; workout executable name
    either find/last/tail src "/" [
      exe: copy find/last/tail src "/"
    ][
      exe: copy src
    ]
    exe: copy/part exe find exe "."
    either lib [
      switch/default target [
        "Windows"	[exe: join exe [".dll"]]
        "Darwin"   	[exe: join exe [".dylib"]]
      ][
      	  exe: join exe [".so"]
      ]
      exe
    ][     
      if windows-os? [
        exe: join exe [".exe"]
      ]
    ]
    
    ;; find the path to the src
    if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    
    ;; red/system or red
    red?: false
    parse read src red?-rule
 
    ;; compose and write compilation script
    either binary? [
    	if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    	either lib [
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe
    					  " -dlib -t " target " "
    					  to-local-file src
    		]
    	][
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe " "
    					  to-local-file src	
    		]  		
    	]
    	comp-output: make string! 1024
    	do call* cmd comp-output
    ][
    	comp: mold compose/deep [
    	  REBOL []
    	  halt: :quit
    	  echo (comp-echo)
    	  do/args (reduce base-dir/red.r) (join " -o " [
    	  	  	  reduce runnable-dir/:exe " ###lib###***src***" 
    	  ])
    	]
    	either lib [
    		replace comp "###lib###" join "-dlib -t " [target " "]
    	][
    		replace comp "###lib###" ""
    	]
    
    	replace comp "***src***"  clean-path src
    	write comp-r comp

    	;; compose command line and call it
    	cmd: join to-local-file system/options/boot [" -sc " comp-r]
    	do call* cmd make string! 1024	;; redirect output to anonymous
    											;; buffer
    ]
    
    ;; collect compiler output & tidy up
    if exists? comp-echo [
    	comp-output: read comp-echo
    	delete comp-echo
    ]
    if exists? comp-r [delete comp-r]
    either compile-ok? [
      exe
    ][
      none
    ]    
  ]
  
  compile-and-run: func [src /error /pgm] [
    source-file?: true
    either exe: compile src [
      either error [
        run/error  exe
      ][
      	  either pgm [
      	  	  run/pgm exe
      	  ][
      	  	  run exe
      	  ]
      ]
    ][
      compile-error src
      output: "Compilation failed"
    ]
  ]
    
  compile-and-run-from-string: func [src /error] [
    source-file?: false
    either exe: compile-from-string src [
      either error [
        run/error  exe
      ][
        run exe
      ]
    ][
      
      compile-error "Supplied source"
      output: "Compilation failed"
    ]
  ]
  
  compile-dll: func [
    lib-src [file!]
    target	[string!]
    /local
    	dll
  ][
    ;; compile the lib into the runnable dir
    if not dll: compile/lib lib-src target [
      compile-error lib-src
      output: "Lib compilation failed"  
    ]
    dll
  ]
  
  compile-from-string: func [src][
    ;-- add a default header if not provided
    parse src script-header-rule
    if no-script-header? [
    	insert src join script-header "^/"
    ]
    write test-src-file src
    compile test-src-file                  ;; returns path to executable or none
  ]
  
  compile-error: func [
    src [file! string!]
  ][
    print join "^/" [src " - compiler error^/"]
    print comp-output
    print newline
    clear output                           ;; clear the output from previous test
    _signify-failure
  ]
  
  compile-ok?: func [] [
    either find comp-output "output file size :" [true] [false]
  ] 
  
  compile-run-print: func [src [file!] /error][
  	  either error [
  	  	  compile-and-run/error src
  	  ][
  	  	  compile-and-run src
    ]
    if output <> "Compilation failed" [print output]
  ]
  
  compiled?: func [
    src [string!]
  ][
    exe: compile-from-string src
    clean-compile-from-string
    qt/compile-ok?
  ]
  
  run: func [
    prog [file!]
    ;;/args                         ;; not yet needed
      ;;parms [string!]             ;; not yet needed
    /error                          ;; run time error expected
    /pgm							;; a program not a test
    /local
    exec [string!]                  ;; command to be executed
  ][
    exec: to-local-file runnable-dir/:prog
    ;;exec: join "" compose/deep [(exec either args [join " " parms] [""])]
    clear output
    do call* exec output
    if all [red? windows-os?] [output: qt/utf-16le-to-utf-8 output]
    if all [
      source-file?
      not pgm
      any [
      	  all [
      	   none <> find output "Runtime Error"
      	   not error
      	  ]
      	  none = find output "Passed"
      ]
    ][	
    print "signify failure"
      _signify-failure
    ]
  ]
  
  run-unit-test: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd make string! 1024
  ]
  
  run-unit-test-quiet: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    test-name: find/last/tail src "/"
    test-name: copy/part test-name find test-name "."
    prin [ "running " test-name #"^(0D)"]
    clear output
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    do call* cmd output
    if find output "Error:" [_signify-failure]
    add-to-run-totals
    write/append log-file output
    file/title: test-name
    replace file/title "-test" ""
    _print-summary file
  ]
  
  run-script: func [
    src [file!]
    /local
     filename                     ;; filename of script 
     script                       ;; %runnable/filename
  ][
    if not filename: copy find/last/tail src "/" [filename: copy src]
    script: runnable-dir/:filename
    write to file! script read join tests-dir [src]
    if error? try [do script] [_signify-failure]
  ]
  
  run-script-quiet: func [
  	src [file!]
  ][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-script src
    add-to-run-totals
    print: :_save-print
    write/append log-file print-output
    _print-summary file
  ]
  
  run-test-file: func [
  	src [file!]
  ][
    file/reset
    unless file/title: find/last/tail to string! src "/" [file/title: src]
    replace file/title "-test.reds" ""
    replace file/title "-test.red" ""
    compile-run-print src
    add-to-run-totals
  ]
  
  run-test-file-quiet: func [
  	src [file!]
  	][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-test-file src
    print: :_save-print
    write/append log-file print-output
    _print-summary file
    output: copy ""
  ]
  
  add-to-run-totals: func [
    /local
      tests
      
      asserts
      passes
      failures
      rule
      digit
      number
  ][
    digit: charset [#"0" - #"9"]
    number: [some digit]
    ws: charset [#"^-" #"^/" #" "]
    whitespace: [some ws]
    rule: [
      thru "Number of Tests Performed:" whitespace copy tests number
      thru "Number of Assertions Performed:" whitespace copy asserts number
      thru "Number of Assertions Passed:" whitespace copy passed number
      thru "Number of Assertions Failed:" whitespace copy failures number
      to end
    ]
    if parse/all output rule [
      file/no-tests: file/no-tests + to integer! tests
      file/no-asserts: file/no-asserts + to integer! asserts
      file/passes: file/passes + to integer! passed
      file/failures: file/failures + to integer! failures
      _add-file-to-run-totals
    ]
  ]
  
  _start: func [
    data [object!]
    leader [string!]
    title [string!]
  ][
    print [leader title]
    data/title: title
    data/no-tests: 0
    data/no-asserts: 0
    data/passes: 0
    data/failures: 0
    _init-group
  ]

  start-test-run: func [
    title [string!]
  ][
    _start test-run "***Starting***" title
    prin newline
  ]
  
  start-test-run-quiet: func [
    title [string!]
      ][
    _start test-run "" title
    prin newline
    write log-file rejoin ["***Starting*** " title newline]
  ]
  
  start-file: func [
    title [string!]
  ][
    _start file "~~~started test~~~" title
  ]
  
  start-group: func[
    title [string!]
  ][
   group-name: title
   group?: true
  ]
  
  start-test: func[
    title [string!]
  ][
    _init-test
    test-name: title
    file/no-tests: file/no-tests + 1
  ]
    
  assert: func [
    assertion [logic!]
  ][
    file/no-asserts: file/no-asserts + 1
    either assertion [
      file/passes: file/passes + 1
    ][
      file/failures: file/failures + 1
      if group? [
        if group-name-not-printed [
          print ""
          print ["===group===" group-name]
        ]
      ]
      print ["---test---" test-name "FAILED**************"]
    ]
  ]
  
  assert-msg?: func [msg][
    assert found? find qt/comp-output msg
  ]
  
  assert-printed?: func [msg] [
    assert found? find qt/output msg
  ]
  
  clean-compile-from-string: does [
    if exists? test-src-file [delete test-src-file]
    if all [exe exists? exe][delete exe]
]
  
  end-group: does [
    _init-group
  ]
  
  _end: func [
    data [object!]
    leader [string!]
  ][
    print [leader data/title]
    print ["No of tests  " data/no-tests]
    print ["No of asserts" data/no-asserts]
    print ["Passed       " data/passes]
    print ["Failed       " data/failures]
    if data/failures > 0 [print "***TEST FAILURES***"]
    print ""
  ]
  
  end-file: func [] [
    _end file "~~~finished test~~~" 
    _add-file-to-run-totals
  ]
  
  end-test-run: func [] [
      print ""
    _end test-run "***Finished***"
  ]
  
  end-test-run-quiet: func [] [
    print: :_quiet-print
    print-output: copy ""
    end-test-run
    print: :_save-print
    write/append log-file print-output
    prin newline
    _print-summary test-run
  ]
  
  _print-summary: func [
    data [object!]
    /local
      print-line
  ][
    print-line: copy summary-template
    print-line: skip print-line 5
    remove/part print-line length? data/title
    insert print-line data/title
    print-line: skip tail print-line negate (3 + length? mold data/passes)
    remove/part print-line length? mold data/passes
    insert print-line data/passes
    append print-line data/no-asserts
    print-line: head print-line
    either data/no-asserts = data/passes [
      replace print-line ".." "ok"
    ][
      replace/all print-line "." "*"
      append print-line " **"
    ]
    print print-line
  ]
  
  make-if-needed?: func [
    {This function is used by the Red run-all scripts to build the auto files
     when necessary.} 
    auto-test-file [file!]
    make-file [file!]
    /lib-test
    /local
      stored-length   ; the length of the make... .r file used to build auto tests
      stored-file-length
      digit
      number
      rule
  ][
    auto-test-file: join tests-dir auto-test-file
    make-file: join tests-dir make-file
    
    stored-file-length: does [
      parse/all read auto-test-file rule
      stored-length
    ]
    digit: charset [#"0" - #"9"]
    number: [some digit]
    rule: [
      thru ";make-length:" 
      copy stored-length number (stored-length: to integer! stored-length)
      to end
    ]
    
    if not exists? make-file [return]
   
    if any [
      not exists? auto-test-file
      stored-file-length <> length? read make-file
      0:00 < difference modified? make-file modified? auto-test-file
    ][
      print ["Making" auto-test-file " - it will take a while"]
      do make-file
    ]
  ]
  
  setup-temp-files: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    comp-echo: join runnable-dir ["comp-echo" f ".txt"]
  	comp-r: join runnable-dir ["comp" f ".r"]
  	test-src-file: join runnable-dir ["qt-test-comp" f ".red"]
  ]
  
  delete-temp-files: does [
  	  if exists? comp-echo [delete comp-echo]
  	  if exists? comp-r [delete comp-r]
  	  if exists? test-src-file [delete test-src-file]  
  ]
  
  seperate-log-file: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    log-file: join base-dir ["quick-test/quick-test" f ".log"]
  ]
  
  utf-16le-to-utf-8: func [
    {Translates a utf-16LE encoded string to an utf-8 encoded one
     the algorithm is copied from lexer.r                         }
    in-str [string!]
    /local
      out-str
      code
  ][
   out-str: copy ""
   foreach [low high] to binary! in-str [
     code: high * 256 + low
     case [
       code <= 127  [
         append out-str to char! code					            ;-- c <= 7Fh
       ]
       code <= 2047 [							                        ;-- c <= 07FFh
         append out-str join "" [ 
           to char! ((shift code 6) and #"^(1F)" or #"^(C0)")
					 to char! ((code and #"^(3F)") or #"^(80)")
				 ]
			 ]
			 code <= 65535 [					                         		;-- c <= FFFFh
			   append out-str join "" [
			     to char! ((shift code 12) and #"^(0F)" or #"^(E0)")
			     to char! ((shift code 6) and #"^(3F)" or #"^(80)")
			     to char! (code and #"^(3F)" or #"^(80)")
			   ]
			 ]
			 code <= 1114111 [						                        ;-- c <= 10FFFFh
			   append out-str join "" [
			     to char! ((shift code 18) & ^"(07)" or #"^(F0)")
					 to char! ((shift code 12) and #"^(3F)" or #"^(80)")
					 to char! ((shift code 6)  and #"^(3F)" or #"^(80)")
					 to char! (code and #"^(3F)" or #"^(80)")
				 ]
			 ]                         ;-- Codepoints above U+10FFFF are ignored"
		 ]
	 ]
   out-str 
  ]
  
  ;; create the test "dialect"
  
  set '***start-run***              :start-test-run
  set '***start-run-quiet***        :start-test-run-quiet
  set '~~~start-file~~~             :start-file
  set '===start-group===            :start-group
  set '--test--                     :start-test
  set '--compile                    :compile
  set '--compile-red                :compile
  set '--compile-dll          		:compile-dll
  set '--compile-this               :compile-from-string
  set '--compile-this-red           :compile-from-string
  set '--compile-and-run            :compile-and-run
  set '--compile-and-run-red        :compile-and-run 
  set '--compile-and-run-this       :compile-and-run-from-string
  set '--compile-and-run-this-red   :compile-and-run-from-string
  set '--compile-run-print          :compile-run-print
  set '--compile-run-print-red      :compile-run-print
  set '--compiled?                  :compiled?
  set '--run                        :run
  set '--add-to-run-totals          :add-to-run-totals
  set '--run-unit-test              :run-unit-test
  set '--run-unit-test-quiet        :run-unit-test-quiet
  set '--run-script                 :run-script
  set '--run-script-quiet           :run-script-quiet
  set '--run-test-file              :run-test-file
  set '--run-test-file-red          :run-test-file
  set '--run-test-file-quiet        :run-test-file-quiet
  set '--run-test-file-quiet-red    :run-test-file-quiet
  set '--assert                     :assert
  set '--assert-msg?                :assert-msg?
  set '--assert-printed?            :assert-printed?
  set '--assert-red-printed?        :assert-printed?
  set '--clean                      :clean-compile-from-string
  set '===end-group===              :end-group
  set '~~~end-file~~~               :end-file
  set '***end-run***                :end-test-run
  set '***end-run-quiet***          :end-test-run-quiet
  set '--setup-temp-files			:setup-temp-files
  set '--delete-temp-files			:delete-temp-files
  set '--seperate-log-file			:seperate-log-file	
]
REBOL [
  Title:   "Simple testing framework for Red and Red/System programs"
	Author:  "Peter W A Wood"
	File: 	 %quick-test.r
	Version: 0.12.0
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

comment {
	This script makes some assumptions about the directory structure in which 
	files are stored. They are:
    	this script is stored in Red/quick-test/
    	the Red & Red/System compiler is stored in Red/
    	the default dir for tests is Red/system/tests/
    	
    	The default test dirs can be overriden by setting qt/tests-dir before
    	tests are processed
    	The default script header for code supplied as string is Red [], this 
    	can be overriden by setting qt/script-header
    	The default location of the compiler binary is Red/build/bin, this can
    	be overriden by setting qt/bin-compiler
}

qt: make object! [
  
  ;;;;;;;;;;; Setup ;;;;;;;;;;;;;;
  ;; set the base-dir to ....Red/
  base-dir: system/script/path
  base-dir: copy/part base-dir find base-dir "quick-test"
  ;; set the red/system runnable dir
  runnable-dir: dirize base-dir/quick-test/runnable
  ;; set the default base dir for tests
  tests-dir: dirize base-dir/system/tests
  
  ;; set the version number
  version: system/script/header/version
  
  ;; switch for binary compiler usage
  binary?: false
  
  ;; default binary compiler path
  bin-compiler: base-dir/build/bin/red
  
  ;; default script header to be inserted into code supplied in string form
  script-header: "Red []"
  
  ;; set temporary files names
  ;;  use Red/quick-test/runnable for temp files
  comp-echo: runnable-dir/comp-echo.txt
  comp-r: runnable-dir/comp.r
  test-src-file: runnable-dir/qt-test-comp.red
  
  ;; set log file 
  log-file: join system/script/path "quick-test.log"

  ;; make runnable directory if needed
  make-dir runnable-dir
  
  ;; windows ?
  windows-os?: system/version/4 = 3
  
  ;; use Cheyenne call with REBOL v2.7.8 on Windows (re: 'call bug on Windows 7)
  if all [
    windows-os?
    system/version/3 = 8              
  ][
		do %call.r					               
		set 'call :win-call
	]
	
	;; script header parse rules - assumes parsing without /all
	red?: false
	red-header: ["red" any " " "[" to end (red?: true)]
	red-system-header: ["red/system" any " " "[" to end (red?: false)]
	red?-rule: [(red?: false) any [red-system-header | red-header | skip]]
	script-header-rule: [
		(no-script-header?: true) 
		any [ 
				[["red/system" | "red"] any " " "[" (no-script-header?: false)]
			|
				skip
		]
	]

	;;;;;;;;; End Setup ;;;;;;;;;;;;;;
  
  comp-output: copy ""                 ;; output captured from compile
  output: copy ""                      ;; output captured from pgm exec
  exe: none                            ;; filepath to executable
  source-file?: true                   ;; true = running  test file
                                       ;; false = runnning test script
				  

  summary-template: ".. - .................................................. / "
  
  data: make object! [
    title: copy ""
    no-tests: 0
    no-asserts: 0
    passes: 0
    failures: 0
    reset: does [
      title: copy ""
      no-tests: 0
      no-asserts: 0
      passes: 0
      failures: 0
    ]
  ]
  
  file: make data []
  test-run: make data []
  _add-file-to-run-totals: does [
    test-run/no-tests: test-run/no-tests + file/no-tests
    test-run/no-asserts: test-run/no-asserts + file/no-asserts
    test-run/passes: test-run/passes + file/passes
    test-run/failures: test-run/failures + file/failures
  ]
  _signify-failure: does [
    ;; called when a compiler or runtime error occurs
    file/failures: file/failures + 1           
    file/no-tests: file/no-tests + 1
    file/no-asserts: file/no-asserts + 1
    test-run/failures: test-run/failures + 1           
    test-run/no-tests: test-run/no-tests + 1
    test-run/no-asserts: test-run/no-asserts + 1
  ]
  
  ;; group data
  group-name: copy ""
  group?: false
  group-name-not-printed: true
  _init-group: does [
    group?: false
    group-name-not-printed: true
    group-name: copy ""
  ]
  
  ;; test data
  test-name: copy ""
  _init-test: does [
    test-name: copy ""
  ]
  
  ;; print diversion function
  _save-print: :print
  print-output: copy ""
  _quiet-print: func [val] [
    append print-output join "" [reduce val "^/"]
  ]
        
  	compile: func [
  		src [file!]
  		/bin
  		/lib
  	  		target [string!]	
  	  	/local
  	  		comp                          	;; compilation script
  	  		cmd                           	;; compilation cmd
  	  		exe								;; executable name
  ][
    clear comp-output
    
    ;; workout executable name
    either find/last/tail src "/" [
      exe: copy find/last/tail src "/"
    ][
      exe: copy src
    ]
    exe: copy/part exe find exe "."
    either lib [
      switch/default target [
        "Windows"	[exe: join exe [".dll"]]
        "Darwin"   	[exe: join exe [".dylib"]]
      ][
      	  exe: join exe [".so"]
      ]
      exe
    ][     
      if windows-os? [
        exe: join exe [".exe"]
      ]
    ]
    
    ;; find the path to the src
    if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    
    ;; red/system or red
    red?: false
    parse read src red?-rule
 
    ;; compose and write compilation script
    either binary? [
    	if #"/" <> first src [src: tests-dir/:src]     ;; relative path supplied
    	either lib [
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe
    					  " -dlib -t " target " "
    					  to-local-file src
    		]
    	][
    		cmd: join "" [to-local-file bin-compiler " -o " 
    					  to-local-file runnable-dir/:exe " "
    					  to-local-file src	
    		]  		
    	]
    	comp-output: make string! 1024
    	call/wait/output cmd comp-output
    ][
    	comp: mold compose/deep [
    	  REBOL []
    	  halt: :quit
    	  echo (comp-echo)
    	  do/args (reduce base-dir/red.r) (join " -o " [
    	  	  	  reduce runnable-dir/:exe " ###lib###***src***" 
    	  ])
    	]
    	either lib [
    		replace comp "###lib###" join "-dlib -t " [target " "]
    	][
    		replace comp "###lib###" ""
    	]
    
    	replace comp "***src***"  clean-path src
    	write comp-r comp

    	;; compose command line and call it
    	cmd: join to-local-file system/options/boot [" -sc " comp-r]
    	call/wait/output cmd make string! 1024	;; redirect output to anonymous
    											;; buffer
    ]
    
    ;; collect compiler output & tidy up
    if exists? comp-echo [
    	comp-output: read comp-echo
    	delete comp-echo
    ]
    if exists? comp-r [delete comp-r]
    either compile-ok? [
      exe
    ][
      none
    ]    
  ]
  
  compile-and-run: func [src /error /pgm] [
    source-file?: true
    either exe: compile src [
      either error [
        run/error  exe
      ][
      	  either pgm [
      	  	  run/pgm exe
      	  ][
      	  	  run exe
      	  ]
      ]
    ][
      compile-error src
      output: "Compilation failed"
    ]
  ]
    
  compile-and-run-from-string: func [src /error] [
    source-file?: false
    either exe: compile-from-string src [
      either error [
        run/error  exe
      ][
        run exe
      ]
    ][
      
      compile-error "Supplied source"
      output: "Compilation failed"
    ]
  ]
  
  compile-dll: func [
    lib-src [file!]
    target	[string!]
    /local
    	dll
  ][
    ;; compile the lib into the runnable dir
    if not dll: compile/lib lib-src target [
      compile-error lib-src
      output: "Lib compilation failed"  
    ]
    dll
  ]
  
  compile-from-string: func [src][
    ;-- add a default header if not provided
    parse src script-header-rule
    if no-script-header? [
    	insert src join script-header "^/"
    ]
    write test-src-file src
    compile test-src-file                  ;; returns path to executable or none
  ]
  
  compile-error: func [
    src [file! string!]
  ][
    print join "^/" [src " - compiler error^/"]
    print comp-output
    print newline
    clear output                           ;; clear the output from previous test
    _signify-failure
  ]
  
  compile-ok?: func [] [
    either find comp-output "output file size :" [true] [false]
  ] 
  
  compile-run-print: func [src [file!] /error][
  	  either error [
  	  	  compile-and-run/error src
  	  ][
  	  	  compile-and-run src
    ]
    if output <> "Compilation failed" [print output]
  ]
  
  compiled?: func [
    src [string!]
  ][
    exe: compile-from-string src
    clean-compile-from-string
    qt/compile-ok?
  ]
  
  run: func [
    prog [file!]
    ;;/args                         ;; not yet needed
      ;;parms [string!]             ;; not yet needed
    /error                          ;; run time error expected
    /pgm							;; a program not a test
    /local
    exec [string!]                  ;; command to be executed
  ][
    exec: to-local-file runnable-dir/:prog
    ;;exec: join "" compose/deep [(exec either args [join " " parms] [""])]
    clear output
    call/output/wait exec output
    if all [red? windows-os?] [output: qt/utf-16le-to-utf-8 output]
    if all [
      source-file?
      not pgm
      any [
      	  all [
      	   none <> find output "Runtime Error"
      	   not error
      	  ]
      	  none = find output "Passed"
      ]
    ][	
    print "signify failure"
      _signify-failure
    ]
  ]
  
  run-unit-test: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    call/wait cmd
  ]
  
  run-unit-test-quiet: func [
    src [file!]
    /local               
      cmd                             ;; command to run
      test-name                     
  ][
    source-file?: false
    test-name: find/last/tail src "/"
    test-name: copy/part test-name find test-name "."
    prin [ "running " test-name #"^(0D)"]
    clear output
    cmd: join to-local-file system/options/boot [" -sc " tests-dir src]
    call/output/wait cmd output
    if find output "Error:" [_signify-failure]
    add-to-run-totals
    write/append log-file output
    file/title: test-name
    replace file/title "-test" ""
    _print-summary file
  ]
  
  run-script: func [
    src [file!]
    /local
     filename                     ;; filename of script 
     script                       ;; %runnable/filename
  ][
    if not filename: copy find/last/tail src "/" [filename: copy src]
    script: runnable-dir/:filename
    write to file! script read join tests-dir [src]
    if error? try [do script] [_signify-failure]
  ]
  
  run-script-quiet: func [
  	src [file!]
  ][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-script src
    add-to-run-totals
    print: :_save-print
    write/append log-file print-output
    _print-summary file
  ]
  
  run-test-file: func [
  	src [file!]
  ][
    file/reset
    unless file/title: find/last/tail to string! src "/" [file/title: src]
    replace file/title "-test.reds" ""
    replace file/title "-test.red" ""
    compile-run-print src
    add-to-run-totals
  ]
  
  run-test-file-quiet: func [
  	src [file!]
  	][
    prin [ "running " find/last/tail src "/" #"^(0D)"]
    print: :_quiet-print
    print-output: copy ""
    run-test-file src
    print: :_save-print
    write/append log-file print-output
    _print-summary file
    output: copy ""
  ]
  
  add-to-run-totals: func [
    /local
      tests
      
      asserts
      passes
      failures
      rule
      digit
      number
  ][
    digit: charset [#"0" - #"9"]
    number: [some digit]
    ws: charset [#"^-" #"^/" #" "]
    whitespace: [some ws]
    rule: [
      thru "Number of Tests Performed:" whitespace copy tests number
      thru "Number of Assertions Performed:" whitespace copy asserts number
      thru "Number of Assertions Passed:" whitespace copy passed number
      thru "Number of Assertions Failed:" whitespace copy failures number
      to end
    ]
    if parse/all output rule [
      file/no-tests: file/no-tests + to integer! tests
      file/no-asserts: file/no-asserts + to integer! asserts
      file/passes: file/passes + to integer! passed
      file/failures: file/failures + to integer! failures
      _add-file-to-run-totals
    ]
  ]
  
  _start: func [
    data [object!]
    leader [string!]
    title [string!]
  ][
    print [leader title]
    data/title: title
    data/no-tests: 0
    data/no-asserts: 0
    data/passes: 0
    data/failures: 0
    _init-group
  ]

  start-test-run: func [
    title [string!]
  ][
    _start test-run "***Starting***" title
    prin newline
  ]
  
  start-test-run-quiet: func [
    title [string!]
      ][
    _start test-run "" title
    prin newline
    write log-file rejoin ["***Starting*** " title newline]
  ]
  
  start-file: func [
    title [string!]
  ][
    _start file "~~~started test~~~" title
  ]
  
  start-group: func[
    title [string!]
  ][
   group-name: title
   group?: true
  ]
  
  start-test: func[
    title [string!]
  ][
    _init-test
    test-name: title
    file/no-tests: file/no-tests + 1
  ]
    
  assert: func [
    assertion [logic!]
  ][
    file/no-asserts: file/no-asserts + 1
    either assertion [
      file/passes: file/passes + 1
    ][
      file/failures: file/failures + 1
      if group? [
        if group-name-not-printed [
          print ""
          print ["===group===" group-name]
        ]
      ]
      print ["---test---" test-name "FAILED**************"]
    ]
  ]
  
  assert-msg?: func [msg][
    assert found? find qt/comp-output msg
  ]
  
  assert-printed?: func [msg] [
    assert found? find qt/output msg
  ]
  
  clean-compile-from-string: does [
    if exists? test-src-file [delete test-src-file]
    if all [exe exists? exe][delete exe]
]
  
  end-group: does [
    _init-group
  ]
  
  _end: func [
    data [object!]
    leader [string!]
  ][
    print [leader data/title]
    print ["No of tests  " data/no-tests]
    print ["No of asserts" data/no-asserts]
    print ["Passed       " data/passes]
    print ["Failed       " data/failures]
    if data/failures > 0 [print "***TEST FAILURES***"]
    print ""
  ]
  
  end-file: func [] [
    _end file "~~~finished test~~~" 
    _add-file-to-run-totals
  ]
  
  end-test-run: func [] [
      print ""
    _end test-run "***Finished***"
  ]
  
  end-test-run-quiet: func [] [
    print: :_quiet-print
    print-output: copy ""
    end-test-run
    print: :_save-print
    write/append log-file print-output
    prin newline
    _print-summary test-run
  ]
  
  _print-summary: func [
    data [object!]
    /local
      print-line
  ][
    print-line: copy summary-template
    print-line: skip print-line 5
    remove/part print-line length? data/title
    insert print-line data/title
    print-line: skip tail print-line negate (3 + length? mold data/passes)
    remove/part print-line length? mold data/passes
    insert print-line data/passes
    append print-line data/no-asserts
    print-line: head print-line
    either data/no-asserts = data/passes [
      replace print-line ".." "ok"
    ][
      replace/all print-line "." "*"
      append print-line " **"
    ]
    print print-line
  ]
  
  make-if-needed?: func [
    {This function is used by the Red run-all scripts to build the auto files
     when necessary.} 
    auto-test-file [file!]
    make-file [file!]
    /lib-test
    /local
      stored-length   ; the length of the make... .r file used to build auto tests
      stored-file-length
      digit
      number
      rule
  ][
    auto-test-file: join tests-dir auto-test-file
    make-file: join tests-dir make-file
    
    stored-file-length: does [
      parse/all read auto-test-file rule
      stored-length
    ]
    digit: charset [#"0" - #"9"]
    number: [some digit]
    rule: [
      thru ";make-length:" 
      copy stored-length number (stored-length: to integer! stored-length)
      to end
    ]
    
    if not exists? make-file [return]
   
    if any [
      not exists? auto-test-file
      stored-file-length <> length? read make-file
      0:00 < difference modified? make-file modified? auto-test-file
    ][
      print ["Making" auto-test-file " - it will take a while"]
      do make-file
    ]
  ]
  
  setup-temp-files: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    comp-echo: join runnable-dir ["comp-echo" f ".txt"]
  	comp-r: join runnable-dir ["comp" f ".r"]
  	test-src-file: join runnable-dir ["qt-test-comp" f ".red"]
  ]
  
  delete-temp-files: does [
  	  if exists? comp-echo [delete comp-echo]
  	  if exists? comp-r [delete comp-r]
  	  if exists? test-src-file [delete test-src-file]  
  ]
  
  seperate-log-file: func [
  	  /local
  	  	f
  ][
  	f: to string! now/time/precise
  	f: replace/all f ":" ""
  	f: replace/all f "." ""
    log-file: join base-dir ["quick-test/quick-test" f ".log"]
  ]
  
  utf-16le-to-utf-8: func [
    {Translates a utf-16LE encoded string to an utf-8 encoded one
     the algorithm is copied from lexer.r                         }
    in-str [string!]
    /local
      out-str
      code
  ][
   out-str: copy ""
   foreach [low high] to binary! in-str [
     code: high * 256 + low
     case [
       code <= 127  [
         append out-str to char! code					            ;-- c <= 7Fh
       ]
       code <= 2047 [							                        ;-- c <= 07FFh
         append out-str join "" [ 
           to char! ((shift code 6) and #"^(1F)" or #"^(C0)")
					 to char! ((code and #"^(3F)") or #"^(80)")
				 ]
			 ]
			 code <= 65535 [					                         		;-- c <= FFFFh
			   append out-str join "" [
			     to char! ((shift code 12) and #"^(0F)" or #"^(E0)")
			     to char! ((shift code 6) and #"^(3F)" or #"^(80)")
			     to char! (code and #"^(3F)" or #"^(80)")
			   ]
			 ]
			 code <= 1114111 [						                        ;-- c <= 10FFFFh
			   append out-str join "" [
			     to char! ((shift code 18) & ^"(07)" or #"^(F0)")
					 to char! ((shift code 12) and #"^(3F)" or #"^(80)")
					 to char! ((shift code 6)  and #"^(3F)" or #"^(80)")
					 to char! (code and #"^(3F)" or #"^(80)")
				 ]
			 ]                         ;-- Codepoints above U+10FFFF are ignored"
		 ]
	 ]
   out-str 
  ]
  
  ;; create the test "dialect"
  
  set '***start-run***              :start-test-run
  set '***start-run-quiet***        :start-test-run-quiet
  set '~~~start-file~~~             :start-file
  set '===start-group===            :start-group
  set '--test--                     :start-test
  set '--compile                    :compile
  set '--compile-red                :compile
  set '--compile-dll          		:compile-dll
  set '--compile-this               :compile-from-string
  set '--compile-this-red           :compile-from-string
  set '--compile-and-run            :compile-and-run
  set '--compile-and-run-red        :compile-and-run 
  set '--compile-and-run-this       :compile-and-run-from-string
  set '--compile-and-run-this-red   :compile-and-run-from-string
  set '--compile-run-print          :compile-run-print
  set '--compile-run-print-red      :compile-run-print
  set '--compiled?                  :compiled?
  set '--run                        :run
  set '--add-to-run-totals          :add-to-run-totals
  set '--run-unit-test              :run-unit-test
  set '--run-unit-test-quiet        :run-unit-test-quiet
  set '--run-script                 :run-script
  set '--run-script-quiet           :run-script-quiet
  set '--run-test-file              :run-test-file
  set '--run-test-file-red          :run-test-file
  set '--run-test-file-quiet        :run-test-file-quiet
  set '--run-test-file-quiet-red    :run-test-file-quiet
  set '--assert                     :assert
  set '--assert-msg?                :assert-msg?
  set '--assert-printed?            :assert-printed?
  set '--assert-red-printed?        :assert-printed?
  set '--clean                      :clean-compile-from-string
  set '===end-group===              :end-group
  set '~~~end-file~~~               :end-file
  set '***end-run***                :end-test-run
  set '***end-run-quiet***          :end-test-run-quiet
  set '--setup-temp-files			:setup-temp-files
  set '--delete-temp-files			:delete-temp-files
  set '--seperate-log-file			:seperate-log-file	
]
#' Load a bunch of dependencies by filename
#' 
#' This is useful for reducing pollution in the global namespace,
#' and not loading multiple files twice unnecessarily.
#'
#' @export
#' @param ... see examples.
#' @param envir environment. The parent environment to use when calling
#'   \code{base::source} to fetch dependencies.
#' @param local logical. If \code{TRUE} and \code{envir} is missing,
#'   it will set \code{envir = parent.frame()}.
#' @examples
#' \dontrun{
#' helper_fn <- define('some/dir/helper_fn')
#' define(c('some/dir/helper_fn', 'some/other_dir/library_fn'), function(helper_fn, library_fn) { ... }
#' helper_fns <<- define('some/dir/helper_fn1', 'some/otherdir/helper_fn2')
#' helper_fns[[1]]('do something'); helper_fns[[2]]('do something else')
#' }
define <- (function() {
  number_of_required_arguments <- function(fn) {
    function_has_variable_number_of_arguments <- '...' %in% names(formals(fn))
    if (function_has_variable_number_of_arguments) return(NA_real_)
    function_arguments <- formals(fn)
    required_arguments <- sapply(function_arguments, class) == 'name'
    sum(required_arguments)
  }

  process_function_with_no_dependencies <- function(fn) {
    number_of_arguments <- number_of_required_arguments(fn)
    if (number_of_arguments == 0) fn()
    else if (number_of_arguments == 1) fn(define)
    else stop("Ramd::define only processes functions with <= 1 ",
              "arguments if no dependencies are given, but the ",
              "passed function has ", number_of_required_arguments, 
              " required arguments")
  }

  flatten <- function(lists) {    
    atomic_vector <- unlist(c(lists))
    delimited_string <- paste(atomic_vector, collapse = ' ')
    strsplit(delimited_string, '[^-a-zA-Z0-9.-_`:\\\\\\/]+')[[1]]
  }

  parse_dependencies <- function(arguments) {
    cd <- current_directory()
    if (any(sapply(arguments, class) != 'character'))
      stop("Ramd::define only accepts atomic character vectors for ",
           "specifying dependencies")
    dependencies <- unlist(c(arguments))
    if ('Ramd.no_flatten' %in% names(.Options) &&
        getOption('Ramd.no_flatten')) dependencies
    else flatten(dependencies)
  }

  fetch_dependencies <- function(arguments, envir) {
    dependency_names <- parse_dependencies(arguments)
    dependencies <- lapply(dependency_names, load_dependency, envir = envir)
    names(dependencies) <- dependency_names
    dependencies
  }

  verify_number_of_required_arguments_matches_number_of_dependencies <-
    function(fn, number_of_dependencies) {
      num_of_required_arguments <- number_of_required_arguments(fn)
      if (is.na(num_of_required_arguments)) return(TRUE)
      if (num_of_required_arguments != number_of_dependencies)
        stop("Ramd::define was not able to load dependencies because ",
             number_of_dependencies, " dependenc",
             # Pluralization, for fun!
             if (number_of_dependencies == 1) 'y was' else 'ies were',
             " passed in but the given function has ",
             num_of_required_arguments, " required argument",
             if (num_of_required_arguments == 1) '' else 's')
      TRUE
    }

  function(..., envir = parent.env(topenv()), local) {
    if (!missing(local) && isTRUE(local)) {
      envir <- parent.frame()
    }

    arguments <- list(...)
    if ('packages' %in% names(arguments)) {
      if (length(arguments) == 1)
        stop("Ramd::define does more than just load packages, ",
             "please provide some dependencies or a function. ",
             "To just load packages, use Ramd::packages")
      packages(arguments$packages)
      arguments <- arguments[names(arguments) != 'packages']
    }

    fn <- tail(arguments, 1)[[1]]
    valid_function <- is.function(fn)
    if (valid_function) {
      dependencies <- head(arguments, -1)
      if (length(dependencies) == 0)
        return (process_function_with_no_dependencies(fn))
    } else dependencies <- arguments

    if (valid_function)
      verify_number_of_required_arguments_matches_number_of_dependencies(
        fn, length(unlist(dependencies)))

    dependencies <- fetch_dependencies(dependencies, envir = envir)
    if (valid_function) do.call(fn, unname(dependencies))
    else dependencies
  }

})()
`%||%` <- function(x, y) if (is.null(x)) y else x


# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Attempt to memoize a function using the memoise package.
#' 
#' This function will load the \code{memoise} package if it is
#' available, or do nothing otherwise.
#'
#' (Blame Hadley for the spelling of memoise.)
#'
#' @param fn function. The function to memoize.
#' @return nothing, but \code{try_memoize} will use non-standard
#'   evaluation to memoize in the calling environment.
#' @name try_memoize
try_memoize <- function(fn) {
  if ('memoise' %in% installed.packages()) {
    require(memoise)
    eval.parent(substitute(memoise(fn)))
  }
  fn
}

# A reference class that implements a stack data structure.
shtack <- setRefClass('stack', list(elements = 'list'), methods = list(
  clear      = function()  { elements <<- list() },
  empty      = function()  { length(elements) == 0 },
  push       = function(x) { elements[[length(elements) + 1]] <<- x },
  peek       = function(n = 1)  {
    if (isTRUE(n)) return(elements)
    els <- seq(length(elements), length(elements) - n + 1)
    if (length(els) == 1) elements[[els]]
    else elements[els]
  },
  pop        = function()  {
    if (length(elements) == 0) stop("director:::stack is empty")
    tmp <- tail(elements, 1)[[1]]
    elements[[length(elements)]] <<- NULL
    tmp
  },
  pop_all    = function()  { tmp <- elements; elements <<- list(); tmp }
))                                                                      

#' Whether or not a directory is an idempotent resource.
#'
#' By definition, this means the directory contains a file with the same name
#' (ignoring extension) as the directory.
#'
#' @param dir character. The directory to check.
#' @return \code{TRUE} or \code{FALSE} according as the directory is idempotent.
#'   There is no checking to ensure the directory exists.
#' @examples
#' \dontrun{
#'   # If we have a directory foo containing foo.R, then
#'   is.idempotent_directory('foo')
#'   # is TRUE, otherwise it's FALSE.
#' }
is.idempotent_directory <- function(dir) {
  # TODO: (RK) Case insensitivity in OSes that don't respect it, i.e. Windows?
  # TODO: (RK) File extensions besides .r and .R?
  extensionless_exists(file.path(dir, basename(dir)))
}

#' Determine whether an R file exists regardless of case of extension.
#'
#' @param filename character. The filename to test (possibly without extension).
#' @return \code{TRUE} or \code{FALSE} if the filename exists regardless of 
#'   R extension.
#' @examples
#' \dontrun{
#'  # Assume we have a file \code{"foo.R"}. The following all return \code{TRUE}.
#'  extensionless_exists('foo.R')
#'  extensionless_exists('foo.r')
#'  extensionless_exists('foo')
#' }
extensionless_exists <- function(filename) {
  file.exists(paste0(strip_r_extension(filename), '.r')) ||
  file.exists(paste0(strip_r_extension(filename), '.R')) 
  # Don't use the any + sapply trick because we can skip the latter check if the
  # former succeeds.
}

#' Strip R extension.
#'
#' @param filename character. The filename to strip.
#' @return the filename without the '.r' or '.R' at the end.
strip_r_extension <- function(filename) {
  stopifnot(is.character(filename))
  gsub("\\.[rR]$", "", filename)
}

#' Strip a root file path from an absolute filename.
#'
#' @param root character. The root path.
#' @param filename character. The full file name.
#' @return the stripped file path.
#' @examples
#' \dontrun{
#'   stopifnot("test" == strip_root("foo/bar/test", "test"))
#' }
strip_root <- function(root, filename) {
  stopifnot(is.character(root) && is.character(filename))
  if (substring(filename, 1, nchar(root)) == root) {
    filename <- substring(filename, nchar(root) + 1, nchar(filename)) 
    gsub("^\\/*", "", filename)
  } else filename
}

#' Convert an idempotent resource name to a non-idempotent resource name.
#'
#' @param filename character. The filename to convert.
#' @return the non-idempotent filename.
drop_idempotence <- function(filename) {
  if (basename(dirname(filename)) == basename(filename))
    dirname(filename)
  else filename
}

#' Convert a filename to a resource name.
#'
#' @param filename character. The filename.
#' @return the resource name (i.e., stripped of idempotence and extension).
resource_name <- function(filename) {
  drop_idempotence(strip_r_extension(filename))
}

#' Create a resource cache key from a resource key.
#'
#' This is the key under whose director cache the info about the resource
#' as of previous execution will be stored.
#'
#' @param resource_key character. The resource key.
#' @return a cache key, currently just \code{"resource_cache/"} followed by
#'    the \code{resource_key}.
resource_cache_key <- function(resource_key) {
 file.path('resource_cache', resource_key)
}

#' Get all helper files associated with an idempotent resource directory.
#'
#' @param path character. The *absolute* path of the idempotent resource.
#' @return a character list of relative helper paths.
#' @examples
#' \dontrun{
#'   # If we have a directory structure given by \code{"model/model.R"},
#'   # \code{"model/constants.R"}, \code{"model/functions.R"}, then the
#'   # below will return \code{c("constants.R", "functions.R")}.
#'   get_helpers("model")
#' }
get_helpers <- function(path) {
  helper_files <- list.files(path, pattern = '\\.[rR]$') # TODO: (RK) Recursive helpers?
  same_file <- which(vapply(helper_files, 
    function(f) strip_r_extension(f) == basename(path), logical(1)))
  helper_files <- helper_files[-same_file]
}

#' Whether or not any substring of a string is any of a set of strings.
#'
#' @param string character.
#' @param set_of_strings character.
#' @return logical
#' @examples
#' stopifnot(director:::any_is_substring_of('test', c('blah', 'te', 'woo'))) # TRUE
#' stopifnot(!director:::any_is_substring_of('test', c('blah', 'woo'))) # FALSE
any_is_substring_of <- function(string, set_of_strings) {
  any(vapply(set_of_strings,
             function(x) substring(string, 1, nchar(x)) == x, logical(1)))
}

# Stolen from testthat:::colourise
.fg_colours <- 
  structure(c("0;30", "0;34", "0;32", "0;36", "0;31", "0;35", "0;33",
  "0;37", "1;30", "1;34", "1;32", "1;36", "1;31", "1;35", "1;33",
  "1;37"), .Names = c("black", "blue", "green", "cyan", "red",
  "purple", "brown", "light gray", "dark gray", "light blue", "light green",
  "light cyan", "light red", "light purple", "yellow", "white"))
.bg_colours <- 
  structure(c("40", "41", "42", "43", "44", "45", "46", "47"), .Names = c("black",
  "red", "green", "brown", "blue", "purple", "cyan", "light gray"
  ))

colourise <- function (text, fg = "black", bg = NULL) {
  term <- Sys.getenv()["TERM"]
  colour_terms <- c("xterm-color", "xterm-256color", "screen",
      "screen-256color")
  if (!any(term %in% colour_terms, na.rm = TRUE)) return(text)
  col_escape <- function(col) paste0("\033[", col, "m")
  col <- .fg_colours[tolower(fg)]
  if (!is.null(bg)) col <- paste0(col, .bg_colours[tolower(bg)], sep = ";")
  init <- col_escape(col)
  reset <- col_escape("0")
  paste0(init, text, reset)
}



require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.basenames <- function(path,recursive=FALSE) {    
    grn.files <- list.files(path, pattern = "_Grn.idat$", recursive = recursive, 
                            ignore.case = TRUE, full.names = TRUE)
    red.files <- list.files(path, pattern = "_Red.idat$", recursive = recursive, 
                            ignore.case = TRUE, full.names = TRUE)
    intersect(sub("_Grn.idat$", "", grn.files), 
              sub("_Red.idat$", "", red.files))
}

meffil.probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

meffil.read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

meffil.rg.to.mu <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

meffil.extract.controls <- function(basename, probes=meffil.probe.info()) {
    msg("sample file", basename)
    rg <- meffil.read.rg(basename)
    extract.controls(rg, probes)
}

meffil.background.correct <- function(rg, probes=meffil.probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target %in% c("M","U") & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1

        addresses <- probes$address[which(probes$type == "control" & probes$dye == dye)]
        xc <- rg[[dye]][addresses]
        xc[which(xc <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        bg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), c(xf,xc)) + offset
        names(bg) <- c(names(xf), names(xc))
        bg
    })
}

meffil.dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}


meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=meffil.probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- meffil.read.rg(basename)
    rg.correct <- meffil.background.correct(rg, probes)
    rg.correct <- meffil.dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- meffil.rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

meffil.preprocess.control.matrix <- function(control.matrix) {
    control.matrix <- control.matrix[-grep("^intensity.bc", rownames(control.matrix)),]
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    t(scale(control.matrix))
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=meffil.probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("preprocessing the control matrix")
    control.matrix <- meffil.preprocess.control.matrix(control.matrix)

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}

meffil.normalize.sample <- function(object, probes=meffil.probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- meffil.read.rg(object$basename)
    rg.correct <- meffil.background.correct(rg, probes)
    rg.correct <- meffil.dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- meffil.rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-select.normalization.subsets(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=meffil.probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}


extract.controls <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    ## minfi does this. shouldn't it be green, not red??????
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ext %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ext %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.Rp <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.Rp,na.rm=T)/mean(spec1.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.Gp <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.Gp,na.rm=T)/mean(spec1.R,na.rm=T)
    ## color swap vs spec1.ratio1??? just following minfi but that seems weird
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normC + normG)/(normA + normT)

    rg.bg <- meffil.background.correct(rg, probes)
    addresses <- probes.R$address[which(probes.R$target %in% c("NORM_A", "NORM_T"))]
    intensity.bc.R <- mean(rg.bg$R[addresses], na.rm = TRUE)
    addresses <- probes.G$address[which(probes.G$target %in% c("NORM_G", "NORM_C"))]
    intensity.bc.G <- mean(rg.bg$G[addresses], na.rm = TRUE)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio,
      intensity.bc.G=intensity.bc.G,
      intensity.bc.R=intensity.bc.R)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    ratios <- control.matrix["intensity.bc.G",]/control.matrix["intensity.bc.R",]
    reference <- which.min(abs(ratios-1))
    intensity <- (control.matrix["intensity.bc.G",] + control.matrix["intensity.bc.R",])[reference]/2
    list(R=intensity/control.matrix["intensity.bc.R",sample.idx],
         G=intensity/control.matrix["intensity.bc.G",sample.idx])
}


define.quantile.probe.sets <- function(probes=meffil.probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

select.normalization.subsets <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles + t(residuals(fits))
}

compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


########################
#Functions for calculating
#sufficient statistics
#
########################
legendre_Pl_array<-function(m,y){
  pf<-polynomial.functions(legendre.polynomials(m,normalized=F))
  lv<-sapply(X=1:(m+1),FUN=function(x){
    pf[[x]](y)
  })
  return(t(lv)*sqrt(2))
}

edge.means<-function(dat,edgelist,m,cores){
  n<-dim(dat)[1]
  nedge<- dim(edgelist)[1]
  if(nedge==0) return(array(dim=c(m,m,0)))
  me<-mclapply(
    1:nedge,
    function(e){
      ge<-edgelist[e,]
      s<-ge[1];t<-ge[2]
      tcrossprod(legendre_Pl_array(m,2*dat[,s]-1)[-1,,drop=F],
                 legendre_Pl_array(m,2*dat[,t]-1)[-1,,drop=F])/n
    },
    mc.cores=cores)
  return(array(unlist(me),dim=c(m,m,nedge)))
}

node.means<-function(dat,m,cores){
  if(is.vector(dat)){
    dat<-matrix(dat,length(dat),1)
  }
  d=dim(dat)[2]
  me<-mclapply(
    1:d,
    function(v){
      rowMeans(legendre_Pl_array(m,2*dat[,v]-1)[-1,,drop= F])
    },
    mc.cores=cores
  )
  return(matrix(unlist(me),nrow=d,byrow=T ))
}## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}

textareaInput <- function(inputId, label, value="", placeholder="", rows=2){
  tagList(
    div(strong(label), style="margin-top: 5px;"),
    tags$style(type="text/css", "textarea {width:100%; margin-top: 5px;}"),
    tags$textarea(id = inputId, placeholder = placeholder, rows = rows, value))
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='', selectize=FALSE, size=3)),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(id='sheetControlTab',
                 tabPanel('Type', value='sheetTabType',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter')),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping', value='sheetTabMapping',

                          fluidRow(
                            column(4,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL, selectize=FALSE, size=15)
                                   ),
                            column(8,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='', inline=TRUE)
                                                    ),

                                   uiOutput('mapOrSetUI')
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters', value='sheetTabFilters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize', value='sheetTabCustomize',
                          textareaInput(inputId = 'plotTitle', label="Plot Title", value="",
                                        placeholder = 'Enter Plot Title here', rows = 2),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    colorInput('textColor', 'Font Color'),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    colorInput('rectColor', 'Border Color'),
                                                    colorInput('rectFill', 'Fill'),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    colorInput('lineColor', 'Line Color'),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   ),
                                   conditionalPanel('output.ggElementType=="character"',
                                                    uiOutput('charSetting')
                                   )
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))



####################################################
## Project saving and loading
####################################################
shrink <- function(x){
  if(is.list(x) && !is.data.frame(x)){
    if(is.reactivevalues(x)){
      x <- lapply(reactiveValuesToList(x), function(y){
        if(typeof(y)!='closure') shrink(y) else NULL
      })
      attr(x, 'wasReavtive') <- TRUE
    } else {
      x <- lapply(x, shrink)
    }
  } else {
    if(typeof(x)!='closure') x else NULL
  }
  x
}

output$downloadProject <- downloadHandler(
  filename = function() { 'MyProject.sData' },
  content = function(file) {
    isolate({

      allData <- list(pp=shrink(projProperties),
                      dl=lapply(datList, function(d){
                        list('staticProperties'=d[['staticProperties']],
                             'dynamicProperties'=shrink(d[['dynamicProperties']]))
                      }),
                      sl=lapply(sheetList, function(d){
                        list('dynamicProperties'=shrink(d[['dynamicProperties']]))
                      }),
                      docl=shrink(docList))
      save(allData, file=file)

    })
  }
)


loadProject <- function(file, replaceOrMerge='replace'){
  load(file)

  if(replaceOrMerge=='replace'){
    for(n in names(datList)) datList[[n]] <<- NULL; projProperties[['activeDat']] <<- NULL
    for(n in names(sheetList)) sheetList[[n]] <<- NULL; projProperties[['activeSheet']] <<- NULL
    for(n in names(docList)) docList[[n]] <<- NULL; projProperties[['activeDoc']] <<- NULL
  }

  for(n in names(allData$pp)){
    if(is.null(projProperties[[n]]) || projProperties[[n]] != allData$pp[[n]]){
      projProperties[[n]] <<- allData$pp[[n]]
    }
  }

  for(di in names(allData$dl)){
    if(is.null(datList[[di]])){ # new data
      datList[[di]] <<- DatClass$new('staticProperties'=allData$dl[[di]][['staticProperties']])
      datList[[di]][['dynamicProperties']] <<- reactiveValues()

    }
    for(n in names(allData$dl[[di]][['dynamicProperties']])){
      x <- allData$dl[[di]][['dynamicProperties']][[n]]
      if(n=='fieldsList'){
        if(is.null(datList[[di]][['dynamicProperties']][[n]])) datList[[di]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(datList[[di]][['dynamicProperties']][[n]][[n1]])) datList[[di]][['dynamicProperties']][[n]][[n1]] <<- reactiveValues()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              datList[[di]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
            }
          } else {
            datList[[di]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        datList[[di]][['dynamicProperties']][[n]] <<- x
      }
    }
    datList[[di]]$setDatDependencies()
  }

  for(si in names(allData$sl)){
    if(is.null(sheetList[[si]])){ # new sheet
      sheetList[[si]] <<- createNewSheetObj(withPlotLayer=FALSE)
      setSheetReactives(si)
    }
    for(n in names(allData$sl[[si]][['dynamicProperties']])){
      x <- allData$sl[[si]][['dynamicProperties']][[n]]
      if(n=='layerList'){
        if(is.null(sheetList[[si]][['dynamicProperties']][[n]])) sheetList[[si]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(sheetList[[si]][['dynamicProperties']][[n]][[n1]]))
              sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- createNewLayer()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              if(n2=='aesList'){
                names3 <- names(x[[n1]][[n2]])
                for(n3 in names3){
                  if(is.reactivevalues(x[[n1]][[n2]][[n3]])){
                    names4 <- names(x[[n1]][[n2]][[n3]])
                    for(n4 in names4){
                      if(typeof(x[[n1]][[n2]][[n3]][[n4]]) != 'closure')
                        sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]][[n4]] <<- x[[n1]][[n2]][[n3]][[n4]]
                    }
                    setAesReactives(si,n1,n3)
                  } else {
                    sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]] <<- x[[n1]][[n2]][[n3]]
                  }
                }
              } else {
                sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
              }
            }
          } else {
            sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        sheetList[[si]][['dynamicProperties']][[n]] <<- x
      }
    }
  }

  for(di in names(allData$docl)){
    if(is.null(docList[[di]])){ # new doc
      docList[[di]] <<- reactiveValues()

    }
    for(n in names(allData$docl[[di]])){
      x <- allData$docl[[di]][[n]]
      docList[[di]][[n]] <<- x
    }
  }

  ## update all UI
  sapply(unique(c(names(input), names(updateInput))), triggerUpdateInput)
  updateTabsetPanel(session, 'mainNavBar', selected='Visualize')
}

observe({
  inFile <- input[['loadProject']]
  isolate({
    if (!is.null(inFile)){
      loadProject(file=inFile$datapath, replaceOrMerge=input[['loadProjectAction']])
    }
  })

})

observe({
  v <- input$openSampleProj
  isolate({
    file <- paste('samples', input[['sampleProj']], sep='/')
    if(v && file.exists(file)){
      loadProject(file=file, 'replace')
    }
  })
})
## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}

textareaInput <- function(inputId, label, value="", placeholder="", rows=2){
  tagList(
    div(strong(label), style="margin-top: 5px;"),
    tags$style(type="text/css", "textarea {width:100%; margin-top: 5px;}"),
    tags$textarea(id = inputId, placeholder = placeholder, rows = rows, value))
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='', selectize=FALSE, size=3)),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(id='sheetControlTab',
                 tabPanel('Type', value='sheetTabType',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping', value='sheetTabMapping',

                          fluidRow(
                            column(4,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL, selectize=FALSE, size=15)
                                   ),
                            column(8,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='', inline=TRUE)
                                                    ),

                                   uiOutput('mapOrSetUI')
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters', value='sheetTabFilters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize', value='sheetTabCustomize',
                          textareaInput(inputId = 'plotTitle', label="Plot Title", value="",
                                        placeholder = 'Enter Plot Title here', rows = 2),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    colorInput('textColor', 'Font Color'),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    colorInput('rectColor', 'Border Color'),
                                                    colorInput('rectFill', 'Fill'),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    colorInput('lineColor', 'Line Color'),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   ),
                                   conditionalPanel('output.ggElementType=="character"',
                                                    uiOutput('charSetting')
                                   )
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))


## switching data source
observe({
  v <- input$datList
  isolate({
    if(!isEmpty(input$datList)) projProperties[['activeDat']] <<- v
  })
})
observe({
  updateInput[['activeDat']]
  updateSelectInput(session, 'datList', choices=(datListNames()),
                    selected=isolate(projProperties[['activeDat']]))
})


## modify dat source name
observe({
  v <- input$datName
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      if(!isEmpty(v) && isEmpty(datListNames()[v])){
        ## the second condition makes sure v is different
        ## update doc's rmd
        oldName <- paste('`', datList[[currentDat]][['dynamicProperties']][['name']], '`', sep='')
        newName <- paste('`', v, '`', sep='')
        sapply(names(docList), function(currentDoc){
          docList[[currentDoc]][['rmd']] <<- gsub(oldName, newName, docList[[currentDoc]][['rmd']], fixed=TRUE)
          NULL
        })
        triggerUpdateInput('docRmd')

        datList[[currentDat]][['dynamicProperties']][['name']] <<- v
      }
    }
  })

})
observe({
  updateInput[['datName']]
  currentDat <- projProperties[['activeDat']]
  s <- if(!isEmpty(currentDat)){
    isolate(datList[[currentDat]][['dynamicProperties']][['name']])
  } else ''
  updateTextInput(session, 'datName', value=null2String(s))
})

## Selecting fields
observe({
  activeField <- input$fieldsList
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      datList[[currentDat]][['dynamicProperties']][['activeField']] <<- activeField
    }
  })

})
observe({
  updateInput[['activeField']]
  currentDat <- projProperties[['activeDat']]
  s <- if(!isEmpty(currentDat)){
    isolate(datList[[currentDat]][['dynamicProperties']][['activeField']])
  } else ''
  choices <- if(!isEmpty(currentDat)) datList[[currentDat]][['fieldNames']]()
  updateSelectizeInput(session, "fieldsList", choices=null2String(choices),
                       selected=null2String(s))
})

## modify field name
observe({
  v <- (input$fieldName) #make.names
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      currentField <- (datList[[currentDat]][['dynamicProperties']][['activeField']])
      if(!isEmpty(currentField)){
        if(!isEmpty(v) && isEmpty((datList[[currentDat]][['fieldNames']]())[v])){
          datList[[currentDat]][['dynamicProperties']][['fieldsList']][[currentField]][['name']] <<- v
          if(v!=input$fieldName) triggerUpdateInput('fieldName')
        }
      }
    }
  })

})
observe({
  updateInput[['fieldName']]
  currentDat <- projProperties[['activeDat']]
  s <- ''
  if(!isEmpty(currentDat)){
    currentField <- datList[[currentDat]][['dynamicProperties']][['activeField']]
    if(!isEmpty(currentField)){
      s <- isolate(datList[[currentDat]][['dynamicProperties']][['fieldsList']][[currentField]][['name']])
    }
  }
  updateTextInput(session, 'fieldName', value=null2String(s))
})

## Manipulating set of measures
observe({
  newMeasures <- input$measures
  isolate({
    currentDat <- (projProperties[['activeDat']])
    if(!isEmpty(currentDat)){
      datList[[currentDat]][['dynamicProperties']][['measures']] <<- newMeasures
    }
  })
})
observe({
  updateInput[['measures']]
  currentDat <- projProperties[['activeDat']]
  s <- if(!isEmpty(currentDat)){
    isolate(datList[[currentDat]][['dynamicProperties']][['measures']])
  } else ''
  choices <- if(!isEmpty(currentDat)) datList[[currentDat]][['fieldNames']]()
  updateSelectizeInput(session, "measures", choices=null2String(choices),
                       selected=null2String(s))
})

## Add data source from text file
observe({
  # input$file1 will be NULL initially. After the user selects
  # and uploads a file, it will be a data frame with 'name',
  # 'size', 'type', and 'datapath' columns. The 'datapath'
  # column will contain the local filenames where the data can
  # be found.
  inFile <- input[['file']]
  isolate({
    if (!is.null(inFile)){
      dat  <- fread(inFile$datapath, header="auto", sep="auto")
      fileN <- paste('file_',newGuid(),sep='')
      existingNames <- names(datListNames())
      ## make sure the new name is different
      newName <- make.unique(c(existingNames, inFile$name), sep='_')[length(existingNames)+1]

      datList[[fileN]] <<- createNewDatClassObj(dat, name=newName,
                                                nameOriginal=inFile$name, type='file')
      projProperties[['activeDat']] <<- fileN
      triggerUpdateInput('activeDat')
    }
  })

})

output$uploadingTextFile <- reactive({
  TRUE
})
outputOptions(output, "uploadingTextFile", suspendWhenHidden=FALSE)

output$datPreview <- renderDataTable({
  currentDat <- projProperties[['activeDat']]
  if(!isEmpty(currentDat)){
    datPrev <- datList[[currentDat]][['datR']]()
    setnames(datPrev, names(datList[[currentDat]][['fieldNames']]()))
    datPrev
  }
})


## Text file import calibration

#   observe({
#     hh <- input[['header']]; ss <- input[['sep']]; qq <- input[['quote']]
#     if(uploadingData){
#       inFile <- isolate(input[['file']])
#
#       if (!is.null(inFile)){
#
#         dat  <- read.csv(inFile$datapath, header=hh, sep=ss, quote=qq)
#         fileN <- isolate(input$datList)
#         datList[[fileN]] <<- dat
#
#         defaultMeasures <- colnames(dat)[apply(dat,2,is.numeric)]
#         updateSelectizeInput(session, "measures", choices=colnames(dat), selected=defaultMeasures)
#
#         output$datPreview <- renderDataTable({
#           (dat)
#         })
#
#         metaDataSources[[fileN]][['data']] <<- dat
#         metaDataSources[[fileN]][['measures']] <<- defaultMeasures
#
#       }
#     }
#   })



####################################################
## Project saving and loading
####################################################
output$downloadProject <- downloadHandler(
  filename = function() { 'MyProject.sData' },
  content = function(file) {
    isolate({
      for(di in names(datList)){
        datList[[di]]$removeDatDependencies()
      }
      allData <- list(pp=reactiveValuesToList(projProperties),
                      dl=datList,
                      sl=sheetList,
                      docl=docList)
      save(allData, file=file)
      for(di in names(datList)){
        datList[[di]]$setDatDependencies()
      }
    })
  }
)


loadProject <- function(file, replaceOrMerge='replace'){
  load(file)

  if(replaceOrMerge=='replace'){
    for(n in names(datList)) datList[[n]] <<- NULL; projProperties[['activeDat']] <<- NULL
    for(n in names(sheetList)) sheetList[[n]] <<- NULL; projProperties[['activeSheet']] <<- NULL
    for(n in names(docList)) docList[[n]] <<- NULL; projProperties[['activeDoc']] <<- NULL
  }

  for(n in names(allData$pp)){
    if(is.null(projProperties[[n]]) || projProperties[[n]] != allData$pp[[n]]){
      projProperties[[n]] <<- allData$pp[[n]]
    }
  }

  for(di in names(allData$dl)){
    if(is.null(datList[[di]])){ # new data
      datList[[di]] <<- DatClass$new('staticProperties'=allData$dl[[di]][['staticProperties']])
      datList[[di]][['dynamicProperties']] <<- reactiveValues()

    }
    for(n in names(allData$dl[[di]][['dynamicProperties']])){
      x <- allData$dl[[di]][['dynamicProperties']][[n]]
      if(n=='fieldsList'){
        if(is.null(datList[[di]][['dynamicProperties']][[n]])) datList[[di]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(datList[[di]][['dynamicProperties']][[n]][[n1]])) datList[[di]][['dynamicProperties']][[n]][[n1]] <<- reactiveValues()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              datList[[di]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
            }
          } else {
            datList[[di]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        datList[[di]][['dynamicProperties']][[n]] <<- x
      }
    }
    datList[[di]]$setDatDependencies()
  }

  for(si in names(allData$sl)){
    if(is.null(sheetList[[si]])){ # new sheet
      sheetList[[si]] <<- createNewSheetObj(withPlotLayer=FALSE)
      setSheetReactives(si)
    }
    for(n in names(allData$sl[[si]][['dynamicProperties']])){
      x <- allData$sl[[si]][['dynamicProperties']][[n]]
      if(n=='layerList'){
        if(is.null(sheetList[[si]][['dynamicProperties']][[n]])) sheetList[[si]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(sheetList[[si]][['dynamicProperties']][[n]][[n1]]))
              sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- createNewLayer()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              if(n2=='aesList'){
                names3 <- names(x[[n1]][[n2]])
                for(n3 in names3){
                  if(is.reactivevalues(x[[n1]][[n2]][[n3]])){
                    names4 <- names(x[[n1]][[n2]][[n3]])
                    for(n4 in names4){
                      if(typeof(x[[n1]][[n2]][[n3]][[n4]]) != 'closure')
                        sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]][[n4]] <<- x[[n1]][[n2]][[n3]][[n4]]
                    }
                    setAesReactives(si,n1,n3)
                  } else {
                    sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]] <<- x[[n1]][[n2]][[n3]]
                  }
                }
              } else {
                sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
              }
            }
          } else {
            sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        sheetList[[si]][['dynamicProperties']][[n]] <<- x
      }
    }
  }

  for(di in names(allData$docl)){
    if(is.null(docList[[di]])){ # new doc
      docList[[di]] <<- reactiveValues()

    }
    for(n in names(allData$docl[[di]])){
      x <- allData$docl[[di]][[n]]
      docList[[di]][[n]] <<- x
    }
  }

  ## update all UI
  sapply(unique(c(names(input), names(updateInput))), triggerUpdateInput)
  updateTabsetPanel(session, 'mainNavBar', selected='Visualize')
}

observe({
  inFile <- input[['loadProject']]
  isolate({
    if (!is.null(inFile)){
      loadProject(file=inFile$datapath, replaceOrMerge=input[['loadProjectAction']])
    }
  })

})

observe({
  v <- input$openSampleProj
  isolate({
    file <- paste('samples', input[['sampleProj']], sep='/')
    if(v && file.exists(file)){
      loadProject(file=file, 'replace')
    }
  })
})
#' Prepare the datapoll
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   if (!(NROW (H) %in% dim(HP)))
     stop ("The number of species in H and HP don't match")
   if (!(NROW (P) %in% dim(HP)))
     stop ("The number of species in P and HP don't match")
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}
#' Prepare the datapoll
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}


####################################################
## Project saving and loading
####################################################
output$downloadProject <- downloadHandler(
  filename = function() { 'MyProject.sData' },
  content = function(file) {
    isolate({
      for(di in names(datList)){
        datList[[di]]$removeDatDependencies()
      }
      allData <- list(pp=reactiveValuesToList(projProperties),
                      dl=datList,
                      sl=sheetList,
                      docl=docList)
      save(allData, file=file)
      for(di in names(datList)){
        datList[[di]]$setDatDependencies()
      }
    })
  }
)


loadProject <- function(file, replaceOrMerge='replace'){
  load(file)

  if(replaceOrMerge=='replace'){
    for(n in names(datList)) datList[[n]] <<- NULL; projProperties[['activeDat']] <<- NULL
    for(n in names(sheetList)) sheetList[[n]] <<- NULL; projProperties[['activeSheet']] <<- NULL
    for(n in names(docList)) docList[[n]] <<- NULL; projProperties[['activeDoc']] <<- NULL
  }

  for(n in names(allData$pp)){
    if(is.null(projProperties[[n]]) || projProperties[[n]] != allData$pp[[n]]){
      projProperties[[n]] <<- allData$pp[[n]]
    }
  }

  for(di in names(allData$dl)){
    if(is.null(datList[[di]])){ # new data
      datList[[di]] <<- DatClass$new('staticProperties'=allData$dl[[di]][['staticProperties']])
      datList[[di]][['dynamicProperties']] <<- reactiveValues()

    }
    for(n in names(allData$dl[[di]][['dynamicProperties']])){
      x <- allData$dl[[di]][['dynamicProperties']][[n]]
      if(n=='fieldsList'){
        if(is.null(datList[[di]][['dynamicProperties']][[n]])) datList[[di]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(datList[[di]][['dynamicProperties']][[n]][[n1]])) datList[[di]][['dynamicProperties']][[n]][[n1]] <<- reactiveValues()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              datList[[di]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
            }
          } else {
            datList[[di]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        datList[[di]][['dynamicProperties']][[n]] <<- x
      }
    }
    datList[[di]]$setDatDependencies()
  }

  for(si in names(allData$sl)){
    if(is.null(sheetList[[si]])){ # new sheet
      sheetList[[si]] <<- createNewSheetObj(withPlotLayer=FALSE)
    }
    for(n in names(allData$sl[[si]][['dynamicProperties']])){
      x <- allData$sl[[si]][['dynamicProperties']][[n]]
      if(n=='layerList'){
        if(is.null(sheetList[[si]][['dynamicProperties']][[n]])) sheetList[[si]][['dynamicProperties']][[n]] <<- list()
        names1 <- names(x)
        for(n1 in names1){
          if(is.reactivevalues(x[[n1]])){
            if(is.null(sheetList[[si]][['dynamicProperties']][[n]][[n1]]))
              sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- createNewLayer()
            names2 <- names(x[[n1]])
            for(n2 in names2){
              if(n2=='aesList'){
                names3 <- names(x[[n1]][[n2]])
                for(n3 in names3){
                  if(is.reactivevalues(x[[n1]][[n2]][[n3]])){
                    names4 <- names(x[[n1]][[n2]][[n3]])
                    for(n4 in names4){
                      if(typeof(x[[n1]][[n2]][[n3]][[n4]]) != 'closure')
                        sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]][[n4]] <<- x[[n1]][[n2]][[n3]][[n4]]
                    }
                    setAesReactives(si,n1,n3)
                  } else {
                    sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]][[n3]] <<- x[[n1]][[n2]][[n3]]
                  }
                }
              } else {
                sheetList[[si]][['dynamicProperties']][[n]][[n1]][[n2]] <<- x[[n1]][[n2]]
              }
            }
          } else {
            sheetList[[si]][['dynamicProperties']][[n]][[n1]] <<- x[[n1]]
          }
        }
      } else {
        sheetList[[si]][['dynamicProperties']][[n]] <<- x
      }
    }
  }
  setSheetReactives()

  for(di in names(allData$docl)){
    if(is.null(docList[[di]])){ # new doc
      docList[[di]] <<- reactiveValues()

    }
    for(n in names(allData$docl[[di]])){
      x <- allData$docl[[di]][[n]]
      docList[[di]][[n]] <<- x
    }
  }

  ## update all UI
  sapply(names(updateInput), triggerUpdateInput)
  updateTabsetPanel(session, 'mainNavBar', selected='Visualize')
}

observe({
  inFile <- input[['loadProject']]
  isolate({
    if (!is.null(inFile)){
      loadProject(file=inFile$datapath, replaceOrMerge=input[['loadProjectAction']])
    }
  })

})

observe({
  v <- input$openSampleProj
  isolate({
    file <- paste('samples', input[['sampleProj']], sep='/')
    if(v && file.exists(file)){
      loadProject(file=file, 'replace')
    }
  })
})

source('helpers.r', local=TRUE)

shinyServer(function(input, output, session) {

  sessionEnv <- environment()
  projProperties <- reactiveValues('activeDat'='')
  sessionProperties <- reactiveValues()
  updateInput <- reactiveValues('activeDat'=0,'datName'=0,'activeField'=0,'fieldName'=0,'measures'=0,
                                'activeSheet'=0,'sheetName'=0,'sheetDatId'=0,'combineMeasures'=0,
                                'sheetColumns'=0,'sheetRows'=0,'sheetOutput'=0,'sheetPlotLayer'=0,
                                'sheetLayerAes'=0,'aesField'=0,'aesAggregate'=0,'aesAggFun'=0,'aesDiscrete'=0,
                                'layerGeom'=0,'layerStatType'=0,'layerYFun'=0,
                                'layerPositionType'=0, 'layerPositionWidth'=0, 'layerPositionHeight'=0,
                                'activeDoc'=0,'docName'=0,'docRmd'=0,'rmdOuputFormat'=0,
                                'customizeItem'=0, 'plotXlab'=0, 'plotYlab'=0, 'plotTitle'=0,
                                'textFamily'=0, 'textFace'=0, 'textColor'=0,'textSize'=0, 'textHjust'=0, 'textVjust'=0,
                                'textAngle'=0, 'textLineheight'=0)

  #                                 'layerX'=0,'layerY'=0,
  #                                 'layerColor'=0,'layerFill'=0,'layerSize'=0,'layerAlpha'=0,'layerLabel'=0,
  #                                 'layerLineType'=0)

  triggerUpdateInput <- function(inputId){
    updateInput[[inputId]] <<- updateInput[[inputId]] + 1
  }

  datList <- list()
  makeReactiveBinding('datList')
  datListNames <- reactive({
    if(length(datList)){
      x <- names(datList)
      names(x) <- sapply(datList, function(y) y[['dynamicProperties']][['name']])
      x
    } else c('')
  })

  docList <- list()
  makeReactiveBinding('docList')
  docListNames <- reactive({
    if(length(docList)){
      x <- names(docList)
      names(x) <- sapply(docList, function(y) y[['name']])
      x
    } else c('')
  })
  addDoc <- function(){
    newDoc <- paste("Doc_",newGuid(),sep="")
    existingNames <- names(docListNames())
    ## make sure the new name is different
    newName <- make.unique(c(existingNames, 'Doc'), sep='_')[length(existingNames)+1]

    docObj <- reactiveValues('name'=newName, 'rmdOuputFormat'='pdf_document')
    docList[[newDoc]] <<- docObj
    projProperties[['activeDoc']] <- newDoc
  }
  isolate(addDoc())



  sheetList <- list()
  makeReactiveBinding('sheetList')

  sheetListNames <- reactive({
    if(length(sheetList)){
      x <- names(sheetList)
      names(x) <- sapply(sheetList, function(y) y[['dynamicProperties']][['name']])
      x
    } else c('')
  })
  setAesReactives <- function(currentSheet, currentLayer, currentAes){
      sheetList[[currentSheet]][['dynamicProperties'
                                 ]][['layerList']][[currentLayer]][['aesList']][[currentAes]][['canFieldBeContinuous']] <<- reactive({
                                   aes <- sheetList[[currentSheet]][['dynamicProperties'
                                                                     ]][['layerList']][[currentLayer]][['aesList']][[currentAes]]
                                   measures <- sheetList[[currentSheet]][['measuresR']]()
                                   field <- aes[['aesField']]
                                   if(isEmpty(field)){
                                     field <- sheetList[[currentSheet]][['dynamicProperties'
                                               ]][['layerList']][['Plot']][['aesList']][[currentAes]][['aesField']]
                                   }
                                   aes[['aesAggregate']] || (!isEmpty(field) && field %in% measures)
                                 })
  }
  addSheet <- function(){
    newSheet <- paste("Sheet_",newGuid(),sep="")
    existingNames <- names(sheetListNames())
    ## make sure the new name is different
    newName <- make.unique(c(existingNames, 'Sheet'), sep='_')[length(existingNames)+1]

    sheetObj <- createNewSheetObj(newName)
    sheetList[[newSheet]] <<- sheetObj
    projProperties[['activeSheet']] <- newSheet

    for(currentLayer in names(sheetObj[['dynamicProperties']][['layerList']])){
      for(currentAes in names(sheetObj[['dynamicProperties']][['layerList']][[currentLayer]][['aesList']])){
        setAesReactives(newSheet, currentLayer, currentAes)
      }
    }
  }
  isolate(addSheet())



  ## create sheet reactives and defaults
  setSheetReactives <- function(){#browser()
    for(currentSheet1 in names(sheetList)){
      isolate(local({
        currentSheet <- currentSheet1

        if(isFieldUninitialized(sheetList[[currentSheet]],'layerNames')){
          sheetList[[currentSheet]][['layerNames']] <<- reactive({
            sl <- isolate(sheetList)
            if(!isEmpty(sl[[currentSheet]][['dynamicProperties']][['layerList']])){
              names(sl[[currentSheet]][['dynamicProperties']][['layerList']])
            } else c()
          })
        }


        if(isFieldUninitialized(sheetList[[currentSheet]],'fieldNames')){
          sheetList[[currentSheet]][['fieldNames']] <<- reactive({
            sl <- isolate(sheetList)
            dl <- isolate(datList)
            currentDat <- sl[[currentSheet]][['dynamicProperties']][['datId']]
            combineMeasures <- sl[[currentSheet]][['dynamicProperties']][['combineMeasures']]

            if(!isEmpty(currentDat)){
              currentDatObj <- dl[[currentDat]]
              if(combineMeasures) currentDatObj[['moltenNames']]() else currentDatObj[['fieldNames']]()
            }
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'measuresR')){
          sheetList[[currentSheet]][['measuresR']] <<- reactive({
            sl <- isolate(sheetList)
            dl <- isolate(datList)
            currentDat <- sl[[currentSheet]][['dynamicProperties']][['datId']]
            combineMeasures <- sl[[currentSheet]][['dynamicProperties']][['combineMeasures']]

            if(!isEmpty(currentDat)){
              currentDatObj <- dl[[currentDat]]
              if(combineMeasures) c(MoltenMeasuresName) else currentDatObj[['dynamicProperties']][['measures']]
            }
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'datR')){
          sheetList[[currentSheet]][['datR']] <<- reactive({
            sl <- isolate(sheetList)
            dl <- isolate(datList)
            currentDat <- sl[[currentSheet]][['dynamicProperties']][['datId']]
            combineMeasures <- sl[[currentSheet]][['dynamicProperties']][['combineMeasures']]

            if(!isEmpty(currentDat)){
              currentDatObj <- dl[[currentDat]]
              if(combineMeasures) currentDatObj[['moltenDat']]() else currentDatObj[['datR']]()
            }
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'tableR')){
          sheetList[[currentSheet]][['tableR']] <<- reactive({
            sl <- isolate(sheetList)
            tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
                       (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )
          })
        }



        if(isFieldUninitialized(sheetList[[currentSheet]],'plotCore')){
          ## Helpful ggplot references:
          ## http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/
          ## http://www.ling.upenn.edu/~joseff/rstudy/summer2010_ggplot2_intro.html
          ## http://learnr.wordpress.com/2009/03/17/ggplot2-barplots/
          ## http://sape.inf.usi.ch/quick-reference/ggplot2
          ## http://ggplot2.org/book/

          ## http://stackoverflow.com/questions/20249653/insert-layer-underneath-existing-layers-in-ggplot2-object

          ## current solutions:
          ## http://blog.ouseful.info/2011/08/03/working-visually-with-the-ggplot2-web-interface/  (no support for saving project)
          ## Deducer


          sheetList[[currentSheet]][['plotCore']] <<- reactive({
            sl <- isolate(sheetList)
            layerList <- sl[[currentSheet]][['dynamicProperties']][['layerList']]
            cc <- empty2NULL(sl[[currentSheet]][['dynamicProperties']][['columns']])
            rr <- empty2NULL(sl[[currentSheet]][['dynamicProperties']][['rows']])
            datSheet <- sl[[currentSheet]][['datR']]()
            validate(need(!isEmpty(datSheet), label='Data'))

            gg <- NULL
            for(i in c('bar','line','point')) update_geom_defaults(i, list(colour = "darkblue", fill = "darkblue"))

            aes.base <- layerList[['Plot']][['aesList']]
            for(currentLayer in names(layerList)){
              layer.current <- layerList[[currentLayer]]

              stat <- empty2NULL(layer.current[['statType']])
              geom <- empty2NULL(layer.current[['geom']])
              fun.y <- empty2NULL(layer.current[['yFun']])
              position <- empty2NULL(layer.current[['layerPositionType']])
              pWidth <- empty2NULL(layer.current[['layerPositionWidth']])
              pHeight <- empty2NULL(layer.current[['layerPositionHeight']])

              if(!is.null(geom) && !is.null(stat) && !is.null(position)){
                ## get effective aesthetics taking into account of inheritance
                aes.current <- layer.current[['aesList']][isolate(unlist(layer.current[['aesChoices']], use.names=FALSE))]
                aes.current <- sapply(names(aes.current), function(n){
                  temp <- reactiveValuesToList(aes.current[[n]]) # converting to list so we can modify it
                  if(are.vectors.different(temp[['aesMapOrSet']],'set')){
                    temp[['aesField']] <- ifempty(temp[['aesField']], empty2NULL(aes.base[[n]][['aesField']]))
                    if(!is.null(temp[['aesField']])){
                      if(temp[['aesAggregate']]){
                        temp[['aesFieldOriginal']] <- temp[['aesField']]
                        temp[['aesField']] <- paste(temp[['aesFieldOriginal']], temp[['aesAggFun']], sep='_')
                      }
                    }
                  }
                  temp
                }, simplify=FALSE)
                aes.current <- aes.current[sapply(aes.current,
                     function(x) {
                       isSetting <- !are.vectors.different(x[['aesMapOrSet']],'set')
                       (isSetting && !isEmpty(x[['aesValue']])) || (!isSetting && !isEmpty(x[['aesField']]))
                     })]

                borderColor <- aes.current[['aesBorderColor']]
                aes.current[['aesBorderColor']] <- NULL
                if(geom %in% c('bar','area','boxplot')){
                  aes.current[['aesFill']] <- aes.current[['aesColor']]
                  aes.current[['aesColor']] <- borderColor
                }

                ## aesthetics validation
                validate(
                  need(!is.null(aes.current[['aesX']]), label='X')
                )
                if(stat=='identity'){
                  validate(
                    need(!is.null(aes.current[['aesY']]), label='Y')
                  )
                }
                if(geom=='text'){
                  validate(
                    need(!is.null(aes.current[['aesLabel']]), label='Label')
                  )
                }
                if(geom=='boxplot' && stat=='identity'){
                  validate(
                    need(!is.null(aes.current[['aesYmin']]), label='Y Min')
                  )
                  validate(
                    need(!is.null(aes.current[['aesYmax']]), label='Y Max')
                  )
                  validate(
                    need(!is.null(aes.current[['aesLower']]), label='Y Lower')
                  )
                  validate(
                    need(!is.null(aes.current[['aesMiddle']]), label='Y Middle')
                  )
                  validate(
                    need(!is.null(aes.current[['aesUpper']]), label='Y Upper')
                  )
                }
                if(position=='fill'){
                  validate(
                    need(!is.null(aes.current[['aesYmax']]), label='Y Max')
                  )
                }

                i.map <- sapply(aes.current, function(x) are.vectors.different(x[['aesMapOrSet']],'set'))
                aes.map <- aes.current[i.map]
                aes.set <- aes.current[!i.map]

                ## aggregate data for layer
                datLayer <- datSheet
                aes.toAgg <- aes.map[sapply(aes.map, function(x) x[['aesAggregate']])]
                if(length(aes.toAgg)){
                  # get rid of duplicates to avoid aggregating the same field the same way twice
                  dups <- duplicated(sapply(aes.toAgg, function(x) x[['aesField']]))
                  aes.toAgg <- aes.toAgg[!dups]

                  # some validation
                  agg.fields <- sapply(aes.toAgg, function(x) x[['aesFieldOriginal']])
                  overlaps <- intersect(agg.fields, c(rr,cc))
                  validate(need(isEmpty(overlaps), 'Can not aggregate fields used in faceting.'))

                  # build the j-expression from string; there may be a better way
                  agg.str <- sapply(aes.toAgg, function(x) paste(x[['aesAggFun']], '(', x[['aesFieldOriginal']], ')', sep=''))
                  agg.str <- paste(sapply(aes.toAgg, function(x) x[['aesField']]), agg.str, sep='=', collapse=', ')
                  agg.str <- paste0('list(', agg.str, ')')
                  agg.exp <- parse(text=agg.str)[[1]]
                  groupBy <- unique(c(rr,cc,sapply(aes.map[sapply(aes.map, function(x) !(x[['aesAggregate']]))],
                                                   function(x) x[['aesField']])))
                  datLayer <- eval(bquote(datSheet[, .(agg.exp), by=.(groupBy)]))

                  if(currentLayer=='Plot'){
                    ## add to dataList
                    outDf <- datLayer
                    isolate({
                      sheetNameDat <- convertSheetNameToDatName(sheetList[[currentSheet]][['dynamicProperties']][['name']])
                      if(is.null(datList[[currentSheet]])){
                        datList[[currentSheet]] <<- createNewDatClassObj(outDf, name=sheetNameDat, type='sheet')
                      } else {
                        datList[[currentSheet]][['dynamicProperties']][['dat']] <<- outDf
                        datList[[currentSheet]][['dynamicProperties']][['measures']] <<- intersect(datList[[currentSheet]][['dynamicProperties']][['measures']],
                                                                                                   getDefaultMeasures(outDf))
                        ## add new fields, delete outdated fields, leave common fields alone since they might have user customizations
                        newFields <- getDefaultFieldsList(outDf)
                        oldList <- names(datList[[currentSheet]][['dynamicProperties']][['fieldsList']])
                        newList <- names(newFields)
                        for(n in setdiff(newList, oldList)){
                          datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- newFields[[n]]
                        }
                        for(n in setdiff(oldList, newList)){
                          datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- NULL
                        }
                      }
                    })
                  }
                }


                ## get ready to ggplot
                if(stat=='summary'){ # need to re-point all the other aesthetics to ..y..
                  sapply(setdiff(names(aes.map), 'aesY'),
                         function(x){
                           if(aes.map[[x]][['aesField']]==aes.map[['aesY']][['aesField']]){
                             aes.map[[x]][['aesField']] <<- InternalY
                           }
                         })
                }


                ## list of set values
                aes.set.args <- list()
                if(length(aes.set)){
                  aes.set.args <- lapply(aes.set,
                                     function(x) {
                                       x[['aesValue']]
                                     }
                  )
                  names(aes.set.args) <- tolower(substring(names(aes.set), 4)) # get rid of the 'aes' prefix
                }

                aes.args <- lapply(aes.map,
                                   function(x) {
                                     if(x[['canFieldBeContinuous']]()){
                                       paste(ifelse(x[['aesDiscrete']], 'as.factor(', 'as.numeric('),
                                             x[['aesField']], ')', sep='')
                                     } else {
                                       x[['aesField']]
                                     }
                                   }
                                   )
                names(aes.args) <- tolower(substring(names(aes.map), 4)) # get rid of the 'aes' prefix

                aess <- do.call('aes_string', aes.args)
                position <- do.call(paste('position', position, sep='_'),
                                    list(width=pWidth, height=pHeight))
                #browser()
                if(is.null(gg)) gg <- ggplot()
                gg <- gg + do.call(paste('geom',geom,sep='_'),
                                   c(aes.set.args, list(mapping=aess, data=datLayer, stat=stat, fun.y=fun.y, position=position)))

              }
            }
            if(!is.null(gg)){
              if(!isEmpty(cc) || !isEmpty(rr)){
                gg <- gg + facet_grid(as.formula(paste(names2formula(rr), names2formula(cc), sep=" ~ ")))
              }
              gg <- gg + theme_bw()
            }
            gg
          })
        }

        if(isFieldUninitialized(sheetList[[currentSheet]],'plotR')){
          sheetList[[currentSheet]][['plotR']] <<- reactive({
            sl <- isolate(sheetList)
            layerList <- sl[[currentSheet]][['dynamicProperties']][['layerList']]
            aes.base <- layerList[['Plot']][['aesList']]

            fieldNames <- sl[[currentSheet]][['fieldNames']]()

            gg <- sl[[currentSheet]][['plotCore']]()
            if(!is.null(gg)){
              themeElementCalls <-
                sapply(sheetList[[currentSheet]][['dynamicProperties']][['formatting']],
                       simplify = FALSE, USE.NAMES = TRUE,
                       function(cus){
                         eleBlank <- attr(cus, 'elementBlank')
                         if(!is.null(eleBlank) && eleBlank) return(element_blank())
                         if(!isEmpty(cus)){
                           cus1 <- cus[!sapply(cus, isEmpty)]
                           names(cus1) <- tolower(substring(names(cus1), 5)) # get rid of the 4-char prefix like 'text', 'rect', etc.
                           switch(attr(cus, 'type'),
                                  'unit'=if(!isEmpty(cus1$x) && !isEmpty(cus1$units)) do.call('unit', cus1),
                                  'character'=if(!isEmpty(cus1$mainvalue)){
                                    if(cus1$mainvalue!='custom_'){
                                      cus1$mainvalue
                                    } else {
                                      c(cus1$altvalue1, cus1$altvalue2)
                                    }
                                  },
                                  do.call(attr(cus, 'type'), cus1))
                         }
                       })
              themeElementCalls <- themeElementCalls[!sapply(themeElementCalls, is.null)]


              gg <- gg + xlab(sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']]) +
                ylab(sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']]) +
                ggtitle(sheetList[[currentSheet]][['dynamicProperties']][['plotTitle']])
              if(length(themeElementCalls)){
                gg <- gg + do.call('theme', themeElementCalls)
              }

            }
            gg
          })
        }

      }))
    }
  }

  observe({
    setSheetReactives()
  }, priority=10)



  isDatBasedonSheet <- function(datId, sheetId){
    if(!is.null(datList[[datId]])){
      while(datList[[datId]][['staticProperties']][['type']] == 'sheet'){
        if(datId==sheetId) return(TRUE)
        datId <- sheetList[[datId]][['dynamicProperties']][['datId']]
      }
    }
    FALSE
  }





  source('data.r', local=TRUE)
  source('sheets.r', local=TRUE)
  source('sheetsCustomize.r', local=TRUE)
  source('project.r', local=TRUE)
  source('docs.r', local=TRUE)

  observe({
    v <- input$importFonts
    isolate({
      if(!is.null(v) && v==1){  # so it's executed the first time the button is clicked
        if(!require(extrafont)) install.packages('extrafont')
        extrafont::font_import(prompt=FALSE) # this only needs run once but takes a long time
        # todo: alert user
      }
    })
  })

})


####by Heather E. Wheeler 20140602####
"%&%" = function(a,b) paste(a,b,sep="")
args <- commandArgs(trailingOnly=T)
date <- Sys.Date() 
###############################################
### Directories & Variables
 
cri = F #on cri cluster?
if(cri) precri = "/group/im-lab/" else precri = '/'

my.dir <- precri %&% "nas40t2/hwheeler/PrediXcan_CV/GTEx_2014-06013_release/"
 
#tissue <- "Nerve - Tibial" ###check GTEx_Analysis_2014-06-13.SampleTissue.annot for available tissues###
tissue <- "Adipose - Subcutaneous"
tis <- "GTEx-AdS"
Nk <- 15 ##number of peer factors to calculate, recommend 25% of sample size, but no more than 100, GTEx included 15 in pilot analyses
 
################################################
### Functions & Libraries
 
library(SNPRelate)
library(peer)
library(preprocessCore)
#library(GenABEL)
##if can't install GenABEL
source(my.dir %&% 'GenABEL/R/ztransform.R')
source(my.dir %&% 'GenABEL/R/rntransform.R')
 
################################################
sam <- read.table(my.dir %&% "GTEx_Analysis_2014-06-13.SampleTissue.annot",header=T,sep="\t") 
### above file includes SAMPID and SMTSD from: 
### /group/im-lab/nas40t2/haky/Data/dbGaP/GTEx/41400/gtex/exchange/GTEx_phs000424/exchange/analysis_releases/GTEx_Analysis_2014-06-13/sample_annotations/GTEx_Data_2014-06-13_Annotations_SampleAttributesDS.txt
sample <- subset(sam,SMTSD == tissue) ### pull sample list of chosen tissue###
 
expidlist <- scan("GTEx_Analysis_2014-06-13.RNA-seq.ID.list","character")
expgenelist <- scan("GTEx_Analysis_2014-06-13.RNA-seq.GENE.list","character")
exp <- scan("GTEx_Analysis_2014-06-13.RNA-seq.GENExID")
expdata <- matrix(exp, ncol=length(expidlist), byrow=T)
t.expdata <- t(expdata)
rownames(t.expdata) <- expidlist
colnames(t.expdata) <- expgenelist

gencodefile <- my.dir %&% "gencode.v18.genes.patched_contigs.summary.protein"
gencode <- read.table(gencodefile) ##split into 10 files, call each from run_1_CV_GTEx_polyscore_PrediXcan_subset*.sh
rownames(gencode) <- gencode[,5]
t.expdata <- t.expdata[,intersect(colnames(t.expdata),rownames(gencode))] ###pull protein coding gene expression data

tissue.exp <- t.expdata[intersect(rownames(t.expdata),sample$SAMPID),] ###pull expression data for chosen tissue###
expsamplelist <- rownames(tissue.exp) ###samples with exp data###
substr.expsamplelist <- substr(expsamplelist,1,10) ###to match with genotype data###
 
famfile <- my.dir %&% "GTEx_Analysis_2014-06-13_OMNI_2.5M_5M_451Indiv_Pheno_2for5M_1for2.5M.fam"
fam <- read.table(famfile)
gtsamplelist <- fam$V1
substr.gtsamplelist <- substr(gtsamplelist,1,10) ###to match with exp data###
rownames(fam) <- substr.gtsamplelist
samplelist <- intersect(substr.gtsamplelist,substr.expsamplelist)
nsample <- length(samplelist)
tissue.exp.substr <- tissue.exp
for(id in samplelist){  ####take mean of exp for samples with >1 RNA Seq dataset
        matchexp <- tissue.exp.substr[substr(rownames(tissue.exp.substr),1,10)==id,]
        if(is.array(matchexp)=='TRUE'){
                expmean <- colMeans(matchexp)
                for(i in rownames(matchexp)){
                        tissue.exp.substr[i,] <- expmean
                }
        }
}


rownames(tissue.exp.substr) <- substr.expsamplelist ###change rownames of tissue.exp to match with genotypes###
exp.w.geno <- tissue.exp.substr[samplelist,] ###get expression of samples with genotypes###
explist <- subset(colMeans(exp.w.geno), colMeans(exp.w.geno)>0) ###pull genes with mean expression > 0###
explist <- names(explist)
exp.w.geno <- exp.w.geno[,explist]
 

###get first 3 PCs from genos, as in GTEx
pc.matrix<-read.table(my.dir %&% "GTEx_Analysis_2014-06-13_OMNI_2.5M_5M_451Indiv_PostImput_20genotPCs.txt",header=T)
pcs3 <- pc.matrix[,3:5]
pclist <- substr(pc.matrix[,1],1,10)
rownames(pcs3) <- pclist
pcs <- as.matrix(pcs3[samplelist,])

###pull gender, used as cov in GTEx
famsubset <- fam[samplelist,]
gender <- famsubset$V5
names(gender)<-rownames(famsubset)

###quantile normalize and transform to standard normal exp.w.geno matrix, as in GTEx###
t.exp.w.geno <- t(exp.w.geno)

rowtable<-function(x) length(table(x))>2 ##function to determine if more than 2 exp levels per gene
nonbin<-apply(t.exp.w.geno,1,rowtable) ##apply to matrix
t.exp.w.geno <- t.exp.w.geno[nonbin,] ##remove binary genes from matrix

qn.t.exp.w.geno <- normalize.quantiles(t.exp.w.geno) ##quantile normalize
rn.qn.t.exp.w.geno <- apply(qn.t.exp.w.geno,1,"rntransform") ##rank transform to normality & transposes, not sure why?##

###Now we can create the model object, ### from https://github.com/PMBio/peer/wiki/Tutorial

model = PEER()

###set the observed data,

PEER_setPhenoMean(model,as.matrix(rn.qn.t.exp.w.geno))

dim(PEER_getPhenoMean(model))

###(NULL response means no error here), say we want to infer K=20 hidden confounders,

PEER_setNk(model,Nk)

PEER_getNk(model)

####and perform the inference. ###for Nk=20 and GTEx-NT, it took 323 iterations, for Nk=15 and GTEx-NT, it took 37 iterations

PEER_update(model)

factors = PEER_getX(model)
rownames(factors) <- rownames(exp.w.geno)
write.table(factors,file <- tis %&% "." %&% Nk %&% ".PEER.factors." %&% date %&% ".txt", quote=F)
weights = PEER_getW(model)
precision = PEER_getAlpha(model)
residuals = PEER_getResiduals(model)

png(file= tis %&% "." %&% Nk %&% ".PEER.factors.plotmodel." %&% date %&% ".png")
PEER_plotModel(model)
dev.off()

adj.exp.matrix<-matrix(NA,nrow=dim(rn.qn.t.exp.w.geno)[1],ncol=dim(rn.qn.t.exp.w.geno)[2])

for(i in 1:dim(rn.qn.t.exp.w.geno)[2]){
	res <- summary(lm(rn.qn.t.exp.w.geno[,i] ~ factors + pcs + gender, na.action=na.exclude))
	resid <- residuals(res)
	adj.exp.matrix[,i] <- resid
}

colnames(adj.exp.matrix) <- rownames(t.exp.w.geno)
rownames(adj.exp.matrix) <- colnames(t.exp.w.geno)

write.table(adj.exp.matrix, file= tis %&% ".exp.adj." %&% Nk %&% "PEERfactors.3PCs.gender.IDxGENE", quote=F, row.names=F, col.names=F)
write(colnames(adj.exp.matrix), file = tis %&% ".exp.adj." %&% Nk %&% "PEERfactors.3PCs.gender.GENE.list", ncolumns=1)
write(rownames(adj.exp.matrix), file = tis %&% ".exp.adj." %&% Nk %&% "PEERfactors.3PCs.gender.ID.list", ncolumns=1)
#' @title Pobieranie danych o szkołach.
#' @description
#' Funkcja pobiera z bazy dane o szkołach - o ich typie i specyfice, nazwie, adresowe
#' i o lokalizacji.
#' @param lata wektor liczb całkowitych - lata, których mają dotyczyć dane (dla każdej
#' szkoły zwrócone zostaną tylko najświeższe dane w ramach tego okresu)
#' @param typySzkol opcjonalny wektor tekstowy z typami szkół, które mają zostać zwrócone
#' (lub NULL - zwraca informacje o wszystkich szkołach)
#' @param idOke wartość logiczna (domyślnie FALSE) - czy dołączać kody OKE szkół?
#' @param daneAdresowe wartość logiczna (domyślnie FALSE) - czy dołączać nazwę i dane
#' adresowe?
#' @return data frame
#' @import dplyr
#' @import ZPD
#' @export
pobierz_dane_szkol = function(lata, typySzkol = NULL, idOke = FALSE,
                              daneAdresowe = FALSE) {
  stopifnot(is.numeric(lata)        , length(lata) > 0,
            is.character(typySzkol) | is.null(typySzkol),
            is.logical(idOke)       , length(idOke) == 1,
            is.logical(daneAdresowe), length(daneAdresowe) == 1
  )
  stopifnot(idOke %in% c(TRUE, FALSE),
            daneAdresowe %in% c(TRUE, FALSE))

  if (length(typySzkol) == 1) typySzkol = rep(typySzkol, 2)  # brzydkie, ale za to 4 wiersze dalej zadziała
  szkoly = pobierz_szkoly(polacz())
  szkoly = filter_(szkoly, ~ rok %in% lata)
  szkoly = select_(szkoly, ~ -wojewodztwo, ~ -powiat, ~ -gmina)
  if (!is.null(typySzkol)) szkoly = filter_(szkoly, ~ typ_szkoly %in% typySzkol)
  if (!idOke) szkoly = select_(szkoly, ~ -id_szkoly_oke)
  if (!daneAdresowe) szkoly = select_(szkoly, ~ -nazwa_szkoly, ~ -adres, ~ -miejscowosc,
                                      ~ -pna, ~ -poczta, ~ -wielkosc_miejscowosci,
                                      ~ -teryt_szkoly, ~ -rodzaj_gminy)
  szkoly = collect(szkoly)
  szkoly = group_by_(szkoly, ~ rok)
  szkoly = mutate_(szkoly, .dots=list(max_rok = "max(rok)"))
  szkoly = filter_(szkoly, ~ rok == max_rok)
  szkoly = select_(szkoly, ~ -max_rok)
  szkoly = as.data.frame(szkoly)

  typyWWynikach = typySzkol %in% szkoly$typ_szkoly
  if (any(!typyWWynikach)) warning("Nie znaleziono żadnych szkół typu/ów: ",
                                   paste0(typySzkol[!typyWWynikach], collapse=", "), ".")

  for (i in names(szkoly)[unlist(lapply(szkoly, is.character))]) {
    Encoding(szkoly[, i]) = "UTF-8"
  }
  attributes(szkoly)$lata = lata
  return(szkoly)
}
library = function (...)
    suppressMessages(base::library(..., warn.conflicts = FALSE, quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

melt = function (...) {
    args = list(...)
    result = reshape2::melt(...)
    varnames = if ('varnames' %in% names(args))
        args$varnames
    else if ('variable.name' %in% names(args))
        args$variable.name
    else
        'variable'

    result[, varnames] = sapply(result[, varnames], as.character)
    result
}
assign('melt', melt, globalenv())

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
#!/usr/bin/Rscript

library(fields)
library(GGally)
library(ggplot2)
library(igraph)
library(mapproj)
library(maps)
library(pander)
library(plyr)
library(RColorBrewer)
library(reshape2)
library(scales)
library(vegan)
source('custom-plot-functions.r')

Sys.setlocale("LC_TIME", "C") #Needed for identical()
Sys.setlocale("LC_COLLATE", "C")

## Get case data

dataDir <- '.'

tmpf <- function(){
  fn <- file.path(dataDir, 'PEDvweeklyreport-state-ts-01-08-14.csv')
  ret <- read.csv(fn)
  ret[1:9, c('CA', 'MD', 'NE', 'WY')] <- 0
  key <- order(colnames(ret)[-c(1:2)])
  ret <- cbind(ret[, c(1:2)], ret[, -c(1:2)][, key])
  ret$Unk <- NULL
  target <- structure(list(week = structure(c(20L, 29L, 32L, 8L, 12L),
.Label = c("10/13/2013", "10/20/2013", "10/27/2013", "10/6/2013",
"11/10/2013", "11/17/2013", "11/24/2013", "11/3/2013", "12/1/2013",
"12/15/2013", "12/22/2013", "12/29/2013", "12/8/2013", "4/15/2013",
"4/22/2013", "4/29/2013", "5/13/2013", "5/20/2013", "5/27/2013",
"5/6/2013", "6/10/2013", "6/16/2013", "6/23/2013", "6/3/2013",
"6/30/2013", "7/14/2013", "7/21/2013", "7/28/2013", "7/7/2013",
"8/11/2013", "8/18/2013", "8/25/2013", "8/4/2013", "9/1/2013",
"9/15/2013", "9/22/2013", "9/29/2013", "9/8/2013"), class = "factor"),
totalNumberSwineAccessions = c(17L, 34L, 26L, 90L, 134L), CA = c(0, 0,
0, 0, 1), CO = c(1L, 1L, 0L, 0L, 0L), IA = c(8L, 6L, 2L, 38L, 54L), IL
= c(0L, 1L, 0L, 1L, 14L), IN = c(3L, 2L, 1L, 1L, 3L), KS = c(0L, 4L,
3L, 6L, 4L), KY = c(0L, 0L, 0L, 0L, 0L), MD = c(0, 0, 0, 0, 0), MI =
c(0L, 0L, 0L, 2L, 0L), MN = c(1L, 2L, 2L, 7L, 20L), MO = c(0L, 0L, 0L,
2L, 4L), NC = c(0L, 3L, 4L, 14L, 18L), NE = c(0, 0, 0, 0, 2), NY =
c(0L, 0L, 0L, 0L, 0L), OH = c(0L, 2L, 1L, 5L, 5L), OK = c(0L, 11L,
10L, 10L, 2L), PA = c(1L, 0L, 3L, 1L, 0L), SD = c(0L, 0L, 0L, 0L, 3L),
TN = c(0L, 0L, 0L, 1L, 1L), TX = c(0L, 0L, 0L, 1L, 1L), WI = c(0L, 0L,
0L, 1L, 0L ), WY = c(0, 0, 0, 0, 1)), .Names = c("week",
"totalNumberSwineAccessions", "CA", "CO", "IA", "IL", "IN", "KS",
"KY", "MD", "MI", "MN", "MO", "NC", "NE", "NY", "OH", "OK", "PA",
"SD", "TN", "TX", "WI", "WY" ), row.names = c(4L, 13L, 20L, 30L, 38L),
class = "data.frame")
  stopifnot(identical(target, ret[c(4,13,20,30,38),]))
  ret
}
caseData <- tmpf()

unwanted <- c('week', 'totalNumberSwineAccessions', 'Unk')
ind <- which(!colnames(caseData) %in% unwanted)
observed <- caseData[, ind]

## Get cross correlations

n <- ncol(observed)
CC <- matrix(nrow=n, ncol=n)

getcc <- function(x,y, lag=1){
    foo <- ccf(x, y, plot=FALSE)
    ind <- which(foo$lag == lag)
    foo$acf[ind]
}

for(i in seq_len(n)){
    for(j in seq_len(n)){
        ## CC[i,j] will be high if deviations from the mean in series i
        ## are shifted to the left of similar deviations to the mean in series j
        ## i.e. i's deviations are indicative of j's future deviations
        CC[i,j] <- getcc(observed[,j], observed[,i])
    }
}

colnames(CC) <- rownames(CC) <- colnames(observed)

check_cc_directionality <- function(){
    t <- 1:100 * .25
    x <- sin(t)
    ## y is shifted to the right
    y <- sin(t-1)

    xylag1 <- getcc(x, y)
    yxlag1 <- getcc(y,x)
    main <- paste('getcc(x, y) ==', round(xylag1,2),
                  '; getcc(y,x) == ', round(yxlag1,2))
    if(xylag1 > yxlag1){
        conc <- 'left arg delayed by lag'
    } else{
        conc <- 'right arg delayed by lag'
    }
    plot(x~t, type='l', ylab='f(t)', main=main, sub=conc)
    lines(y~t, col=2)
    legend('topright', col=1:2, legend=c('x', 'y'), lty=1)
}

png('direction-check.png')
check_cc_directionality()
dev.off()

## Get shared-border neighborhoods

nbEdgelist <- read.csv(file.path(dataDir, 'state_neighbors_fips.txt'), header=FALSE)
data(state.fips)
g <- graph.data.frame(nbEdgelist, directed=FALSE)
g <- simplify(g)
key <- match(V(g)$name, state.fips$fips)
abb <- state.fips$abb[key]
V(g)$name <- as.character(abb)
vids <- which(V(g)$name %in% colnames(caseData))
g2 <- induced.subgraph(g, vids)
nms <- colnames(observed)
nhood <- as.matrix(g2[nms,nms])

## Get shipment flows

epO <- ep <- read.csv(file.path(dataDir, 'shipment-flows-origins-on-rows-dests-on-columns.csv'),row.names=1)
key <- match(colnames(observed), colnames(ep))
ep <- ep[key, key]
rownames(ep) <- colnames(ep)

### assertions based on inspection of original .xls file
stopifnot(ep['CA', 'IL'] == 9415)
stopifnot(ep['MI', 'KS'] == 6)
stopifnot(ep['IL', 'IA'] == 1424813)
stopifnot(ep['KY', 'IA'] == 17658)
stopifnot(ep['MO', 'IA'] == 2389932)
stopifnot(ep['OK', 'CA'] == 16762)
stopifnot(ep['MO', 'CA'] == 645)

epl <- log10(ep +1)
epl <- data.matrix(epl)
## We discard the within-state flows because they do not enter into
## the analysis. Thus it is mostly a matter of how the plots will
## look, and because the original spreadsheet had no data on
## within-state flows (they were added for some other analyses based
## on an assumption of 90% of total flow), there's no good reason to
## include them in the plot.
diag(epl) <- NA

key <- match(colnames(ep), colnames(CC))
CC <- CC[key,key]



## Get great circle distance

key <- match(colnames(CC), state.abb)

cx <- state.center$x[key]
cy <- state.center$y[key]

n <- ncol(CC)
centerDists <- matrix(nrow=n, ncol=n)

# Calculates the geodesic distance between two points specified by radian latitude/longitude using the
# Haversine formula (hf)
# source: http://www.r-bloggers.com/great-circle-distance-calculations-in-r/
gcd.hf <- function(long1, lat1, long2, lat2) {
      R <- 6371 # Earth mean radius [km]
        delta.long <- (long2 - long1)
        delta.lat <- (lat2 - lat1)
        a <- sin(delta.lat/2)^2 + cos(lat1) * cos(lat2) * sin(delta.long/2)^2
        c <- 2 * asin(min(1,sqrt(a)))
        d = R * c
        return(d) # Distance in km
  }

deg2rad <- function(deg) return(deg*pi/180)

getCenterDist <- function(state1,state2){
    long1 <- deg2rad(cx[state1])
    long2 <- deg2rad(cx[state2])
    lat1 <- deg2rad(cy[state1])
    lat2 <- deg2rad(cy[state2])
    gcd.hf(long1, lat1, long2, lat2)
}

for(i in seq_len(n)){
    for(j in seq_len(n)){
        centerDists[i,j] <- getCenterDist(i, j)
    }
}

colnames(centerDists) <- rownames(centerDists) <- colnames(CC)

## hypothesis tesing

getMat <- function(x) switch(x, 'shipment'=epl, 'cor'=CC,
                             'gcd'=-centerDists, 'sharedBord'=nhood)

doTest <- function(M1, M2, symmetrize=FALSE, ...){
    x <- getMat(M1)
    y <- getMat(M2)
    if(symmetrize){
        x <- (x + t(x))*0.5
        y <- (y + t(y))*0.5
    }
    mantel(x, y, ...)
}

mats <- c('shipment', 'cor', 'gcd', 'sharedBord')
methods <- c('spearman', 'pearson')
symmetrize <- c(TRUE, FALSE)
des <- expand.grid(M1=mats, M2=mats, method=methods, symmetrize=symmetrize, stringsAsFactors=FALSE)
des <- des[des$M1 != des$M2, ]
des$permutations <- 10000

res <- list()
for(i in seq_len(nrow(des))){
    print(i)
    res[[i]] <- do.call(doTest, as.list(des[i,]))
}

des$r <- sapply(res, '[[', 'statistic')
des$pValues <- sapply(res, '[[', 'signif')

sink('mantel-table.txt')
pander(des)
sink()

save.image(file='mantel-testing-checkpoint1.RData')

## plotting

### jflowmap
projection <- 'azequalarea'
orientation <- c(30.82,-98.57,0)
#scale of 1 does not allow good edge-bundling with this projection
scale <- 100

adjmatrix <- data.matrix(epO[state.abb, state.abb])
diag(adjmatrix) <- 0
g <- graph.adjacency(adjmatrix, mode='directed', weighted='flow')
stopifnot(colnames(adjmatrix) == V(g)$name)
V(g)$PEDVpositive <- V(g)$name %in% colnames(CC)
key <- match(V(g)$name, state.abb)
proj <- mapproject(x=state.center$x[key], y=state.center$y[key],
                   projection=projection, orientation=orientation)
V(g)$x <- proj$x*scale
V(g)$y <- proj$y*scale
adjmatrix <- getMat('cor')
diag(adjmatrix) <- 0
g2 <- graph.adjacency(adjmatrix, mode='directed', weighted='crossCorrelation')
E(g2)$ccShifted <- E(g2)$crossCorrelation + 1
g3 <- graph.union(g, g2)
adjmatrix <- (adjmatrix + t(adjmatrix))/2
g2 <- graph.adjacency(adjmatrix, mode='undirected', weighted='symCC')
#g3 <- graph.union(g3, g2)
#V(g3)$name <- paste('US', V(g3)$name, sep='-')
g3 <- delete.vertices(g3, c('AK', 'HI'))
write.graph(g3, file='swine-flows-CC.xml', format='graphml')

scl <- 1.8
png(file='us-background.png', width=535*scl, height=283*scl)
par(mai=rep(0,4))
map('state', mar=rep(0,4), projection=projection, orientation=orientation,
    resolution=0, myborder=0, col='dark grey', lwd=3)
bbox <- par('usr')*scale
# uncomment to verify bbox
#do.call(rect, c(as.list(bbox[c(1,3,2,4)]/scale), lwd=30))
dev.off()

# bbox as read by jflowmap
paste(bbox[1], -bbox[4], bbox[2]-bbox[1], bbox[4]-bbox[3], sep=',')

## choropleths

theme_clean <- function (base_size=12) {
  theme_grey(base_size) %+replace% theme(
      axis.title = element_blank (),
      axis.text = element_blank (),
      panel.background = element_blank (),
      panel.grid = element_blank (),
      axis.ticks.length = unit (0,"cm"),
      axis.ticks.margin = unit (0,"cm"),
      panel.margin = unit (0,"lines"),
      plot.margin = unit(c(0,0,0,0),"lines"),
      complete =TRUE)
}

state_map <- map_data("state")

## use data from cumulative burden analysis to ensure consistency

get_map_data <- function(){
    load('pedv-cum.RData')
    key <- match(mg$State, state.abb)
    ret <- data.frame(label=mg$State, state=tolower(state.name[key]),
                           Cases=mg$cases, Inventory=mg$inventory2012,
                           x=mg$stateLong, y=mg$stateLat)
    ret$Cases <- ifelse(ret$Cases == 0, NA, ret$Cases)
    ret
}

map_data <- get_map_data()
## manually position some state labels
i <- which(map_data$label=='NH')
dy <- 1.4
map_data$x[i] <- -68.08
map_data$y[i] <- map_data$y[map_data$label=='VT'] - 1.3
ii <- which(map_data$label=='MA')
map_data$x[ii] <- map_data$x[i]
map_data$y[ii] <- map_data$y[i] - dy
ii <- which(map_data$label=='RI')
map_data$x[ii] <- map_data$x[i] - 0.3
map_data$y[ii] <- map_data$y[i] - 2*dy
i <- which(map_data$label=='DE')
map_data$x[i] <- map_data$x[i] + 2
map_data$y[i] <- map_data$y[i] - 1
ii <- which(map_data$label=='NJ')
map_data$x[ii] <- map_data$x[i] + 1.2
map_data$y[ii] <- map_data$y[ii] - 1.2
i <- which(map_data$label=='CT')
map_data$x[i] <- map_data$x[ii] + 0.5
map_data$y[i] <- map_data$y[i] - 1.7
i <- which(map_data$label=='MD')
map_data$x[i] <- map_data$x[ii] - 1.8
map_data$y[i] <- map_data$y[i] - 3

get_endpoints <- function(state){
    i1 <- which(map_data$label==state)
    i2 <- which(state.abb==state)
    data.frame(x=state.center$x[i2], y=state.center$y[i2],
               xend=map_data$x[i1] - 1.5, yend=map_data$y[i1] + 0.3)
}

g <- make_choropleth(fill_var='Cases')
ggsave(filename='cases-choropleth.pdf', plot=g, width=8.6/2.54, height=8.6/2.54)
g <- make_choropleth('Inventory')
ggsave(filename='inventory-choropleth.pdf', plot=g, width=8.6/2.54, height=8.6/2.54)

### ggPairs

mats2 <- mats[1:3]
getData <- function(matName, sym, rankv){
    dists <- getMat(matName)
    if(sym){
        dists <- (dists + t(dists))/2
    }
    ret <- as.vector(as.dist(dists))
    if(rankv){
        ret <- rank(ret)
    }
    return(ret)
}
tmpf <- function(x, ...){
    sapply(mats2, getData, sym=x, ...)
}
tmpff <- function(x) {
    lapply(c(undirected=TRUE, directed=FALSE), tmpf, rankv=x)
}
matData <- lapply(c(ranked=TRUE, original=FALSE), tmpff)

theme_set(theme_classic())
theme_update(panel.grid.major=element_blank(), panel.grid.minor=element_blank(),
             axis.ticks=element_blank(), panel.border=element_blank(),
             axis.line=element_blank())


pm <- makePlotMat(dfl=matData, type='directed', transform='ranked')
pdf(file='ggpairs-spearman-directed.pdf', width=8.6/2.54, height=8.6/2.54) 
print(pm)
dev.off()

pm <- makePlotMat(dfl=matData, type='undirected', transform='ranked')
pdf(file='ggpairs-spearman-undirected.pdf', width=8.6/2.54, height=8.6/2.54) 
print(pm)
dev.off()

pm <- makePlotMat(dfl=matData, type='directed', transform='original',
                  labelBreaks=TRUE, gridLabelSize=2.0)
plotMatDirectedPearson <- pm
pdf(file='ggpairs-pearson-directed.pdf', width=9.5/2.54, height=6.6/2.54) 
print(pm)
dev.off()

pm <- makePlotMat(dfl=matData, type='undirected', transform='original',
                  labelBreaks=TRUE)
pdf(file='ggpairs-pearson-undirected.pdf', width=11.4/2.54, height=1.2*8.6/2.54) 
print(pm)
dev.off()

### diagnostics

df <- data.frame(epl=unclass(as.dist(epl)), CC=unclass(as.dist(CC)))
m <- lm(CC~epl, data=df)
pdf('diagnostics.pdf')
plot(m)
dev.off()

## image plots

pdf('cors-heatmap.pdf')
orderings <- heatmap(data.matrix(epl), scale='none')
dev.off()

makeImagePlot <- function(M, orderings, ...){
    x <- data.matrix(M)[orderings$rowInd, orderings$colInd]
    x <- t(x)
    col <- brewer.pal(9, 'Blues')
    nc <- ncol(x)
    nr <- nrow(x)
    xi <- 1:nr
    yi <- 1:nc
    names(xi) <- colnames(x)
    names(yi) <- rownames(x)
    image.plot.ebo(x=xi, y=yi, z=x, horizontal=FALSE,col=col, graphics.reset=TRUE, ...)
}


pdf('matrices.pdf', width=8.7/2.54, height=12/2.54)
layout(matrix(1:2, ncol=1))
par(mar=c(4,4.5,.5,.5))
makeImagePlot(M=data.matrix(epl), orderings=orderings, xlab='Destination', ylab='Source',
              legend.args=list(text=expression(paste(Log[10], '(transport flow)')),
                  line=2.9, side=4), panelLab='A')
par(mar=c(4,4.5,1,.5))
CCnoDiag <- CC
diag(CCnoDiag) <- NA
makeImagePlot(M=data.matrix(CCnoDiag), orderings=orderings, xlab='Leading state', ylab='Lagging state', 
              legend.args=list(text='Cross correlation', line=2.9, side=4), panelLab='B')
dev.off()

### time series

mts <- melt(caseData, id='week')
keepers <- c('MN', 'KS',
             'IL', 'OK',
             'IA', 'NC')
test <- mts$variable %in% keepers
mts <- mts[test, ]
mts$variable <- factor(mts$variable, levels=keepers)
mts$x <- as.Date(as.character(mts$week), format='%m/%d/%Y')
labdf <- ddply(mts, 'variable', summarize, minx=x[1], maxy=max(value))
labdf$minx[labdf$variable == 'OK'] <- as.Date('2013-11-01')

tmpf <- function(df){
    g <- ggplot(df, aes(x=x, y=value, group=variable))
    g <- g + geom_hline(yintercept=0, size=0.5, col='grey')
    g <- g + geom_step(direction="vh")
    g <- g + facet_wrap(~variable, ncol=2, scales='free_y')
    g <- g + scale_x_date()
    g <- g + scale_y_discrete(breaks=pretty_breaks(n=2))
    g <- g + xlab('2013-2014 Date') + ylab('Cases')
    g <- g + theme_classic()
    g <- g + theme(strip.background = element_blank(),
                   strip.text.x = element_blank())
    g <- g + theme(plot.margin=unit(c(0,2,2,0),"mm"))
    g <- g + geom_text(data=labdf, hjust=0, vjust=1,
                       aes(x=minx, y=maxy, label=variable))
    g <- g + theme(axis.title.x = element_text(vjust=-0.5))
}

g <- tmpf(mts)
ggsave('ts.pdf', width=8.6/2.54, height=6/2.54)

### composite time series and scatterplot matrix

tmpf <- function(){
    grid.newpage()
    lay <- grid.layout(1,2, widths=unit(c(8.6,8.6), 'cm'),
                       heights=unit(c(6), 'cm'))
    pushViewport(viewport(layout=lay))
    pushViewport(viewport(layout.pos.col=1, layout.pos.row=1))
    myPrintGGpairs(plotMatDirectedPearson, newpage=FALSE)
    grid.text(label="A", x=unit(0, "npc") - unit(1.5, "lines"),
              y=unit(1, "npc"), just= "left")
    popViewport()
    pushViewport(viewport(layout.pos.col=2, layout.pos.row=1))
    print(g, newpage=FALSE)
    grid.text(label="B", x=unit(0, "npc"), y=unit(1, "npc"), just= "left")
    popViewport()
}

cairo_ps(filename = 'plotMatrixWithTimeSeries.eps', width = 19/2.54, height = 6.4/2.54)
tmpf()
dev.off()

cairo_pdf(filename = 'plotMatrixWithTimeSeries.pdf', width = 19/2.54, height = 6.4/2.54)
tmpf()
dev.off()




####################################################
## Reshaping data
####################################################


## Sheet input interdependence
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
    if(!isEmpty(currentLayer)){
      markType <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']]
      stat <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']]
      isolate({
        # control stat choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']] <<-
          StatChoices[sapply(StatChoices, function(n) !is.null(getAesChoices(geom=markType, stat=n)))]
        # control aesthetics choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']] <<-
          getAesChoices(markType, stat)
      })
    }

    cc <- sheetList[[currentSheet]][['dynamicProperties']][['columns']]
    rr <- sheetList[[currentSheet]][['dynamicProperties']][['rows']]
    mDat <- sheetList[[currentSheet]][['datR']]()
    fields <- sheetList[[currentSheet]][['fieldNames']]()
    measures <- sheetList[[currentSheet]][['measuresR']]()

    cc1 <- ''; rr1 <- ''; cChoices <- ''; rChoices <- ''
    outTable <- NULL; outDf <- NULL;
    cc.measures <- ''; cc.dims <- '';
    rr.measures <- ''; rr.dims <- ''
    if(!is.null(fields)){
      dims <- setdiff.c(fields, measures)
      cc1 <- intersect(cc,dims); rr1 <- intersect(rr,dims)
      #         cc.measures <- intersect(cc1,measures); rr.measures <- intersect(rr1,measures)
      #         cc.dims <- setdiff(cc1,cc.measures); rr.dims <- setdiff(rr1,rr.measures)

      #         cc1 <- c(cc.dims,cc.measures); rr1 <- c(rr.dims,rr.measures)

      all.x <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesX']][['aesField']])
      all.y <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesY']][['aesField']])

      cChoices <- setdiff.c(dims, c(all.x, all.y, rr1))
      rChoices <- setdiff.c(dims, c(all.x, all.y, cc1))
      if(!isEmpty(currentLayer)){
        isolate({
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesX']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesY']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
        })
      }


      if(!is.null(mDat)){
        outType <- (sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
        if(outType=='table'){
          #             if(combineMeasures && !is.null(facets)){
          #               outTable <- cast(mDat, facets, sum)
          #               outDf <- as.data.frame(outTable)
          #             }

        } else {

        }

        if(!is.null(outDf)){
          ## add to dataList
          isolate({
            sheetNameDat <- convertSheetNameToDatName(sheetList[[currentSheet]][['dynamicProperties']][['name']])
            if(is.null(datList[[currentSheet]])){
              datList[[currentSheet]] <<- createNewDatClassObj(outDf, name=sheetNameDat, type='sheet')
            } else {
              datList[[currentSheet]][['dynamicProperties']][['dat']] <<- outDf
              datList[[currentSheet]][['dynamicProperties']][['measures']] <<- intersect(datList[[currentSheet]][['dynamicProperties']][['measures']],
                                                                                         getDefaultMeasures(outDf))
              ## add new fields, delete outdated fields, leave common fields alone since they might have user customizations
              newFields <- getDefaultFieldsList(outDf)
              oldList <- names(datList[[currentSheet]][['dynamicProperties']][['fieldsList']])
              newList <- names(newFields)
              for(n in setdiff(newList, oldList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- newFields[[n]]
              }
              for(n in setdiff(oldList, newList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- NULL
              }
            }
          })
        }
      }

    }
    isolate({
      #       sheetList[[currentSheet]][['dynamicProperties']][['dat']] <<- mDat
      #       sheetList[[currentSheet]][['dynamicProperties']][['cMeasures']] <<- cc.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['cDims']] <<- cc.dims
      #       sheetList[[currentSheet]][['dynamicProperties']][['rMeasures']] <<- rr.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['rDims']] <<- rr.dims
      if(are.vectors.different(cc1, sheetList[[currentSheet]][['dynamicProperties']][['columns']])){
        triggerUpdateInput('sheetColumns')
      }
      if(are.vectors.different(rr1, sheetList[[currentSheet]][['dynamicProperties']][['rows']])){
        triggerUpdateInput('sheetRows')
      }
      sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- cc1
      sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- rr1
      sheetList[[currentSheet]][['dynamicProperties']][['colChoices']] <<- cChoices
      sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']] <<- rChoices
      sheetList[[currentSheet]][['dynamicProperties']][['outputTable']] <<- outTable
      sheetList[[currentSheet]][['dynamicProperties']][['outputDataframe']] <<- outDf
    })
  }
}, priority=1)




## Switching sheet
observe({
  v <- input$sheetList
  isolate({
    if(!isEmpty(v)) projProperties[['activeSheet']] <<- v
  })

})
observe({
  updateInput[['activeSheet']]
  updateSelectInput(session, 'sheetList', choices=(sheetListNames()),
                    selected=isolate(projProperties[['activeSheet']]))
})


## modify sheet name
observe({
  v <- input$sheetName
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      if(!isEmpty(v) && isEmpty(sheetListNames()[v])){
        ## the second condition makes sure v is different
        ## update doc's rmd
        oldName <- paste('`', sheetList[[currentSheet]][['dynamicProperties']][['name']], '`', sep='')
        newName <- paste('`', v, '`', sep='')
        sapply(names(docList), function(currentDoc){
          docList[[currentDoc]][['rmd']] <<- gsub(oldName, newName, docList[[currentDoc]][['rmd']], fixed=TRUE)
          NULL
        })
        triggerUpdateInput('docRmd')

        sheetList[[currentSheet]][['dynamicProperties']][['name']] <<- v
      }
    }
  })

})
observe({
  updateInput[['sheetName']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['name']])
  } else ''
  updateTextInput(session, 'sheetName', value=null2String(s))
})

## link sheet name to corresponding data name
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    s <- sheetList[[currentSheet]][['dynamicProperties']][['name']]
    isolate({
      if(!is.null(datList[[currentSheet]])){
        datList[[currentSheet]][['dynamicProperties']][['name']] <<- convertSheetNameToDatName(s)
        triggerUpdateInput('datName')
      }
    })
  }
})

## Selecting data for sheet
observe({
  v <- input$sheetDatList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['datId']] <<- v
  })

})
observe({
  updateInput[['sheetDatId']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['datId']])
  } else ''
  choices <- datListNames()
  choices <- choices[!sapply(choices, isDatBasedonSheet, sheetId=currentSheet)]
  updateSelectInput(session, 'sheetDatList', choices=null2String(choices),
                    selected=null2String(s))
})

## whether use molten data?
observe({
  v <- input$combineMeasures
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']] <<- as.logical(v)
    }
  })

})
observe({
  updateInput[['combineMeasures']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']])
  } else FALSE
  updateCheckboxInput(session, 'combineMeasures', value=null2String(s))
})

## Manipulating columns
observe({
  v <- input$columns
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- v
  })

})
observe({
  updateInput[['sheetColumns']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['columns']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['colChoices']]} else ''
  updateSelectizeInput(session, 'columns', choices=null2String(choices), selected=null2String(s))
})

## Manipulating rows
observe({
  v <- input$rows
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- v
  })

})
observe({
  updateInput[['sheetRows']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['rows']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']]} else ''
  updateSelectizeInput(session, 'rows', choices=null2String(choices), selected=null2String(s))
})

## Manipulating output type
observe({
  v <- input$outputTypeList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['outputType']] <<- v
  })

})
observe({
  updateInput[['sheetOutput']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
  } else ''
  updateSelectInput(session, 'outputTypeList', selected=null2String(s))
})

## Selecting ggplot layer for sheet
observe({
  v <- input$layerList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- v
    }
  })
})
observe({
  updateInput[['sheetPlotLayer']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
  } else ''
  choices <- if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['layerNames']]()
  updateSelectInput(session, 'layerList', choices=null2String(choices),
                    selected=null2String(s))
})

## Selecting aesthetic
observe({
  v <- input$aesList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) {
        currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['sheetLayerAes']]
  currentSheet <- projProperties[['activeSheet']]
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']])
    }
  }

  updateSelectInput(session, 'aesList', choices=null2String(choices),
                    selected=null2String(s))
})

## set aes map or set option
observe({
  v <- input$aesMapOrSet
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']] <<- v

            ## set default value
            if(v=='set' && isEmpty(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<-
                switch(currentAes,
                       'aesLabel'='My Label', 'aesFamily'='Times', 'aesFontface'='plain',
                       'aesColor'=, 'aesBorderColor'='',
                       'aesSize'=8, 'aesLineheight'=1,
                       0
                )

              triggerUpdateInput('aesValue')
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesMapOrSet']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- 'map'
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        s1 <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        if(!are.vectors.different('set', s1)) s <- 'set'
      }
    }
  }
  updateRadioButtons(session, 'aesMapOrSet', selected=s)
})

## map or set UI
output$mapOrSetUI <- renderUI({
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        useMapping <- are.vectors.different('set',
                                            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        isolate({
          aes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]]
          if(useMapping){
            s <- null2String(aes[['aesField']])
            choices <- if(currentAes %in% c('aesX','aesY')) {
              aes[['fieldChoices']]
            } else {
              sheetList[[currentSheet]][['fieldNames']]()
            }
            if(!(s %in% choices)) choices[s]=s ## this is needed when s="", otherwise selected will defaults to the first value

            aggFun <- null2String(aes[['aesAggFun']])
            aggFunchoices <- YFunChoices
            if(!(aggFun %in% aggFunchoices)) aggFunchoices[aggFun]=aggFun

            fluidRow(
              column(4,
                     selectizeInput(inputId='aesField', label='Field',
                                    choices=choices, selected=s, multiple=FALSE,
                                    options = list(create = TRUE))
              ),
              column(4,
                     checkboxInput(inputId='aesAggregate', label='Aggregate Field',
                                   value=aes[['aesAggregate']]),
                     conditionalPanel('input.aesAggregate==true',
                                      selectizeInput(inputId='aesAggFun', label='By',
                                                     choices=aggFunchoices,
                                                     selected=aggFun, multiple=FALSE,
                                                     options = list(create = TRUE))
                     )

              ),
              column(4,
                     conditionalPanel('output.canAesFieldBeContinuous==true',
                                      radioButtons('aesDiscrete', 'Treat Field as',
                                                   choices=c('Continuous'='continuous',
                                                             'Discrete'='discrete'),
                                                   selected=ifelse(aes[['aesDiscrete']], 'discrete', 'continuous'),
                                                   inline=FALSE)
                     )


              )
            )
          } else {
            switch(currentAes,
                   'aesLabel'=textInput('aesValue', '', value=aes[['aesValue']]),
                   'aesFontface'=selectInput('aesValue','',choices=FontFaceChoices, selected=aes[['aesValue']]),
                   'aesFamily'=selectInput('aesValue','',choices=FontFamilyChoices, selected=aes[['aesValue']]),
                   'aesColor'=, 'aesBorderColor'=colorInput('aesValue', '', value=aes[['aesValue']]),
                   'aesShape'=, 'aesLineType'=numericInput('aesValue', 'Value', value=aes[['aesValue']], step=1),
                   numericInput('aesValue', 'Value', value=aes[['aesValue']], step=0.1)
            )
          }
        })
      }
    }
  }
})

## set aesValue
observeEvent(input$aesValue,
             {
  v <- input$aesValue
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<- v
      }
    }
  }
})


## set aes field
observe({
  v <- input$aesField
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']] <<- v

              ## set default field properties
              if(isEmpty(v) && currentLayer != 'Plot'){
                v <- null2String(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']][['aesList']][[currentAes]][['aesField']])
              }
              is.measure <- v %in% sheetList[[currentSheet]][['measuresR']]()
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']] <<-
                is.measure  ## just for capturing this information to customize choices for agg fun
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- is.measure
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- if(is.measure) 'sum' else 'length'
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- !is.measure
              sapply(c('aesAggregate','aesAggFun','aesDiscrete'), triggerUpdateInput)

              ## set default xlab, ylab
              if(!isEmpty(v)){
                fieldNames <- sheetList[[currentSheet]][['fieldNames']]()
                i.match <- match(v, fieldNames)
                if(!is.na(i.match)){
                  fieldName <- names(fieldNames)[i.match]
                  switch(currentAes,
                         'aesX'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']] <<- fieldName
                           triggerUpdateInput('plotXlab')
                         },
                         'aesY'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']] <<- fieldName
                           triggerUpdateInput('plotYlab')
                         }
                         )

                }
              }

            }
          }
        }
      }
    })
  }

})


output$canAesFieldBeContinuous <- reactive({
  ans <- FALSE
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        ans <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['canFieldBeContinuous']]()
      }
    }
  }
  ans
})
outputOptions(output, "canAesFieldBeContinuous", suspendWhenHidden=FALSE)

## set aes aggregate
observe({
  v <- input$aesAggregate
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- v
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesAggregate']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- FALSE
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']])

        }
      }
    }
    updateCheckboxInput(session, 'aesAggregate', value=s)
  })

})


## set aes agg fun
observe({
  v <- input$aesAggFun
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['aesAggFun']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- ''
    choices <- YFunChoices
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']]
          is.measure <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']]
          if(!is.null(is.measure) && !is.measure) choices <- AggFunChoicesDimension
        }
      }
    }

    if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
    updateSelectizeInput(session, 'aesAggFun', choices=null2String(choices), selected=null2String(s))
  })
})

## set aes discrete
observe({
  v <- input$aesDiscrete
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            isDiscrete <- (v=='discrete')
            if(currentAes %in% c('aesX', 'aesY')){
              ## can't mix discrete with continuous scales on x or y, so need to keep all layers the same
              for(layer in names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])){
                sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
              }
            } else {
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesDiscrete']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- 'discrete'
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          d <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']])
          if(!isEmpty(d) && !d){
            s <- 'continuous'
          }

        }
      }
    }
    updateRadioButtons(session, 'aesDiscrete', selected=s)
  })
})

## set Mark Type / geom
observe({
  v <- input$markList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']] <<- v
          # set default stat type & position
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<-
            switch(v, 'boxplot'='boxplot', 'identity')
          triggerUpdateInput('layerStatType')
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<-
            switch(v, 'bar'='dodge', 'identity')
          triggerUpdateInput('layerPositionType')
        }
      }
    }
  })
})
observe({
  updateInput[['layerGeom']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']])
      #choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geomChoices']])
    }
  }
  updateSelectInput(session, 'markList', selected=null2String(s))
})

## set Stat Type
observe({
  v <- input$statTypeList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){

          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerStatType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']])
    }
  }

  updateSelectInput(session, 'statTypeList', choices=null2String(choices), selected=null2String(s))
})

## set y fun
observe({
  v <- input$yFunList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerYFun']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']])
    }
  }
  choices <- YFunChoices
  if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
  updateSelectizeInput(session, 'yFunList', choices=null2String(choices), selected=null2String(s))
})



## set PositionType
observe({
  v <- input$layerPositionType
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']])
    }
  }
  updateSelectizeInput(session, 'layerPositionType', selected=null2String(s))
})

## set Position Height
observe({
  v <- empty2NULL(as.numeric(input$layerPositionHeight))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionHeight']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']])
    }
  }
  updateTextInput(session, 'layerPositionHeight', value=null2String(s))
})

## set Position Width
observe({
  v <- empty2NULL(as.numeric(input$layerPositionWidth))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionWidth']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']])
    }
  }
  updateTextInput(session, 'layerPositionWidth', value=null2String(s))
})




tabS <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
                   (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )
canLatexPNG <- tryCatch(length(make.png(tabS)), error=function(e) FALSE)


output$sheetOutput <- renderUI({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    switch(sheetList[[currentSheet]][['dynamicProperties']][['outputType']],
           'table'=if(canLatexPNG) imageOutput('sheetOutputTable') else {
             tags$div(
               HTML(paste(capture.output(Hmisc::html(sheetList[[currentSheet]][['tableR']]())), collapse=" "))
             )
           },
           'plot'=plotOutput('ggplot'))
  }

})


output$sheetOutputTable <- renderImage(if(canLatexPNG) {
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    tab <- sheetList[[currentSheet]][['tableR']]()

    if(!is.null(tab)){
      #width  <- session$clientData$output_test_width
      #height <- session$clientData$output_test_height

      # For high-res displays, this will be greater than 1
      pixelratio <- session$clientData$pixelratio
      fileName <- make.png(tab, resolution=72*pixelratio)
      pngFile <- readPNG(fileName)

      # Return a list containing the filename
      list(src = normalizePath(fileName),
           width = dim(pngFile)[2],
           height = dim(pngFile)[1],
           alt = "Output not available")
    }
  }
}, deleteFile = TRUE)

# x <- tabular( (Species + 1) ~ (n=1) + Format(digits=3)*
#                 (Sepal.Length + Sepal.Width)*(mean + Justify(r)*sd), data=iris )
# tags$div(
#   HTML(paste(capture.output(Hmisc::html(x)), collapse=" "))
# )

## Reshaped output
output$reshapedDat <- renderTable({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['outputTable']]}
})

ggplotOutput <- reactiveValues()
observe({
  if(input$autoRefresh=='refresh'){
    currentSheet <- projProperties[['activeSheet']]
    if(!isEmpty(currentSheet)){
      ggplotOutput[['plot']] <- sheetList[[currentSheet]][['plotR']]()
    }
  } else {
    isolate({
      if(!is.null(ggplotOutput[['plot']])) ggplotOutput[['plot']] <- ggplotOutput[['plot']] + theme_grey()
    })
  }
})
output$ggplot <- renderPlot({
  ggplotOutput[['plot']]
})



## add Layer
observe({
  v <- input$addLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        existingNames <- names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])
        layerName <- make.unique(c(existingNames, 'Overlay'), sep='_')[length(existingNames)+1]

        newLayer <- createNewLayer()
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]] <<- newLayer
        sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- layerName

        #copy from Plot layer
        plotLayer <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']]
        names1 <- names(plotLayer)
        for(n1 in names1){
          if(n1=='aesList'){
            names2 <- names(plotLayer[[n1]])
            for(n2 in names2){
              names3 <- names(plotLayer[[n1]][[n2]])
              for(n3 in names3){
                if(n3 != 'aesField' && typeof(plotLayer[[n1]][[n2]][[n3]]) != 'closure'){#
                  sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]][[n2]][[n3]] <<- plotLayer[[n1]][[n2]][[n3]]
                }
              }
              setAesReactives(currentSheet, layerName, n2)
            }
          } else {
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]] <<- plotLayer[[n1]]
          }
        }

      }
    }
  })
})
## delete Layer
observe({
  v <- input$deleteLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer) && currentLayer!='Plot'){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- 'Plot'
        }
      }
    }
  })
})
## bring Layer to top
observe({
  v <- input$bringToTop
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          temp <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]]
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- temp
        }
      }
    }
  })
})

## add sheet
observe({
  v <- input$addSheet
  isolate({
    if(v){
      addSheet()
    }
  })
})
## delete sheet
observe({
  v <- input$deleteSheet
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        sheets <- names(sheetList)
        i <- match(currentSheet, sheets)
        sheetList[[currentSheet]] <<- NULL
        projProperties[['activeSheet']] <<- ifelse(length(sheets)>i, sheets[i+1],
                                                   ifelse(i>1, sheets[i-1], ''))
      }
    }
  })
})

#!/usr/bin/Rscript

source("plot.r")

doConfidence <- function() {
    numPoints <- 10

    x <- rnorm(numPoints)
    y <- rnorm(numPoints)

    plotWithConfidence(x, y, abs(y/10.0), pdfFile="conf.pdf")
}

doBoxPlot <- function() {
    numPoints <- 10000

    x <- rnorm(numPoints)
    y <- rnorm(numPoints)

    plotBox(x, y, pdfFile="box.pdf")
}

doConfidenceContinous <- function() {
    x1 <- seq(0,10,0.01)
    x <- x1
    for (i in 1:31) {
        x <- c(x,x1)
    }

    numPoints <- length(x)

    y <- x*x + rnorm(numPoints)

    outMean <- tapply(y, x, mean)
    outSD <- tapply(y, x, sd)
    out <- data.frame(x = names(outMean), mean = outMean, sd = outSD, row.names = NULL)

    confLevel <- 0.99
    numReplications <- 32

    plotWithConfidenceContinous(x1, out$mean, 10.0 * qnorm(1.0 - (1.0 - confLevel)/2.0) * out$sd/sqrt(numReplications), pdfFile = "confContinous.pdf")
}

doConfidence()
doBoxPlot()
doConfidenceContinous()
source("colors.r")

#
# OUTLINE
#

# every plot function in this file makes IMHO nice formatted plots in four steps

# 1. Plot an empty plot, to inform R about ranges of data (grid needs this)
# 2. Plot background and grid
# 3. Plot data
# 4. Plot axes, box and titles

################################################################################

# Helper function for leaving out unused margins
doMargins <- function(mainTitle, xTitle, yTitle) {
  margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)
}

################################################################################

# Helper function for plotting axes and title on top of plot
doBoxTitleAndAxes <- function(mainTitle, xTitle, yTitle) {
  box(col = thillux_grey[1], bty="l")
  title(main=mainTitle, col=thillux_grey[1], xlab=xTitle, ylab=yTitle)
  axis(1, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
  axis(2, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
}

################################################################################

# Helper function for creating PDF devices
doOpenPDF <- function(pdfFile, pdfTitle) {
  pdfFilePath = "out.pdf"
  if(!is.null(pdfFile)) {
    pdfFilePath = pdfFile
  }
  pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)
}

################################################################################

# Helper function for plotting background and grid, before plotting on top of it
doPlotBackgroundAndGrid <- function() {
  u <- par("usr")
  rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)
  par(col.lab=thillux_grey[1])
  grid(col=thillux_grey[1], lty=3, lwd=0.5)
}

################################################################################

plotHistogram <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      lty=1,
      cex=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotHistogramNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    h$counts <- h$counts/sum(h$counts)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      freq=FALSE,
      lty=1,
      cex=1)

    x <- seq(min(-10.0, min(dataArray) * 0.5) , max(max(dataArray) * 1.5, 100), length=10000)
    y <- dnorm(x, mean=mean(dataArray), sd=sd(dataArray))

    par(new=TRUE)

    plot(x,y,
         type="l",
         lwd=3,
         axes=FALSE,
         col=colorScheme[2,2],
         xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
         ylab='',
         xlab='',
         main=''
    )

    polygon(x, y,
            col=colorScheme[2,2],
            border=colorScheme[2][1],
            ylab='',
            xlab='',
            main=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqnorm(dataArray, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    qqline(sort(dataArray), ylab='',
      xlab='', col=colorScheme[2,2], lwd=2)

    par(new=TRUE)

    qq <- qqnorm(sort(dataArray), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQ <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqplot(dataArray1, dataArray2, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    qq <- qqplot(sort(dataArray1), sort(dataArray2), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotPoints <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(dataArray1, dataArray2,
      type="p",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotSmoothLine <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(smooth.spline(dataArray1, dataArray2),
      type="l",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidence <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    xLim <- range(xData) + c(-0.1,0.1)
    yLim <- range(c(yData+e,yData-e)) + c(-0.1,0.1)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    widthToInch = 96.0
    arrowLength = diff(range(xData))/25.0

    rect(xData - arrowLength, yData - e, xData + arrowLength, yData + e, col=colorScheme[1,2], border=FALSE)

    arrowTipLength = pmin(e/2.0, arrowLength/3.0)

    segments(xData - arrowLength, yData - e, xData + arrowLength, yData - e, lend=1, col=colorScheme[1,1])
    segments(xData - arrowLength, yData + e, xData + arrowLength, yData + e, lend=1, col=colorScheme[1,1])

    segments(xData - arrowLength/2.0, yData, xData+arrowLength/2.0, yData, col=colorScheme[1,1], lwd = 1.0)

    if (connectionLines) {
      frame <- data.frame(xData,yData)
      frame <- frame[order(xData),]
      lines(frame$xData, frame$yData, col=colorScheme[1,2],lty=2)
    }

    # draw circle outlines
    r <- pmin(e/2.0, arrowLength/5.0)
    for (i in 1 : length(xData)) {
      mid1X <- xData[i] - arrowLength
      mid1Y <- yData[i] + e[i] - r[i]

      mid2X <- xData[i] - arrowLength
      mid2Y <- yData[i] - e[i] + r[i]

      mid3X <- xData[i] + arrowLength
      mid3Y <- yData[i] + e[i] - r[i]

      mid4X <- xData[i] + arrowLength
      mid4Y <- yData[i] - e[i] + r[i]

      deg <- 90 : 180
      xCircle1 <- mid1X + r[i] * cos(deg/180.0 * pi)
      yCircle1 <- mid1Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle1, yCircle1, col=colorScheme[1,1])

      deg <- 180 : 270
      xCircle2 <- mid2X + r[i] * cos(deg/180.0 * pi)
      yCircle2 <- mid2Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle2, yCircle2, col=colorScheme[1,1])

      polygon(c(xCircle1, xCircle2), c(yCircle1, yCircle2), col = colorScheme[1,2], border = FALSE)

      deg <- 0 : 90
      xCircle3 <- mid3X + r[i] * cos(deg/180.0 * pi)
      yCircle3 <- mid3Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle3, yCircle3, col=colorScheme[1,1])

      deg <- 270 : 360
      xCircle4 <- mid4X + r[i] * cos(deg/180.0 * pi)
      yCircle4 <- mid4Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle4, yCircle4, col=colorScheme[1,1])

      polygon(c(xCircle3, xCircle4), c(yCircle3, yCircle4), col = colorScheme[1,2], border = FALSE)
    }

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidenceContinous <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    xLim <- range(xData) + c(-0.1,0.1)
    yLim <- range(c(yData + e, yData - e)) + c(-0.1,0.1)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    polygon(c(sort(xData),rev(sort(xData))),c(yData + e, rev(yData-e)), col=colorScheme[1,2], border=FALSE)

    lines(xData, yData + e, col=colorScheme[1,1])
    lines(xData, yData - e, col=colorScheme[1,1])

    lines(xData,yData,col=colorScheme[2,1])

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotBox <- function(xData, yData, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks=10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(cut(xData, breaks=breaks), yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      col="#00000000",
      border="#00000000",
      bg="#00000000",
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(cut(xData, breaks=breaks), yData,
      type="l",
      axes=FALSE,
      col=thillux_grey[2],
      bg=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
each-mode: no

if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	each-mode:  find args "--each"
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either each-mode [
    	do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ][
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
#' Import a module into the current scope
#'
#' \code{module = import('module')} imports a specified module and makes its
#' code available via the environment-like object it returns.
#'
#' @param module a character string specifying the full module path
#' @param attach either a boolean or a  character vector. If \code{TRUE}, attach
#'  the newly loaded module to the object search path (see \code{Details}).
#'  Alternatively, if a character vector is given, attach only the listed names.
#' @param attach_operators if \code{TRUE}, attach operators of module to the
#'  object search path, even if \code{attach} is \code{FALSE}
#' @param doc boolean specifying whether to load the module’s documentation (see
#'  \code{Details})
#' @return the loaded module environment (invisible)
#'
#' @details Modules are loaded in an isolated environment which is returned, and
#' optionally attached to the object search path of the current scope (if
#' argument \code{attach} is \code{TRUE}).
#' \code{attach} defaults to \code{FALSE}. However, in interactive code it is
#' often helpful to attach packages by default. Therefore, in interactive code
#' invoked directly from the terminal only (i.e. not within modules),
#' \code{attach} defaults to the value of \code{options('import.attach')}, which
#' can be set to \code{TRUE} or \code{FALSE} depending on the user’s preference.
#'
#' \code{attach_operators} causes \emph{operators} to be attached by default,
#' because operators can only be invoked in R if they re found in the search
#' path. Not attaching them therefore drastically limits a module’s usefulness.
#'
#' \code{doc} loads the module’s documentation, specified as roxygen comments.
#' It defaults to \code{TRUE} in interactive mode and to \code{FALSE} otherwise.
#'
#' Modules are searched in the module search path \code{options('import.path')}.
#' This is a vector of paths to consider, from the highest to the lowest
#' priority. The current directory is \emph{always} considered last. That is,
#' if a file \code{a.r} exists both in the current directory and in a module
#' search path, the local file \code{./a.r} will not be loaded, unless the
#' import is explicitly specified as \code{import('./a')}.
#'
#' Module names can be fully qualified to refer to nested paths. See
#' \code{Examples}.
#'
#' Module source code files are assumed to be encoded in UTF-8 without BOM.
#' Ensure that this is the case when using an extended character set.
#'
#' @note Unlike for packages, attaching happens \emph{locally}: if
#' \code{import} is executed in the global environment, the effect is the same.
#' Otherwise, the imported module is inserted as the parent of the current
#' \code{environment()}. When used (globally) \emph{inside} a module, the newly
#' imported module is only available inside the module’s search path, not
#' outside it (nor in other modules which might be loaded).
#'
#' @examples
#' \dontrun{
#' # `a.r` is a file in the local directory containing a function `f`.
#' a = import('a')
#' a$f()
#'
#' # b/c.r is a file in path `b`, containing functions `f` and `g`.
#' import('b/c', attach = 'f')
#' # No module name qualification necessary
#' f()
#' g() # Error: could not find function "g"
#'
#' import('b/c', attach = TRUE)
#' f()
#' g()
#' }
#' @seealso \code{unload}
#' @seealso \code{reload}
#' @seealso \code{module_name}
#' @seealso \code{module_help}
#' @export
import = function (module, attach, attach_operators = TRUE, doc) {
    stopifnot(inherits(module, 'character'))

    if (missing(attach)) {
        attach = if (interactive() && is.null(module_name()))
            getOption('import.attach', FALSE)
        else
            FALSE
    }

    stopifnot(class(attach) == 'logical' && length(attach) == 1 ||
              class(attach) == 'character')

    if (is.character(attach)) {
        export_list = attach
        attach = TRUE
    }
    else
        export_list = NULL

    if (missing(doc))
        doc = interactive()

    module_path = try(find_module(module), silent = TRUE)

    if (inherits(module_path, 'try-error'))
        stop(attr(module_path, 'condition')$message)

    containing_modules = module_init_files(module, module_path)
    mapply(do_import, names(containing_modules), containing_modules,
           rep(doc, length(containing_modules)))

    mod_ns = do_import(as.character(module), module_path, doc)
    module_parent = parent.frame()
    mod_env = exhibit_namespace(mod_ns, as.character(module), module_parent,
                                export_list)

    attached_module = if (attach)
        mod_env
    else if (attach_operators)
        export_operators(mod_ns, module_parent)
    else
        NULL

    if (! is.null(attached_module)) {
        # The following distinction is necesary because R segfaults if we try to
        # change `parent.env(.GlobalEnv)`. More info:
        # http://stackoverflow.com/q/22790484/1968
        if (identical(module_parent, .GlobalEnv)) {
            attach(attached_module, name = environmentName(attached_module))
            attr(mod_env, 'attached') = environmentName(attached_module)
        }
        else
            parent.env(module_parent) = attached_module
    }

    attr(mod_env, 'call') = match.call()
    lockEnvironment(mod_env, bindings = TRUE)
    invisible(mod_env)
}

do_import = function (module_name, module_path, doc) {
    if (is_module_loaded(module_path))
        return(get_loaded_module(module_path))

    # Environment with helper functions which are only available when loading a
    # module via `import`, and are not otherwise exported by the package.
    helper_env = list2env(list(export_submodule = export_submodule),
                          parent = .BaseNamespaceEnv)

    # The namespace contains a module’s content. This schema is very much like
    # R package organisation.
    # A good resource for this is:
    # <http://obeautifulcode.com/R/How-R-Searches-And-Finds-Stuff/>
    namespace = structure(new.env(parent = helper_env),
                          name = paste('namespace', module_name, sep = ':'),
                          path = module_path,
                          class = c('namespace', 'environment'))

    # First cache the (still empty) namespace, then source code into it. This is
    # necessary to allow circular imports.
    cache_module(namespace)

    # R, Windows and Unicode don’t play together. `source` does not work here.
    # See http://developer.r-project.org/Encodings_and_R.html and
    # http://stackoverflow.com/q/5031630/1968 for a discussion of this.
    eval(parse(module_path, encoding = 'UTF-8'), envir = namespace)

    make_S3_methods_known(namespace)

    if (doc)
        attr(namespace, 'doc') = parse_documentation(namespace)
    namespace
}

exhibit_namespace = function (namespace, name, parent, export_list) {
    if (is.null(export_list))
        export_list = ls(namespace)
    else {
        # Verify correctness.
        exist = vapply(export_list, exists, logical(1), envir = namespace)
        if (! all(exist))
            stop(sprintf('Non-existent function(s) (%s) specified for import',
                         paste(export_list[! exist], collapse = ', ')))
    }

    # Skip one parent environment because this module is hooked into the chain
    # between the calling environment and its ancestor, thus sitting in its
    # local object search path.
    structure(list2env(sapply(export_list, get, envir = namespace,
                              simplify = FALSE),
                       parent = parent.env(parent)),
              name = paste('module', name, sep = ':'),
              path = module_path(namespace),
              doc = attr(namespace, 'doc'),
              class = c('module', 'environment'))
}

export_operators = function (namespace, parent) {
    ops = c('+', '-', '*', '/', '^', '**', '&', '|', ':', '::', ':::', '$',
            '$<-', '=', '<-', '<<-', '==', '<', '<=', '>', '>=', '!=', '~',
            '&&', '||', '!', '?', '@', '@<-', ':=')

    is_predefined = function (f) f %in% ops

    is_op = function (f) {
        # `.` delimits an S3 method name, but only when not inside `%…%`.
        prefix = regmatches(f, regexpr('^[^.]+|(%[^%]*%)', f))
        is_predefined(prefix) || grepl('^%.*%$', prefix)
    }

    operators = Filter(is_op, lsf.str(namespace))

    if (length(operators) == 0)
        return()

    name = module_name(namespace)
    # Skip one parent environment because this module is hooked into the chain
    # between the calling environment and its ancestor, thus sitting in its
    # local object search path.
    structure(list2env(sapply(operators, get, envir = namespace),
                       parent = parent.env(parent)),
              name = paste('operators', name, sep = ':'),
              path = module_path(namespace),
              class = c('module', 'environment'))
}

#' Unload a given module
#'
#' Unset the module variable that is being passed as a parameter, and remove the
#' loaded module from cache.
#' @param module reference to the module which should be unloaded
#' @note Any other references to the loaded modules remain unchanged, and will
#' still work. However, subsequently importing the module again will reload its
#' source files, which would not have happened without \code{unload}.
#' Unloading modules is primarily useful for testing during development, and
#' should not be used in production code.
#'
#' \code{unload} comes with a few restrictions. It attempts to detach itself
#' if it was previously attached. This only works if it is called in the same
#' scope as the original \code{import}.
#' @seealso \code{import}
#' @seealso \code{reload}
#' @export
unload = function (module) {
    stopifnot(inherits(module, 'module'))
    module_ref = as.character(substitute(module))
    rm(list = module_path(module), envir = .loaded_modules)
    attached = attr(module, 'attached')
    if (! is.null(attached))
        detach(attached, character.only = TRUE)
    # Unset the module reference in its scope, i.e. the caller’s environment or
    # some parent thereof.
    rm(list = module_ref, envir = parent.frame(), inherits = TRUE)
}

#' Reload a given module
#'
#' Remove the loaded module from the cache, forcing a reload. The newly reloaded
#' module is assigned to the module reference in the calling scope.
#' @param module reference to the module which should be unloaded
#' @note Any other references to the loaded modules remain unchanged, and will
#' still work. Reloading modules is primarily useful for testing during
#' development, and should not be used in production code.
#'
#' \code{reload} comes with a few restrictions. It attempts to re-attach itself
#' in parts or whole if it was previously attached in parts or whole. This only
#' works if it is called in the same scope as the original \code{import}.
#' @seealso \code{import}
#' @seealso \code{unload}
#' @export
reload = function (module) {
    stopifnot(inherits(module, 'module'))
    module_ref = as.character(substitute(module))
    module_parent = parent.frame()
    # Execute in parent scope, since `unload` deletes the scope’s reference to
    # the module.
    eval(call('unload', as.name(module_ref)), envir = module_parent)
    # Use `eval` to replicate the exact call being made to `import`.
    mod_env = eval(attr(module, 'call'), envir = module_parent)
    assign(module_ref, mod_env, envir = module_parent, inherits = TRUE)
}

#' Pretty-print a module’s description
#'
#' @export
print.module = function (module) {
    cat(sprintf('<%s>\n', attr(module, 'name')))
    invisible(module)
}
import_package = function (package, attach, attach_operators = TRUE) {
    stopifnot(inherits(package, 'character'))

    if (missing(attach)) {
        attach = if (interactive() && is.null(module_name()))
            getOption('import.attach', FALSE)
        else
            FALSE
    }

    stopifnot(class(attach) == 'logical' && length(attach) == 1)

    module_parent = parent.frame()

    # TODO: Do we actually need this? Nothing is attached here, even if loading
    # the package via `library` would attach stuff.
    # We can also just opt to blatantly ignore `Depends` packages.
    # Furthermore, S4 functions don’t work, and nor do S3, I’d wager.

    # Package which use `Depends` will pollute the global `search()` path.
    # We save the old `search()` path, and restore it afterwards. Furthermore,
    # We attach the list of attached packages to our local parent environment
    # chain instead.
    old_search = search()
    on.exit({
        if (! identical(module_parent, .GlobalEnv)) {
            newly_attached = setdiff(search(), old_search)
            for (pkg in newly_attached)
                detach(pkg)

            # Insert them into the current package’s parent chain.
            # We only need to insert the first one, since it already has the
            # others as its parents.
            # NOTE: This relies on the fact that `setdiff` doesn’t change the
            # order of the elements.

            parent.env(tail(newly_attached, 1)) = parent.env(module_parent)
            parent.env(module_parent) = newly_attached[1]
        }
    })

    pkg_ns = require_namespace(package)
    if (inherits(pkg_ns, 'error'))
        stop('Unable to load packge ', sQuote(package), '\n',
             'Failed with error: ', sQuote(conditionMessage(pkg_ns)))

    # TODO: Handle attaching

    # TODO: Return entries from  `.__NAMESPACE__.$exports`
    # FIXME: Wrong environment name set (is: 'module:packagename')
    # FIXME: Can the following ever differ from its contents, i.e. is
    #   all.equal(ls(…$exports), sapply(ls(…$exports), get, envir = …$exports))?
    export_list = getNamespaceExports(pkg_ns)
    pkg_env = exhibit_namespace(pkg_ns, package, module_parent, export_list)

    pkg_env$.__S3MethodsTable__. = pkg_ns$.__S3MethodsTable__.

    attached_module = if (attach)
        pkg_env
    else if (attach_operators)
        export_operators(pkg_ns, module_parent)
    else
        NULL

    if (! is.null(attached_module)) {
        # The following distinction is necessary because R segfaults if we try
        # to change `parent.env(.GlobalEnv)`. More info:
        # http://stackoverflow.com/q/22790484/1968
        if (identical(module_parent, .GlobalEnv)) {
            # FIXME: Run .onAttach?
            attach(attached_module, name = environmentName(attached_module))
            attr(pkg_env, 'attached') = environmentName(attached_module)
        }
        else
            parent.env(module_parent) = attached_module
    }

    lockEnvironment(pkg_env, bindings = TRUE)
    invisible(pkg_env)
}

# Similar to `base::requireNamespace`, but returns the package namespace,
# doesn’t swallow the error message, and without NSE shenanigans.
require_namespace = function(package) {
    ns = .Internal(getRegisteredNamespace(package))
    if (is.null(ns))
        ns = tryCatch(loadNamespace(package), error = identity)

    ns
}
library = function (...)
    suppressMessages(base::library(..., warn.conflicts = FALSE, quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
library = function (...) suppressMessages(base::library(..., quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
library = function (...) suppressMessages(base::library(..., quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data, colors) {
    data = melt(data, id.vars = NULL, variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_color_manual(values = colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	each-mode:  find args "--each"
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either each-mode [
    	do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ][
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.extract.controls <- function(basename, probes=meffil.probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=meffil.probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    ## minfi does this. shouldn't it be green, not red??????
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ext %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ext %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.Rp <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.Rp,na.rm=T)/mean(spec1.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.Gp <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.Gp,na.rm=T)/mean(spec1.R,na.rm=T)
    ## color swap vs spec1.ratio1??? just following minfi but that seems weird
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normC + normG)/(normA + normT)

    rg.bg <- background.correct(rg, probes)
    addresses <- probes.R$address[which(probes.R$target %in% c("NORM_A", "NORM_T"))]
    intensity.bc.R <- mean(rg.bg$R[addresses], na.rm = TRUE)
    addresses <- probes.G$address[which(probes.G$target %in% c("NORM_G", "NORM_C"))]
    intensity.bc.G <- mean(rg.bg$G[addresses], na.rm = TRUE)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio,
      intensity.bc.G=intensity.bc.G,
      intensity.bc.R=intensity.bc.R)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    ratios <- control.matrix["intensity.bc.G",]/control.matrix["intensity.bc.R",]
    reference <- which.min(abs(ratios-1))
    intensity <- (control.matrix["intensity.bc.G",] + control.matrix["intensity.bc.R",])[reference]/2
    list(R=intensity/control.matrix["intensity.bc.R",sample.idx],
         G=intensity/control.matrix["intensity.bc.G",sample.idx])
}


meffil.probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=meffil.probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

select.normalization.subsets <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("autosomal",quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("sex",quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
}

rg.to.mu <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=meffil.probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target %in% c("M","U") & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1

        addresses <- probes$address[which(probes$type == "control" & probes$dye == dye)]
        xc <- rg[[dye]][addresses]
        xc[which(xc <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        bg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), c(xf,xc)) + offset
        names(bg) <- c(names(xf), names(xc))
        bg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=meffil.probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- control.matrix[-grep("^intensity.bc", rownames(control.matrix)),]
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=meffil.probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-select.normalization.subsets(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=meffil.probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}

require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

meffil.extract.controls <- function(basename, probes=meffil.probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=meffil.probe.info()) {
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr == "chrX"),]
    probes.y <- probes[which(probes$chr == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        target <- quantile.sets$target[i]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$G[which(probes.G$target == "BISULFITE CONVERSION I"
                               & probes.G$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ExternalType %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ExternalType %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normA + normT)/(normC + normG)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    c(bisulfite1=bisulfite1,
      bisulfite2=bisulfite2,
      extension.G=extension.G,
      extension.R=extension.R,
      hybe=hybe,
      stain.G=stain.G,
      stain.R=stain.R,
      nonpoly.G=nonpoly.G,
      nonpoly.R=nonpoly.R,
      targetrem=targetrem,
      spec1.G=spec1.G,
      spec1.R=spec1.R,
      spec2.G=spec2.G,
      spec2.R=spec2.R,
      spec1.ratio1=spec1.ratio1,
      spec1.ratio=spec1.ratio,
      spec2.ratio=spec2.ratio,
      spec1.ratio2=spec1.ratio2,
      normA=normA,
      normC=normC,
      normT=normT,
      normG=normG,
      dye.bias=dye.bias,
      oob.G=oob.G,
      oob.ratio=oob.ratio)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    reference <- which.min(abs(control.matrix["dye.bias",]-1))
    intensity <- mean(control.matrix[c("normA","normT","normC","normG"), reference])
    list(R=intensity/mean(control.matrix[c("normA", "normT"),sample.idx]),
         G=intensity/mean(control.matrix[c("normC", "normG"),sample.idx]))
}


meffil.probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=meffil.probe.info()) {
    cbind(expand.grid(target=c("M","U"),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr="chrX",
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=c("M","U"),
                      type3=NA,
                      chr=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

eq.wild <- function(x,y) {
    is.na(y) | x == y
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(eq.wild(probes$target, quantile.sets$target[i])
                          & eq.wild(probes$type3, quantile.sets$type3[i])
                          & eq.wild(probes$chr, quantile.sets$chr[i])
                          & eq.wild(probes$chr.type, quantile.sets$chr.type[i]))]
    })
}

apply.quantile.normalization <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & eq.wild("autosomal", quantile.sets$chr.type)
     | mixture & sex == "M" & eq.wild("sex", quantile.sets$chr.type)
     | mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr)     
     #| !mixture & sex == "M" & eq.wild("autosomal",quantile.sets$chr.type)
     #| !mixture & sex == "M" & eq.wild("sex",quantile.sets$chr.type)
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("autosomal", quantile.sets$chr.type)
     | !mixture & sex == "F" & eq.wild("chrX", quantile.sets$chr))
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     #&& length(rg$R) == length(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
     ##&& all(names(rg$R) == names(rg$G)))
}

rg.to.mu <- function(rg, probes=meffil.probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=meffil.probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target != "OOB" & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        xf.bkg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), xf) + offset
        names(xf.bkg) <- names(xf)
        xf.bkg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=meffil.probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < sex.cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value in unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.cutoff <- sex.cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    ## quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=meffil.probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <-apply.quantile.normalization(object$quantile.sets,object$sex,mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

meffil.normalize.samples <- function(objects, probes=meffil.probe.info()) {
    M <- U <- NA
    for (i in 1:length(objects)) {
        msg(i)
        mu <- meffil.normalize.sample(objects[[i]], probes)
        if (i == 1) {
            U <- M <- matrix(NA_integer_,
                             nrow=length(mu$M), ncol=length(objects),
                             dimnames=list(names(mu$M), names(objects)))
        }
        M[,i] <- mu$M
        U[,i] <- mu$U
    }
    list(M=M,U=U)
}

meffil.get.beta <- function(mu) mu$M/(mu$M+mu$U+100)


compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}


####################################################
## Reshaping data
####################################################


## Sheet input interdependence
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
    if(!isEmpty(currentLayer)){
      markType <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']]
      stat <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']]
      isolate({
        # control stat choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']] <<-
          StatChoices[sapply(StatChoices, function(n) !is.null(getAesChoices(geom=markType, stat=n)))]
        # control aesthetics choices
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']] <<-
          getAesChoices(markType, stat)
      })
    }

    cc <- sheetList[[currentSheet]][['dynamicProperties']][['columns']]
    rr <- sheetList[[currentSheet]][['dynamicProperties']][['rows']]
    mDat <- sheetList[[currentSheet]][['datR']]()
    fields <- sheetList[[currentSheet]][['fieldNames']]()
    measures <- sheetList[[currentSheet]][['measuresR']]()

    cc1 <- ''; rr1 <- ''; cChoices <- ''; rChoices <- ''
    outTable <- NULL; outDf <- NULL;
    cc.measures <- ''; cc.dims <- '';
    rr.measures <- ''; rr.dims <- ''
    if(!is.null(fields)){
      dims <- setdiff.c(fields, measures)
      cc1 <- intersect(cc,dims); rr1 <- intersect(rr,dims)
      #         cc.measures <- intersect(cc1,measures); rr.measures <- intersect(rr1,measures)
      #         cc.dims <- setdiff(cc1,cc.measures); rr.dims <- setdiff(rr1,rr.measures)

      #         cc1 <- c(cc.dims,cc.measures); rr1 <- c(rr.dims,rr.measures)

      all.x <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesX']][['aesField']])
      all.y <- sapply(sheetList[[currentSheet]][['dynamicProperties']][['layerList']],
                      function(z) z[['aesList']][['aesY']][['aesField']])

      cChoices <- setdiff.c(dims, c(all.x, all.y, rr1))
      rChoices <- setdiff.c(dims, c(all.x, all.y, cc1))
      if(!isEmpty(currentLayer)){
        isolate({
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesX']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][['aesY']][['fieldChoices']] <<-
            setdiff.c(fields, c(rr1, cc1))
        })
      }


      if(!is.null(mDat)){
        outType <- (sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
        if(outType=='table'){
          #             if(combineMeasures && !is.null(facets)){
          #               outTable <- cast(mDat, facets, sum)
          #               outDf <- as.data.frame(outTable)
          #             }

        } else {

        }

        if(!is.null(outDf)){
          ## add to dataList
          isolate({
            sheetNameDat <- convertSheetNameToDatName(sheetList[[currentSheet]][['dynamicProperties']][['name']])
            if(is.null(datList[[currentSheet]])){
              datList[[currentSheet]] <<- createNewDatClassObj(outDf, name=sheetNameDat, type='sheet')
            } else {
              datList[[currentSheet]][['dynamicProperties']][['dat']] <<- outDf
              datList[[currentSheet]][['dynamicProperties']][['measures']] <<- intersect(datList[[currentSheet]][['dynamicProperties']][['measures']],
                                                                                         getDefaultMeasures(outDf))
              ## add new fields, delete outdated fields, leave common fields alone since they might have user customizations
              newFields <- getDefaultFieldsList(outDf)
              oldList <- names(datList[[currentSheet]][['dynamicProperties']][['fieldsList']])
              newList <- names(newFields)
              for(n in setdiff(newList, oldList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- newFields[[n]]
              }
              for(n in setdiff(oldList, newList)){
                datList[[currentSheet]][['dynamicProperties']][['fieldsList']][[n]] <<- NULL
              }
            }
          })
        }
      }

    }
    isolate({
      #       sheetList[[currentSheet]][['dynamicProperties']][['dat']] <<- mDat
      #       sheetList[[currentSheet]][['dynamicProperties']][['cMeasures']] <<- cc.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['cDims']] <<- cc.dims
      #       sheetList[[currentSheet]][['dynamicProperties']][['rMeasures']] <<- rr.measures
      #       sheetList[[currentSheet]][['dynamicProperties']][['rDims']] <<- rr.dims
      if(are.vectors.different(cc1, sheetList[[currentSheet]][['dynamicProperties']][['columns']])){
        triggerUpdateInput('sheetColumns')
      }
      if(are.vectors.different(rr1, sheetList[[currentSheet]][['dynamicProperties']][['rows']])){
        triggerUpdateInput('sheetRows')
      }
      sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- cc1
      sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- rr1
      sheetList[[currentSheet]][['dynamicProperties']][['colChoices']] <<- cChoices
      sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']] <<- rChoices
      sheetList[[currentSheet]][['dynamicProperties']][['outputTable']] <<- outTable
      sheetList[[currentSheet]][['dynamicProperties']][['outputDataframe']] <<- outDf
    })
  }
}, priority=1)




## Switching sheet
observe({
  v <- input$sheetList
  isolate({
    if(!isEmpty(v)) projProperties[['activeSheet']] <<- v
  })

})
observe({
  updateInput[['activeSheet']]
  updateSelectInput(session, 'sheetList', choices=(sheetListNames()),
                    selected=isolate(projProperties[['activeSheet']]))
})


## modify sheet name
observe({
  v <- input$sheetName
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      if(!isEmpty(v) && isEmpty(sheetListNames()[v])){
        ## the second condition makes sure v is different
        ## update doc's rmd
        oldName <- paste('`', sheetList[[currentSheet]][['dynamicProperties']][['name']], '`', sep='')
        newName <- paste('`', v, '`', sep='')
        sapply(names(docList), function(currentDoc){
          docList[[currentDoc]][['rmd']] <<- gsub(oldName, newName, docList[[currentDoc]][['rmd']], fixed=TRUE)
          NULL
        })
        triggerUpdateInput('docRmd')

        sheetList[[currentSheet]][['dynamicProperties']][['name']] <<- v
      }
    }
  })

})
observe({
  updateInput[['sheetName']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['name']])
  } else ''
  updateTextInput(session, 'sheetName', value=null2String(s))
})

## link sheet name to corresponding data name
observe({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    s <- sheetList[[currentSheet]][['dynamicProperties']][['name']]
    isolate({
      if(!is.null(datList[[currentSheet]])){
        datList[[currentSheet]][['dynamicProperties']][['name']] <<- convertSheetNameToDatName(s)
        triggerUpdateInput('datName')
      }
    })
  }
})

## Selecting data for sheet
observe({
  v <- input$sheetDatList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['datId']] <<- v
  })

})
observe({
  updateInput[['sheetDatId']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['datId']])
  } else ''
  choices <- datListNames()
  choices <- choices[!sapply(choices, isDatBasedonSheet, sheetId=currentSheet)]
  updateSelectInput(session, 'sheetDatList', choices=null2String(choices),
                    selected=null2String(s))
})

## whether use molten data?
observe({
  v <- input$combineMeasures
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']] <<- as.logical(v)
    }
  })

})
observe({
  updateInput[['combineMeasures']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['combineMeasures']])
  } else FALSE
  updateCheckboxInput(session, 'combineMeasures', value=null2String(s))
})

## Manipulating columns
observe({
  v <- input$columns
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['columns']] <<- v
  })

})
observe({
  updateInput[['sheetColumns']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['columns']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['colChoices']]} else ''
  updateSelectizeInput(session, 'columns', choices=null2String(choices), selected=null2String(s))
})

## Manipulating rows
observe({
  v <- input$rows
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['rows']] <<- v
  })

})
observe({
  updateInput[['sheetRows']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['rows']])
  } else ''
  choices <- if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['rowChoices']]} else ''
  updateSelectizeInput(session, 'rows', choices=null2String(choices), selected=null2String(s))
})

## Manipulating output type
observe({
  v <- input$outputTypeList
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['outputType']] <<- v
  })

})
observe({
  updateInput[['sheetOutput']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['outputType']])
  } else ''
  updateSelectInput(session, 'outputTypeList', selected=null2String(s))
})

## Selecting ggplot layer for sheet
observe({
  v <- input$layerList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- v
    }
  })
})
observe({
  updateInput[['sheetPlotLayer']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
  } else ''
  choices <- if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['layerNames']]()
  updateSelectInput(session, 'layerList', choices=null2String(choices),
                    selected=null2String(s))
})

## Selecting aesthetic
observe({
  v <- input$aesList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) {
        currentLayer <- sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']]
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['sheetLayerAes']]
  currentSheet <- projProperties[['activeSheet']]
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesChoices']])
    }
  }

  updateSelectInput(session, 'aesList', choices=null2String(choices),
                    selected=null2String(s))
})

## set aes map or set option
observe({
  v <- input$aesMapOrSet
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']] <<- v

            ## set default value
            if(v=='set' && isEmpty(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<-
                switch(currentAes,
                       'aesLabel'='My Label', 'aesFamily'='Times', 'aesFontface'='plain',
                       'aesColor'=, 'aesBorderColor'='darkblue',
                       'aesSize'=8, 'aesLineheight'=1,
                       0
                )

              triggerUpdateInput('aesValue')
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesMapOrSet']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- 'map'
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        s1 <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        if(!are.vectors.different('set', s1)) s <- 'set'
      }
    }
  }
  updateRadioButtons(session, 'aesMapOrSet', selected=s)
})

## map or set UI
output$mapOrSetUI <- renderUI({
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        useMapping <- are.vectors.different('set',
                                            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesMapOrSet']])
        isolate({
          aes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]]
          if(useMapping){
            s <- null2String(aes[['aesField']])
            choices <- if(currentAes %in% c('aesX','aesY')) {
              aes[['fieldChoices']]
            } else {
              sheetList[[currentSheet]][['fieldNames']]()
            }
            if(!(s %in% choices)) choices[s]=s ## this is needed when s="", otherwise selected will defaults to the first value

            aggFun <- null2String(aes[['aesAggFun']])
            aggFunchoices <- YFunChoices
            if(!(aggFun %in% aggFunchoices)) aggFunchoices[aggFun]=aggFun

            fluidRow(
              column(4,
                     selectizeInput(inputId='aesField', label='Field',
                                    choices=choices, selected=s, multiple=FALSE,
                                    options = list(create = TRUE))
              ),
              column(4,
                     checkboxInput(inputId='aesAggregate', label='Aggregate Field',
                                   value=aes[['aesAggregate']]),
                     conditionalPanel('input.aesAggregate==true',
                                      selectizeInput(inputId='aesAggFun', label='By',
                                                     choices=aggFunchoices,
                                                     selected=aggFun, multiple=FALSE,
                                                     options = list(create = TRUE))
                     )

              ),
              column(4,
                     conditionalPanel('output.canAesFieldBeContinuous==true',
                                      radioButtons('aesDiscrete', 'Treat Field as',
                                                   choices=c('Continuous'='continuous',
                                                             'Discrete'='discrete'),
                                                   selected=ifelse(aes[['aesDiscrete']], 'discrete', 'continuous'),
                                                   inline=FALSE)
                     )


              )
            )
          } else {
            switch(currentAes,
                   'aesLabel'=textInput('aesValue', '', value=aes[['aesValue']]),
                   'aesFontface'=selectInput('aesValue','',choices=FontFaceChoices, selected=aes[['aesValue']]),
                   'aesFamily'=selectInput('aesValue','',choices=FontFamilyChoices, selected=aes[['aesValue']]),
                   'aesColor'=, 'aesBorderColor'=NULL,
                   numericInput('aesValue', 'Value', value=aes[['aesValue']], step=0.1)
            )
          }
        })
      }
    }
  }
})

## set aesValue
observe({
  v <- input$aesValue
  vColor <- input$aesValueColor
  ## using isEmpty instead of is.null below will cause aesValue not being able to be deleted by user
  ## not ideal, but due to the inability of setting value on jscolorPicker
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          if((currentAes=='aesColor' || currentAes=='aesBorderColor') && !isEmpty(vColor)) v <- paste('#', vColor, sep='')
          if(!isEmpty(v)) sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']] <<- v
        }
      }
    }
  })

})
# observe({
#   updateInput[['aesValue']]
#   currentSheet <- (projProperties[['activeSheet']])
#   s <- 0
#   if(!isEmpty(currentSheet)){
#     currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
#     if(!isEmpty(currentLayer)){
#       currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
#       if(!isEmpty(currentAes)){
#         s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesValue']])
#         switch(currentAes,
#                'aesLabel'=updateTextInput(session, 'aesValue', value=s),
#                'aesFamily'=, 'aesFontface'=updateSelectInput(session, 'aesValue', selected=s),
#                'aesColor'=, 'aesBorderColor'=
#                  NULL, # no update jscolorInput available
#
#                updateNumericInput(session, 'aesValue', value=s)
#         )
#       }
#     }
#   }
#
# })

## set aes field
observe({
  v <- input$aesField
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']])){
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']] <<- v

              ## set default field properties
              if(isEmpty(v) && currentLayer != 'Plot'){
                v <- null2String(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']][['aesList']][[currentAes]][['aesField']])
              }
              is.measure <- v %in% sheetList[[currentSheet]][['measuresR']]()
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']] <<-
                is.measure  ## just for capturing this information to customize choices for agg fun
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- is.measure
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- if(is.measure) 'sum' else 'length'
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- !is.measure
              sapply(c('aesAggregate','aesAggFun','aesDiscrete'), triggerUpdateInput)

              ## set default xlab, ylab
              if(!isEmpty(v)){
                fieldNames <- sheetList[[currentSheet]][['fieldNames']]()
                i.match <- match(v, fieldNames)
                if(!is.na(i.match)){
                  fieldName <- names(fieldNames)[i.match]
                  switch(currentAes,
                         'aesX'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']] <<- fieldName
                           triggerUpdateInput('plotXlab')
                         },
                         'aesY'={
                           sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']] <<- fieldName
                           triggerUpdateInput('plotYlab')
                         }
                         )

                }
              }

            }
          }
        }
      }
    })
  }

})
# observe({
#   updateInput[['aesField']]
#   currentSheet <- (projProperties[['activeSheet']])
#   s <- choices <- ''
#   if(!isEmpty(currentSheet)){
#     currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
#     if(!isEmpty(currentLayer)){
#       currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
#       if(!isEmpty(currentAes)){
#         s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesField']])
#         choices <- if(currentAes %in% c('aesX','aesY')) {
#           sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['fieldChoices']]
#         } else {
#           sheetList[[currentSheet]][['fieldNames']]()
#         }
#       }
#     }
#   }
#
#   updateSelectizeInput(session, 'aesField', choices=null2String(choices), selected=null2String(s))
# })

output$canAesFieldBeContinuous <- reactive({
  ans <- FALSE
  currentSheet <- (projProperties[['activeSheet']])
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
      if(!isEmpty(currentAes)){
        ans <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['canFieldBeContinuous']]()
      }
    }
  }
  ans
})
outputOptions(output, "canAesFieldBeContinuous", suspendWhenHidden=FALSE)

## set aes aggregate
observe({
  v <- input$aesAggregate
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']] <<- v
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesAggregate']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- FALSE
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggregate']])

        }
      }
    }
    updateCheckboxInput(session, 'aesAggregate', value=s)
  })

})


## set aes agg fun
observe({
  v <- input$aesAggFun
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['aesAggFun']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- ''
    choices <- YFunChoices
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          s <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesAggFun']]
          is.measure <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesIsFieldMeasure']]
          if(!is.null(is.measure) && !is.measure) choices <- AggFunChoicesDimension
        }
      }
    }

    if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
    updateSelectizeInput(session, 'aesAggFun', choices=null2String(choices), selected=null2String(s))
  })
})

## set aes discrete
observe({
  v <- input$aesDiscrete
  if(!is.null(v)){
    isolate({
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
          if(!isEmpty(currentAes)){
            isDiscrete <- (v=='discrete')
            if(currentAes %in% c('aesX', 'aesY')){
              ## can't mix discrete with continuous scales on x or y, so need to keep all layers the same
              for(layer in names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])){
                sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
              }
            } else {
              sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']] <<- isDiscrete
            }
          }
        }
      }
    })
  }

})
observe({
  updateInput[['aesDiscrete']]
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    s <- 'discrete'
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        currentAes <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['activeAes']]
        if(!isEmpty(currentAes)){
          d <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['aesList']][[currentAes]][['aesDiscrete']])
          if(!isEmpty(d) && !d){
            s <- 'continuous'
          }

        }
      }
    }
    updateRadioButtons(session, 'aesDiscrete', selected=s)
  })
})

## set Mark Type / geom
observe({
  v <- input$markList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']] <<- v
          # set default stat type & position
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<-
            switch(v, 'boxplot'='boxplot', 'identity')
          triggerUpdateInput('layerStatType')
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<-
            switch(v, 'bar'='dodge', 'identity')
          triggerUpdateInput('layerPositionType')
        }
      }
    }
  })
})
observe({
  updateInput[['layerGeom']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geom']])
      #choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['geomChoices']])
    }
  }
  updateSelectInput(session, 'markList', selected=null2String(s))
})

## set Stat Type
observe({
  v <- input$statTypeList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){

          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerStatType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- choices <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statType']])
      choices <- (sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['statChoices']])
    }
  }

  updateSelectInput(session, 'statTypeList', choices=null2String(choices), selected=null2String(s))
})

## set y fun
observe({
  v <- input$yFunList
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']] <<- v
        }
      }
    }
  })
})
observe({
  updateInput[['layerYFun']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['yFun']])
    }
  }
  choices <- YFunChoices
  if(!isEmpty(s) && !(s %in% choices)) choices[s]=s
  updateSelectizeInput(session, 'yFunList', choices=null2String(choices), selected=null2String(s))
})



## set PositionType
observe({
  v <- input$layerPositionType
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionType']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionType']])
    }
  }
  updateSelectizeInput(session, 'layerPositionType', selected=null2String(s))
})

## set Position Height
observe({
  v <- empty2NULL(as.numeric(input$layerPositionHeight))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionHeight']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionHeight']])
    }
  }
  updateTextInput(session, 'layerPositionHeight', value=null2String(s))
})

## set Position Width
observe({
  v <- empty2NULL(as.numeric(input$layerPositionWidth))
  isolate({
    currentSheet <- (projProperties[['activeSheet']])
    if(!isEmpty(currentSheet)){
      currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
      if(!isEmpty(currentLayer)){
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']] <<- v
      }
    }
  })

})
observe({
  updateInput[['layerPositionWidth']]
  currentSheet <- (projProperties[['activeSheet']])
  s <- ''
  if(!isEmpty(currentSheet)){
    currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
    if(!isEmpty(currentLayer)){
      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]][['layerPositionWidth']])
    }
  }
  updateTextInput(session, 'layerPositionWidth', value=null2String(s))
})




tabS <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
                   (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )
canLatexPNG <- tryCatch(length(make.png(tabS)), error=function(e) FALSE)


output$sheetOutput <- renderUI({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    switch(sheetList[[currentSheet]][['dynamicProperties']][['outputType']],
           'table'=if(canLatexPNG) imageOutput('sheetOutputTable') else {
             tags$div(
               HTML(paste(capture.output(Hmisc::html(sheetList[[currentSheet]][['tableR']]())), collapse=" "))
             )
           },
           'plot'=plotOutput('ggplot'))
  }

})


output$sheetOutputTable <- renderImage(if(canLatexPNG) {
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){
    tab <- sheetList[[currentSheet]][['tableR']]()

    if(!is.null(tab)){
      #width  <- session$clientData$output_test_width
      #height <- session$clientData$output_test_height

      # For high-res displays, this will be greater than 1
      pixelratio <- session$clientData$pixelratio
      fileName <- make.png(tab, resolution=72*pixelratio)
      pngFile <- readPNG(fileName)

      # Return a list containing the filename
      list(src = normalizePath(fileName),
           width = dim(pngFile)[2],
           height = dim(pngFile)[1],
           alt = "Output not available")
    }
  }
}, deleteFile = TRUE)

# x <- tabular( (Species + 1) ~ (n=1) + Format(digits=3)*
#                 (Sepal.Length + Sepal.Width)*(mean + Justify(r)*sd), data=iris )
# tags$div(
#   HTML(paste(capture.output(Hmisc::html(x)), collapse=" "))
# )

## Reshaped output
output$reshapedDat <- renderTable({
  currentSheet <- projProperties[['activeSheet']]
  if(!isEmpty(currentSheet)){sheetList[[currentSheet]][['dynamicProperties']][['outputTable']]}
})

output$ggplot <- renderPlot({
  if(input$autoRefresh=='refresh'){
    currentSheet <- projProperties[['activeSheet']]
    if(!isEmpty(currentSheet)){
      sheetList[[currentSheet]][['plotR']]()
    }
  } else {
    gg <- last_plot()
    if(!is.null(gg)) gg <- gg  + theme_grey()
    gg
  }

})



## add Layer
observe({
  v <- input$addLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        existingNames <- names(sheetList[[currentSheet]][['dynamicProperties']][['layerList']])
        layerName <- make.unique(c(existingNames, 'Overlay'), sep='_')[length(existingNames)+1]

        newLayer <- createNewLayer()
        sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]] <<- newLayer
        sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- layerName

        #copy from Plot layer
        plotLayer <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][['Plot']]
        names1 <- names(plotLayer)
        for(n1 in names1){
          if(n1=='aesList'){
            names2 <- names(plotLayer[[n1]])
            for(n2 in names2){
              names3 <- names(plotLayer[[n1]][[n2]])
              for(n3 in names3){
                if(n3 != 'aesField' && typeof(plotLayer[[n1]][[n2]][[n3]]) != 'closure'){#
                  sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]][[n2]][[n3]] <<- plotLayer[[n1]][[n2]][[n3]]
                }
              }
              setAesReactives(currentSheet, layerName, n2)
            }
          } else {
            sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[layerName]][[n1]] <<- plotLayer[[n1]]
          }
        }

      }
    }
  })
})
## delete Layer
observe({
  v <- input$deleteLayer
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer) && currentLayer!='Plot'){
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']] <<- 'Plot'
        }
      }
    }
  })
})
## bring Layer to top
observe({
  v <- input$bringToTop
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        currentLayer <- (sheetList[[currentSheet]][['dynamicProperties']][['activeLayer']])
        if(!isEmpty(currentLayer)){
          temp <- sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]]
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- NULL
          sheetList[[currentSheet]][['dynamicProperties']][['layerList']][[currentLayer]] <<- temp
        }
      }
    }
  })
})

## add sheet
observe({
  v <- input$addSheet
  isolate({
    if(v){
      addSheet()
    }
  })
})
## delete sheet
observe({
  v <- input$deleteSheet
  isolate({
    if(v){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)){
        sheets <- names(sheetList)
        i <- match(currentSheet, sheets)
        sheetList[[currentSheet]] <<- NULL
        projProperties[['activeSheet']] <<- ifelse(length(sheets)>i, sheets[i+1],
                                                   ifelse(i>1, sheets[i-1], ''))
      }
    }
  })
})

#' Load a bunch of dependencies by filename
#' 
#' This is useful for reducing pollution in the global namespace,
#' and not loading multiple files twice unnecessarily.
#'
#' @export
#' @param ... see examples.
#' @param envir environment. The parent environment to use when calling
#'   \code{base::source} to fetch dependencies.
#' @param local logical. If \code{TRUE} and \code{envir} is missing,
#'   it will set \code{envir = parent.frame()}.
#' @examples
#' \dontrun{
#' helper_fn <- define('some/dir/helper_fn')
#' define(c('some/dir/helper_fn', 'some/other_dir/library_fn'), function(helper_fn, library_fn) { ... }
#' helper_fns <<- define('some/dir/helper_fn1', 'some/otherdir/helper_fn2')
#' helper_fns[[1]]('do something'); helper_fns[[2]]('do something else')
#' }
define <- (function() {
  number_of_required_arguments <- function(fn) {
    function_has_variable_number_of_arguments <- '...' %in% names(formals(fn))
    if (function_has_variable_number_of_arguments) return(NA_real_)
    function_arguments <- formals(fn)
    required_arguments <- sapply(function_arguments, class) == 'name'
    sum(required_arguments)
  }

  process_function_with_no_dependencies <- function(fn) {
    number_of_arguments <- number_of_required_arguments(fn)
    if (number_of_arguments == 0) fn()
    else if (number_of_arguments == 1) fn(define)
    else stop("Ramd::define only processes functions with <= 1 ",
              "arguments if no dependencies are given, but the ",
              "passed function has ", number_of_required_arguments, 
              " required arguments")
  }

  flatten <- function(lists) {    
    atomic_vector <- unlist(c(lists))
    delimited_string <- paste(atomic_vector, collapse = ' ')
    strsplit(delimited_string, '[^a-zA-Z0-9.-_`:\\\\\\/]+')[[1]]
  }

  parse_dependencies <- function(arguments) {
    cd <- current_directory()
    if (any(sapply(arguments, class) != 'character'))
      stop("Ramd::define only accepts atomic character vectors for ",
           "specifying dependencies")
    dependencies <- unlist(c(arguments))
    if ('Ramd.no_flatten' %in% names(.Options) &&
        getOption('Ramd.no_flatten')) dependencies
    else flatten(dependencies)
  }

  fetch_dependencies <- function(arguments, envir) {
    dependency_names <- parse_dependencies(arguments)
    dependencies <- lapply(dependency_names, load_dependency, envir = envir)
    names(dependencies) <- dependency_names
    dependencies
  }

  verify_number_of_required_arguments_matches_number_of_dependencies <-
    function(fn, number_of_dependencies) {
      num_of_required_arguments <- number_of_required_arguments(fn)
      if (is.na(num_of_required_arguments)) return(TRUE)
      if (num_of_required_arguments != number_of_dependencies)
        stop("Ramd::define was not able to load dependencies because ",
             number_of_dependencies, " dependenc",
             # Pluralization, for fun!
             if (number_of_dependencies == 1) 'y was' else 'ies were',
             " passed in but the given function has ",
             num_of_required_arguments, " required argument",
             if (num_of_required_arguments == 1) '' else 's')
      TRUE
    }

  function(..., envir = parent.env(topenv()), local) {
    if (!missing(local) && isTRUE(local)) {
      envir <- parent.frame()
    }

    arguments <- list(...)
    if ('packages' %in% names(arguments)) {
      if (length(arguments) == 1)
        stop("Ramd::define does more than just load packages, ",
             "please provide some dependencies or a function. ",
             "To just load packages, use Ramd::packages")
      packages(arguments$packages)
      arguments <- arguments[names(arguments) != 'packages']
    }

    fn <- tail(arguments, 1)[[1]]
    valid_function <- is.function(fn)
    if (valid_function) {
      dependencies <- head(arguments, -1)
      if (length(dependencies) == 0)
        return (process_function_with_no_dependencies(fn))
    } else dependencies <- arguments

    if (valid_function)
      verify_number_of_required_arguments_matches_number_of_dependencies(
        fn, length(unlist(dependencies)))

    dependencies <- fetch_dependencies(dependencies, envir = envir)
    if (valid_function) do.call(fn, unname(dependencies))
    else dependencies
  }

})()
require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit

## autosomes,X,Y
## all,autosomes,XY,X

meffil.extract.controls <- function(basename, probes=probe.info()) {
    msg("sample file", basename)
    rg <- read.rg(basename)
    extract.controls(rg, probes)
}

meffil.compute.normalization.object <- function(basename, control.matrix,
                                                number.quantiles=500,
                                                probes=probe.info()) {
    
    sample.idx <- match(basename, colnames(control.matrix))
    stopifnot(!is.na(sample.idx))
    dye.bias.factors <- calculate.dye.bias.factors(control.matrix, sample.idx)
        
    rg <- read.rg(basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, dye.bias.factors$R, dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    probes.x <- probes[which(probes$chr.type == "chrX"),]
    probes.y <- probes[which(probes$chr.type == "chrY"),]
    x.signal <- median(log(mu$M[probes.x$name] + mu$U[probes.x$name], 2), na.rm=T)
    y.signal <- median(log(mu$M[probes.y$name] + mu$U[probes.y$name], 2), na.rm=T)

    probs <- seq(0,1,length.out=number.quantiles)
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$names <- get.quantile.probe.sets(quantile.sets)
    quantile.sets$quantiles <- sapply(1:nrow(quantile.sets), function(i) {
        probe.names <- quantile.sets$names[[i]]
        quantile(mu[[target]][probe.names], probs=probs, na.rm=T)   
    })
    quantile.sets$names <- NULL

    list(origin="meffil.compute.normalization.object",
         basename=basename,
         quantile.sets=quantile.sets,
         dye.bias.factors=dye.bias.factors,
         x.signal=x.signal,
         y.signal=y.signal)         
}

msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

extract.controls <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$G[which(probes.G$target == "BISULFITE CONVERSION I"
                               & probes.G$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ExternalType %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ExternalType %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normA + normT)/(normC + normG)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    model.matrix <- c(bisulfite1=bisulfite1,
                      bisulfite2=bisulfite2,
                      extension.G=extension.G,
                      extension.R=extension.R,
                      hybe=hybe,
                      stain.G=stain.G,
                      stain.R=stain.R,
                      nonpoly.G=nonpoly.G,
                      nonpoly.R=nonpoly.R,
                      targetrem=targetrem,
                      spec1.G=spec1.G,
                      spec1.R=spec1.R,
                      spec2.G=spec2.G,
                      spec2.R=spec2.R,
                      spec1.ratio1=spec1.ratio1,
                      spec1.ratio=spec1.ratio,
                      spec2.ratio=spec2.ratio,
                      spec1.ratio2=spec1.ratio2,
                      normA=normA,
                      normC=normC,
                      normT=normT,
                      normG=normG,
                      dye.bias=dye.bias,
                      oob.G=oob.G,
                      oob.ratio=oob.ratio)
}

calculate.dye.bias.factors <- function(control.matrix,sample.idx) {
    reference <- which.min(abs(control.matrix["dye.bias",]-1))
    intensity <- mean(control.matrix[c("normA","normT","normC","normG"), reference])
    list(R=intensity/mean(control.matrix[c("normA", "normT"),sample.idx]),
         G=intensity/mean(control.matrix[c("normC", "normG"),sample.idx]))
}


probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])

    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    ret$chr.type <- ifelse(is.na(ret$chr), NA, "autosomal")
    ret$chr.type[which(ret$chr %in% c("chrX","chrY"))] <- "sex"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}

define.quantile.probe.sets <- function(probes=probe.info()) {
    cbind(expand.grid(target=names(mu),
                      type3=c("iG","iR","ii"),
                      chr=NA,
                      chr.type=c(NA,"autosomal"),
                      stringsAsFactors=F),
          expand.grid(target=names(mu),
                      chr="chrX",
                      type3=NA,
                      chr.type="sex",
                      stringsAsFactors=F),
          expand.grid(target=names(mu),
                      chr=NA,
                      type3=NA,
                      chr.type="sex",
                      stringsAsFactors=F))
}

get.quantile.probe.sets <- function(quantile.sets) {
    lapply(1:nrow(quantile.sets), function(i) {
        probes$name[which(probes$target == quantile.sets$target[i]
                          & probes$type3 == quantile.sets$type3[i]
                          & probes$chr == quantile.sets$chr[i]
                          & probes$chr.type == quantile.sets$chr.type[i])]
    })
}

apply.quantile.normalization <- function(quantile.sets, sex="M", mixture=T) {
    (mixture & quantile.sets$chr.type %in% "autosomal"
     | mixture & sex == "M" & quantile.sets$chr.type %in% "sex"
     | mixture & sex == "F" & quantile.sets$chr %in% "chrX"
     | !mixture & sex == "M" & is.na(quantile.sets$chr.type)
     | !mixture & sex == "F" & quantile.sets$chr.type %in% "autosomal"
     | !mixture & sex == "F" & object$quantile.sets$chr %in% "chrX")
}
 
read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     #&& length(rg$R) == length(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
     ##&& all(names(rg$R) == names(rg$G)))
}

rg.to.mu <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target != "OOB" & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        xf.bkg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), xf) + offset
        names(xf.bkg) <- names(xf)
        xf.bkg
    })
}

dye.bias.correct <- function(rg, factor.R, factor.G) {
    rg$R <- rg$R * factor.R
    rg$G <- rg$G * factor.G
    rg
}

is.normalization.object <- function(object) {
    (all(c("quantile.sets","dye.bias.factors","origin","basename","x.signal","y.signal")
         %in% names(object))
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize.objects <- function(objects, control.matrix, 
                                    number.pcs=2, sex.cutoff=-2, sex=NULL,
                                    probes=probe.info()) {
    stopifnot(length(objects) == ncol(control.matrix))
    stopifnot(is.null(sex) || length(sex) == length(objects) && all(sex %in% c("F","M")))
    stopifnot(number.pcs >= 2)

    msg("cleaning up the control matrix")
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    if (is.null(sex)) {
        msg("predicting sex")
        x.signal <- sapply(objects, function(obj) obj$x.signal)
        y.signal <- sapply(objects, function(obj) obj$y.signal)
        xy.diff <- y.signal-x.signal
        sex <- ifelse(xy.diff < cutoff, "F","M")
    }
    
    msg("normalizing quantiles")
    quantile.sets <- define.quantile.probe.sets(probes)
    quantile.sets$sex.diff <- (length(unique(sex)) >= 2
                               & with(quantile.sets, !is.na(chr.type) & chr.type != "autosomal"))
    normalized.quantiles <- lapply(1:nrow(quantile.sets), function(i) {
        original <- sapply(objects, function(obj) obj$quantile.sets$quantiles[[i]])        
        if (quantile.sets$sex.diff[i]) {
            norm <- original
            for (sex.value %in% unique(na.omit(sex))) {
                sample.idx <- which(sex == sex.value)
                norm[,sample.idx] <- normalize.quantiles(original[,sample.idx],
                                                         control.matrix[,sample.idx], number.pcs)
            }
            norm
        }
        else            
            normalize.quantiles(original, control.matrix, number.pcs)            
    })
    
    for (i in 1:length(objects)) {
        objects[[i]]$sex.threshold <- cutoff
        objects[[i]]$xy.diff <- xy.diff[i]
        objects[[i]]$sex <- sex[i]
        objects[[i]]$quantile.sets$sex.diff <- quantile.sets$sex.diff
        objects[[i]]$quantile.sets$norm <- lapply(normalized.quantiles,
                                                  function(sample.quantiles) sample.quantiles[,i])
    }
    objects
}



impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    ## quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


meffil.normalize.sample <- function(object, probes=probe.info()) {
    stopifnot(is.normalization.object(object))

    probe.names <- unique(na.omit(probes$name))

    U <- M <- rep(NA_integer_, length(probe.names))
    names(U) <- names(M) <- probe.names

    rg <- read.rg(object$basename)
    rg.correct <- background.correct(rg, probes)
    rg.correct <- dye.bias.correct(rg.correct, object$dye.bias.factors$R, object$dye.bias.factors$G)
    mu <- rg.to.mu(rg.correct, probes)

    mu$M <- mu$M[probe.names]
    mu$U <- mu$U[probe.names]

    object$quantile.sets$names <- get.quantile.probe.sets(object$quantile.sets)
    mixture <- sum(object$quantile.sets$sex.diff) == 0
    object$quantile.sets$apply <- apply.quantile.normalization(quantile.sets, object$sex, mixture)

    for (i in which(object$quantile.sets$apply)) {
        target <- object$quantile.sets$target[i]
        probe.idx <- which(names(mu[[target]]) %in% object$quantile$names[[i]])

        orig.signal <- mu[[target]][probe.idx]
        norm.target <- compute.quantiles.target(object$quantile.sets$norm[[i]])
        norm.signal <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal),
                                                                      norm.target)
        mu[[target]][probe.idx] <- norm.signal
    }
    mu
}

compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
}   


#############.....................################
check.sex <- function(xy.diff) {
    fit <- kmeans(xy.diff, centers=range(xy.diff))
    sex.kmeans <- ifelse(fit$cluster == which.min(fit$centers), "F", "M")        
}

## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='', selectize=FALSE, size=3)),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(4,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL, selectize=FALSE, size=15)
                                   ),
                            column(8,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map', inline=TRUE)
                                                    ),

                                   uiOutput('mapOrSetUI'),
                                   conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                                    jscolorInput('aesValueColor'))
                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          textInput('plotTitle', 'Plot Title'),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem', search=TRUE)
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    strong('Font Color'), br(),
                                                    jscolorInput('textColor'), br(),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    strong('Border Color'), br(),
                                                    jscolorInput('rectColor'), br(),
                                                    strong('Fill'), br(),
                                                    jscolorInput('rectFill'), br(),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    strong('Line Color'), br(),
                                                    jscolorInput('lineColor'), br(),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   )

                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

#homeDir<-"//home/user/ENVIRONMENT/workspaces/workspace_scala/FarringtonTest/"
#fileDir<-"EDS"
#outDir<-paste(homeDir, "results", sep="")
#setwd(paste(homeDir,fileDir,sep=""))

require(rjson)

#allData = as.data.frame(fromJSON(readLines("tmp.json")))

#######################################################
## DISPERSION 
## This function estimates the dispersion parameter using the formula described in Farrington #(1996)
#######################################################

disp<-function(i){
	calc<-numeric(baselineNum)
	i<-1
	while(i<baselineNum+1){
		ifelse(expected[i]<1*10^(-150), calc[i]<-1*10^(-150), calc[i]<-w[i]*(((basecont[i]-expected[i])^2)/expected[i]))
		i<-i+1
	}
	calc
}

########Model can not cope with expected[i] being too small and crashes (produces #NAN's).
########As it rounds it off and effectively tries to divide by zero
########Therefore I have set expected[i] to be an extremely small number in the #event that it is effectively zero
########THis will not effect the validity of the results 

###################################################
## DERIVE RESIDUALS	 
## This code is used to derive the anscombe residuals which are used as part of the re-weighting 
## procedure in accounting for past outbreaks. The formula is described in Farrington #(1996)
###################################################

residuals <- function(i){
	b<-numeric(baselineNum)
	i<-1
	model<-glm(formula=basecont~basemth, family=quasipoisson(link=log), weights=w, data=basedata)
	hat<-lm.influence(model)$hat
	while(i<baselineNum+1){     
		ifelse(expected[i]<1*10^(-150),b[i]<-1*10^(-150),b[i]<-(3/(2*(dispersion)^(1/2)))*(((basecont[i])^(2/3))-((expected[i])^(2/3)))/(((expected[i])^(1/6))*((1-hat[i])^(1/2))))
		i<-i+1
	}
	b
}

#########Model can not cope with expected[i] being too small and crashes (produces NAN's).
#########As it rounds it off and effectively tries to divide by zero
#########Therefore I have set expected[i] to be an extremely small number in the event that it is effectively zero
#########THis will not effect the validity of the results 

###################################################
## DERIVE WEIGHTS - PART 1	 
##
## This code is used to derive the first part of the weighting formula, namely to determine the #number
## of times that the residuals are <1. These are summed up in the main body of the algorithm. #Part 1 
## is used to calculate y which is then used in the final calculation of the weights.
###################################################


xconstant <- function(i){
	c<-numeric(baselineNum)
	i<-1
	while(i<baselineNum+1){
		c[i]<-if(residuals1[i]<1) 1 else 0
		i<-i+1
	}
	c
}

###################################################
## DERIVE WEIGHTS - PART 2	 
##
## This code is used to calculate the (residuals)^-2 when the residual(i) <1. These values are #summed up 
## in the main body of the algorithm. Part 2 is used to calculate y which is then used in the #final 
## calculation of the weights.
####################################################

constant1 <- function(i){
	c<-numeric(baselineNum)
	i<-1 
	while (i<baselineNum+1){
		c[i]<-if(residuals1[i]<1) ((residuals1[i]^-2)) else 0
		i<-i+1
	}
	c
}

###################################################
## DERIVE WEIGHTS - PART 3	 
##
## This code is used to derive the final weighting calculation. For each baseline data point, a #weight
## is calculated depending upon if the residuals are <1. 
###################################################

weights <-function(i){
	w2<-numeric(baselineNum)
	i<-1
	while(i<baselineNum+1){
		w2[i]<-if(residuals1[i]<1) (y*(residuals1[i]^-2)) else y
		i<-i+1
	}
	w2
}

###################################################
## DERIVE THRESHOLD VALUES	 
##
## This code is used to derive the threshold values using the formula described in Farrington #1996. 
## Two weights are derived -  "threshold" if the linear trend is included and "threshold2" if the
## the linear trend is not significant.
###################################################

#calculation if model is to include linear trend
threshold <-function(z){
	var<-varalpha+(currentmth*currentmth)*varbeta+(2*currentmth*covariance)
	tao<-(dispersion*expectedc+var)/(expectedc^2)
	U<-expectedc*(1+(2/3)*z*(tao^0.5))^(3/2)
	U
}

#calculation if not include linear trend
threshold2 <- function(z){
	var<-varalpha
	tao<-(dispersion*expectedc+var)/(expectedc^2)
	U<-expectedc*(1+(2/3)*z*(tao^0.5))^(3/2)
	U
}

###########################################################################
###				MAIN MODEL				
###########################################################################

#allData = read.csv("/home/user/ENVIRONMENT/workspaces/workspace_scala/FarringtonTest/results/baselineData.txt")
#allData = as.data.frame(fromJSON(paste(readLines("r-in.json"), collapse="")))

baselineNum = nrow(basedata)
#baseData = allData[1:baselineNum,]
#currentCount = allData[nrow(allData),"Incidents"]
#currentmth = allData[nrow(allData), "MonthNum"]
basemth = basedata$basemth
basecont = basedata$basecont

#basedata<-data.frame(basecont, basemth)
# currentc<-Data2[currentmth, 2+2]  	#LEAVE AS [,2+2] so only look at INCIDENTS. If wish to look at isolations change to [,1+1]. 

w<-rep(1,times=nrow(basedata))					#Set weights = 1 

#---calculate weights----------------
model<-glm(formula=basecont~basemth, family=quasipoisson(link=log), weights=w, data=basedata)	#Fit model
param<-coef(model)
expected<-exp(param[1]+(basemth*param[2]))		#Estimate expected values
expectedc<-exp(param[1]+(currentmth*param[2]))	#Estimate expected value for current month
coeff<-summary(model)$coeff
varalpha<-coeff[1,2]*coeff[1,2]
varbeta<-coeff[2,2]*coeff[2,2]
cova<-vcov(model)					#Covariance matrix
covariance<-cova[1,2]
p<-2						#Number of esitmated parameters
trend=1          #denotes trend is included
calc<-sum(disp())					#First calculation of dispersion parameter
calc2<-1/(baselineNum-p)
dispersion<-if((calc2*calc)>1) calc2*calc else 1		#Calculate dispersion parameter final
residuals1<-residuals()				#Estimate the residuals
m<-sum(xconstant())
k<-constant1()
y<-baselineNum/(sum(k)+(baselineNum-m))				#Calculate the weights
w<-weights()					#Obtain the weights vector for baseline data

#----refit model with weights--------------------
model<-glm(formula=basecont~basemth, family=quasipoisson(link=log), weights=w, data=basedata)
param<-coef(model)
expected<-exp(param[1]+(basemth*param[2]))		#Estimate expected values again
expectedc<-exp(param[1]+(currentmth*param[2]))	#Estimate expected value for current month again	
coeff<-summary(model)$coeff
varalpha<-coeff[1,2]*coeff[1,2]
varbeta<-coeff[2,2]*coeff[2,2]
cova<-vcov(model)					#Covariance matrix
covariance<-cova[1,2]
calc<-sum(disp())					#Calculate the first part of dispersion parameter again
calc2<-1/(baselineNum-p)
dispersion<-if((calc2*calc)>1) calc2*calc else 1		#Recalculate the dispersion parameter
tvalue<-coeff[2]/coeff[2,2]		#T-value for beta
df<-baselineNum-p-1						#Degrees freedom

ttest<-qt(0.95,df)					#T-test for the significance of linear trend
z<-1.96  
U<-threshold(z)		#Calculate the threshold 

if (!( (tvalue>ttest | tvalue < -ttest) & expectedc<=max(basecont)))  { 
	#----fit model with no linear trend-----------------------------
	model<-glm(formula=basecont~1, family=quasipoisson(link=log), weights=w, data=basedata)  #model with no linear trend
	expected<-expected*0+exp(coef(model))
	expectedc<-exp(coef(model))
	trend="noTrend"
	p<-1
	calc<-sum(disp())
	calc2<-1/(n-p)
	dispersion<-if((calc2*calc)>1) calc2*calc else 1  	#Final calculation of dispersion parameter
	U<-threshold2(z)
}

if(expectedc<0.1) U<-1.9                 #threshold starts to increase if expected<0.1 - so fix at value << 2 => if get two cases then raise flag.
if (currentCount==0) {
	expectedc<-0 
	U<-0 
}
thresh<-U
exceed<-(currentCount-expectedc)/(U-expectedc)
if (U==0) exceed<-0 else exceed<-exceed

ifelse(sum(basecont)==0&&currentc>0,exceed<-'>1',exceed<-exceed)

output = toJSON(list(
				"expected" = expectedc[[1]],
				"threshold" = thresh[[1]],
				"trend" = trend,
				"exceed" = exceed[[1]],
				"weights" = w
		))# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            names(dimnames(l.[[i]])) = dimnames[1:length(dim(l.[[i]]))]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=names(l.)[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>% #TODO: use b$match here instead
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = base::match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
source("colors.r")

#
# OUTLINE
#

# every plot function in this file makes IMHO nice formatted plots in four steps

# 1. Plot an empty plot, to inform R about ranges of data (grid needs this)
# 2. Plot background and grid
# 3. Plot data
# 4. Plot axes, box and titles

################################################################################

# Helper function for leaving out unused margins
doMargins <- function(mainTitle, xTitle, yTitle) {
  margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)
}

################################################################################

# Helper function for plotting axes and title on top of plot
doBoxTitleAndAxes <- function(mainTitle, xTitle, yTitle) {
  box(col = thillux_grey[1], bty="l")
  title(main=mainTitle, col=thillux_grey[1], xlab=xTitle, ylab=yTitle)
  axis(1, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
  axis(2, col="#00000000", col.axis = thillux_grey[1], col.ticks = thillux_grey[1])
}

################################################################################

# Helper function for creating PDF devices
doOpenPDF <- function(pdfFile, pdfTitle) {
  pdfFilePath = "out.pdf"
  if(!is.null(pdfFile)) {
    pdfFilePath = pdfFile
  }
  pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)
}

################################################################################

# Helper function for plotting background and grid, before plotting on top of it
doPlotBackgroundAndGrid <- function() {
  u <- par("usr")
  rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)
  par(col.lab=thillux_grey[1])
  grid(col=thillux_grey[1], lty=3, lwd=0.5)
}

################################################################################

plotHistogram <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      lty=1,
      cex=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotHistogramNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    h$counts <- h$counts/sum(h$counts)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    doPlotBackgroundAndGrid()

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      freq=FALSE,
      lty=1,
      cex=1)

    x <- seq(min(-10.0, min(dataArray) * 0.5) , max(max(dataArray) * 1.5, 100), length=10000)
    y <- dnorm(x, mean=mean(dataArray), sd=sd(dataArray))

    par(new=TRUE)

    plot(x,y,
         type="l",
         lwd=3,
         axes=FALSE,
         col=colorScheme[2,2],
         xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
         ylab='',
         xlab='',
         main=''
    )

    polygon(x, y,
            col=colorScheme[2,2],
            border=colorScheme[2][1],
            ylab='',
            xlab='',
            main=''
    )

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqnorm(dataArray, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    qqline(sort(dataArray), ylab='',
      xlab='', col=colorScheme[2,2], lwd=2)

    par(new=TRUE)

    qq <- qqnorm(sort(dataArray), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotQQ <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(qqplot(dataArray1, dataArray2, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    qq <- qqplot(sort(dataArray1), sort(dataArray2), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotPoints <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(dataArray1, dataArray2,
      type="p",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

########################################

plotSmoothLine <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(smooth.spline(dataArray1, dataArray2),
      type="l",
      axes=FALSE,
      col=colorScheme[1,2],
      bg=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidence <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    xLim <- range(xData) + c(-0.1,0.1)
    yLim <- range(c(yData+e,yData-e)) + c(-0.1,0.1)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    widthToInch = 96.0
    arrowLength = diff(range(xData))/25.0

    rect(xData - arrowLength, yData - e, xData + arrowLength, yData + e, col=colorScheme[1,2], border=FALSE)

    arrowTipLength = pmin(e/2.0, arrowLength/3.0)

    segments(xData - arrowLength, yData - e, xData + arrowLength, yData - e, lend=1, col=colorScheme[1,1])
    segments(xData - arrowLength, yData + e, xData + arrowLength, yData + e, lend=1, col=colorScheme[1,1])

    segments(xData - arrowLength/2.0, yData, xData+arrowLength/2.0, yData, col=colorScheme[1,1], lwd = 1.0)

    if (connectionLines) {
      frame <- data.frame(xData,yData)
      frame <- frame[order(xData),]
      lines(frame$xData, frame$yData, col=colorScheme[1,2],lty=2)
    }

    # draw circle outlines
    r <- pmin(e/2.0, arrowLength/5.0)
    for (i in 1 : length(xData)) {
      mid1X <- xData[i] - arrowLength
      mid1Y <- yData[i] + e[i] - r[i]

      mid2X <- xData[i] - arrowLength
      mid2Y <- yData[i] - e[i] + r[i]

      mid3X <- xData[i] + arrowLength
      mid3Y <- yData[i] + e[i] - r[i]

      mid4X <- xData[i] + arrowLength
      mid4Y <- yData[i] - e[i] + r[i]

      deg <- 90 : 180
      xCircle1 <- mid1X + r[i] * cos(deg/180.0 * pi)
      yCircle1 <- mid1Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle1, yCircle1, col=colorScheme[1,1])

      deg <- 180 : 270
      xCircle2 <- mid2X + r[i] * cos(deg/180.0 * pi)
      yCircle2 <- mid2Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle2, yCircle2, col=colorScheme[1,1])

      polygon(c(xCircle1, xCircle2), c(yCircle1, yCircle2), col = colorScheme[1,2], border = FALSE)

      deg <- 0 : 90
      xCircle3 <- mid3X + r[i] * cos(deg/180.0 * pi)
      yCircle3 <- mid3Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle3, yCircle3, col=colorScheme[1,1])

      deg <- 270 : 360
      xCircle4 <- mid4X + r[i] * cos(deg/180.0 * pi)
      yCircle4 <- mid4Y + r[i] * sin(deg/180.0 * pi)
      lines(xCircle4, yCircle4, col=colorScheme[1,1])

      polygon(c(xCircle3, xCircle4), c(yCircle3, yCircle4), col = colorScheme[1,2], border = FALSE)
    }

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotWithConfidenceContinous <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", connectionLines=FALSE) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    xLim <- range(xData) + c(-0.1,0.1)
    yLim <- range(c(yData + e, yData - e)) + c(-0.1,0.1)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    polygon(c(sort(xData),rev(sort(xData))),c(yData + e, rev(yData-e)), col=colorScheme[1,2], border=FALSE)

    lines(xData, yData + e, col=colorScheme[1,1])
    lines(xData, yData - e, col=colorScheme[1,1])

    lines(xData,yData,col=colorScheme[2,1])

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################

plotBox <- function(xData, yData, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks=10) {
    doOpenPDF(pdfFile, pdfTitle)
    doMargins(mainTitle, xTitle, yTitle)

    plot(cut(xData, breaks=breaks), yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      col="#00000000",
      border="#00000000",
      bg="#00000000",
      main='')

    doPlotBackgroundAndGrid()

    par(new=TRUE)

    plot(cut(xData, breaks=breaks), yData,
      type="l",
      axes=FALSE,
      col=thillux_grey[2],
      bg=colorScheme[1,2],
      border=colorScheme[1,1],
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    doBoxTitleAndAxes(mainTitle, xTitle, yTitle)

    noOut <- dev.off()
}

################################################################################
#!/usr/lib/R/bin/Rscript

library(methods)
library(ggplot2)
library(reshape2)

args = commandArgs(T)

mri22_data   = read.table(file=args[1], sep=',', header=T)
mri23_data   = read.table(file=args[2], sep=',', header=T)
jruby17_data = read.table(file=args[3], sep=',', header=T)
jruby9_data  = read.table(file=args[4], sep=',', header=T)
# rbx25_data   = read.table(file=args[5], sep=',', header=T)

x       = mri22_data$concurrent
mri22   = mri22_data$loss
mri23   = mri23_data$loss
jruby17 = jruby17_data$loss
jruby9  = jruby9_data$loss
# rbx25   = rbx25_data$loss

df = data.frame(x, mri22, mri23, jruby17, jruby9) #, rbx25)
df.long = melt(df, id.vars='x')

g = ggplot(df.long, aes(x, value, shape=variable)) +
	scale_x_log10(breaks=c(10, 50, 100, 500, 1000, 5000, 10000)) +
    scale_shape(name='Ruby VM') +
    ylab('Percentage of lost messages') +
	xlab('Concurrent clients (log.)') +
	geom_line() +
	geom_point() +
	theme_bw()

path = paste(args[1], 'loss', 'pdf', sep='.')
print(path)
ggsave(g, file=path)
REBOL [
	Title:   "Red/System compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/utils/profiler.r
profiler/active?: no

do-cache %system/utils/r2-forward.r
do-cache %system/utils/int-to-bin.r
do-cache %system/utils/IEEE-754.r
do-cache %system/utils/virtual-struct.r
do-cache %system/utils/secure-clean-path.r
do-cache %system/linker.r
do-cache %system/emitter.r

system-dialect: make-profilable context [
	verbose:  	  0										;-- logs verbosity level
	job: 		  none									;-- reference the current job object	
	runtime-path: pick [%system/runtime/ %runtime/] encap?
	nl: 		  newline
	
	loader: do bind load-cache %system/loader.r 'self
	
	options-class: context [
		config-name:		none						;-- Preconfigured compilation target ID
		OS:					none						;-- Operating System
		OS-version:			none						;-- OS version
		ABI:				none						;-- optional ABI flags (word! or block!)
		link?:				no							;-- yes = invoke the linker and finalize the job
		debug?:				no							;-- reserved for future use
		build-prefix:		%builds/					;-- prefix to use for output file name (none: no prefix)
		build-basename:		none						;-- base name to use for output file name (none: derive from input name)
		build-suffix:		none						;-- suffix to use for output file name (none: derive from output type)
		format:				none						;-- file format
		type:				'exe						;-- file type ('exe | 'dll | 'lib | 'obj | 'drv)
		target:				'IA-32						;-- CPU target
		cpu-version:		6.0							;-- CPU version (default: Pentium Pro)
		verbosity:			0							;-- logs verbosity level
		sub-system:			'console					;-- 'GUI | 'console
		runtime?:			yes							;-- include Red/System runtime
		use-natives?:		no							;-- force use of native functions instead of C bindings
		debug?:				no							;-- emit debug information into binary
		need-main?:			no							;-- yes => emit a function prolog/epilog around global code
		PIC?:				no							;-- generate Position Independent Code
		base-address:		none						;-- base image memory address
		dynamic-linker: 	none						;-- ELF dynamic linker ("interpreter")
		syscall:			'Linux						;-- syscalls convention: 'Linux | 'BSD
		stack-align-16?:	no							;-- yes => align stack to 16 bytes
		literal-pool?:		no							;-- yes => use pools to store literals, no => store them inlined (default: no)
		unicode?:			no							;-- yes => use Red Unicode API for printing on screen
		red-pass?:			no							;-- yes => Red compiler was invoked
		red-only?:			no							;-- yes => stop compilation at Red/System level and display output
		red-store-bodies?:	yes							;-- no => do not store function! value bodies (body-of will return none)
		red-strict-check?:	yes							;-- no => defers undefined word errors reporting at run-time
		red-tracing?:		yes							;-- no => do not compile tracing code
		red-help?:			no							;-- yes => keep doc-strings from boot.red
		legacy:				none						;-- block of optional OS legacy features flags
	]
	
	compiler: make-profilable context [
		job:		 	 none							;-- shortcut for job object
		pc:			 	 none							;-- source code input cursor
		script:		 	 none							;-- source script file name
		none-type:	 	 [#[none]]						;-- marker for "no value returned"
		last-type:	 	 none-type						;-- type of last value from an expression
		locals: 	 	 none							;-- currently compiled function specification block
		definitions:  	 make block! 100
		enumerations: 	 make hash! 10
		expr-call-stack: make block! 1					;-- simple stack of nested calls for a given expression
		locals-init: 	 []								;-- currently compiler function locals variable init list
		func-name:	 	 none							;-- currently compiled function name
		block-level: 	 0								;-- nesting level of input source block
		catch-level:	 0								;-- nesting level of CATCH body block
		verbose:  	 	 0								;-- logs verbosity level
	
		imports: 	   	 make block! 10					;-- list of imported functions
		exports: 	   	 make block! 10					;-- list of exported symbols
		natives:	   	 make hash!  40					;-- list of functions to compile [name [specs] [body]...]
		ns-path:		 none							;-- namespaces access path
		ns-stack:		 none							;-- namespaces resolution stack
		ns-list:		 make hash!  8					;-- namespaces definition list [name [word type...]...]
		sym-ctx-table:	 make hash!  100				;-- reverse lookup table for contexts
		globals:  	   	 make hash!  40					;-- list of globally defined symbols from scripts
		aliased-types: 	 make hash!  10					;-- list of aliased type definitions
		keywords-list:	 make block! 20
		
		resolve-alias?:  yes							;-- YES: instruct the type resolution function to reduce aliases
		decoration:		 slash							;-- decoration separator for namespaces
		shift-right-sym: to word! ">>>"					;-- workaround REBOL LOAD limitation
		
		debug-lines: reduce [							;-- runtime source line/file information storage
			'records make block!  1000					;-- [address line file] records
			'files	 make hash!   20					;-- filenames table
		]
		
		pos:		none								;-- validation rules cursor for error reporting
		return-def: to-set-word 'return					;-- return: keyword
		fail:		[end skip]							;-- fail rule
		rule: value: v: none							;-- global parsing rules helpers
		
		number!: 	  [byte! integer!]					;-- reserved for internal use only
		bit-set!: 	  [byte! integer! logic!]			;-- reserved for internal use only
		any-float!:	  [float! float32! float64!]		;-- reserved for internal use only
		any-number!:  union number! any-float!			;-- reserved for internal use only
		pointers!:	  [pointer! struct! c-string!] 		;-- reserved for internal use only
		any-pointer!: union pointers! [function!]		;-- reserved for internal use only
		poly!:		  union any-number! pointers!		;-- reserved for internal use only
		any-type!:	  union poly! [logic!]			  	;-- reserved for internal use only
		type-sets:	  [									;-- reserved for internal use only
			number! poly! any-type! any-pointer!
			any-number! bit-set!
		]
		
		comparison-op: [= <> < > <= >=]
		
		functions: to-hash compose [
		;--Name--Arity--Type----Cc--Specs--		   Cc = Calling convention
			+		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			-		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			*		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			/		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			and		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			or		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			xor		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			//		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- modulo
			(to-word "%")		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- remainder (real syntax: %)
			>>		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right signed
			<<		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift left signed
			-**		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right unsigned
			=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			not		[1	inline	- [a [bit-set!] 		   return: [bit-set!]]]
			push	[1	inline	- [a [any-type!]]]
			pop		[0	inline	- [						   return: [integer!]]]
			throw	[1	inline	- [n [integer!]]]
		]
		
		repend functions [shift-right-sym copy functions/-**]
		
		user-functions: tail functions					;-- marker for user functions
		
		action-class: context [action: type: data: none]
		
		struct-syntax: [
			pos: opt [into ['align integer! opt ['big | 'little]]]	;-- struct's attributes
			pos: some [word! into [func-pointer | type-spec]]		;-- struct's members
		]
		
		pointer-syntax: ['integer! | 'byte! | 'float32! | 'float64! | 'float!]
		
		func-pointer: ['function! set value block! (check-specs '- value)]
		
		type-syntax: [
			'logic! | 'integer! | 'byte! | 'int16!		;-- int16! needed for AVR8 backend
			| 'float! | 'float32! | 'float64!
			| 'c-string!
			| 'pointer! into [pointer-syntax]
			| 'struct!  into [struct-syntax]
		]

		type-spec: [
			pos: some type-syntax | pos: set value word! (	;-- multiple types allowed for internal usage		
				unless any [
					all [v: find-aliased/prefix value v <> value find aliased-types v pos/1: v]			;-- rewrite the type to prefix it
					find aliased-types value
					all [v: resolve-ns value v <> value enum-type? v pos/1: v]	;-- rewrite the type to prefix it
					all [enum-type? value pos/1: 'integer!]
				][throw false]							;-- stop parsing if unresolved type			
			)
		]		
		
		keywords: make hash! [
			;&			 [throw-error "reserved for future use"]
			?? 			 [comp-print-debug]
			as			 [comp-as]
			assert		 [comp-assert]
			size? 		 [comp-size?]
			if			 [comp-if]
			either		 [comp-either]
			case		 [comp-case]
			switch		 [comp-switch]
			until		 [comp-until]
			while		 [comp-while]
			any			 [comp-expression-list]
			all			 [comp-expression-list/_all]
			exit		 [comp-exit]
			return		 [comp-exit/value]
			catch		 [comp-catch]
			declare		 [comp-declare]
			null		 [comp-null]
			context		 [comp-context]
			with		 [comp-with]
			comment 	 [comp-comment]
			
			true		 [also true pc: next pc]		  ;-- converts word! to logic!
			false		 [also false pc: next pc]		  ;-- converts word! to logic!
			
			func 		 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			function 	 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			alias 		 [raise-level-error "an alias"]	  ;-- alias declaration not allowed at this level
		]
		
		calling-keywords: [								;-- keywords accepted in expr-call-stack
			?? as assert size? if either case switch until while any all
			return catch
		]
		
		foreach [word action] keywords [append keywords-list word]
		foreach [name spec] functions  [append keywords-list name]
		
		calc-line: has [idx head-end prev p header][
			header: head pc
			idx: (index? pc) - header/1  				;-- calculate real pc position (not counting hidden header)
			prev: 1

			parse header [								;-- search for closest line marker
				skip									;-- skip over header length
				some [
					set p pair! (
						if p/2 = idx [return p/1]		;-- exact value position match
						if p/2 > idx [return prev]		;-- closest value position match 
						prev: p/1
					)
				]
			]
			return p/1									;-- return last marker
		]
		
		store-dbg-lines: has [dbg pos][
			dbg: debug-lines
			unless pos: find dbg/files script [
				pos: tail dbg/files
				append dbg/files script
			]
			repend dbg/records [
				emitter/tail-ptr calc-line index? pos
			]
		]
		
		quit-on-error: does [
			clean-up
			if system/options/args [quit/return 1]
			halt
		]
		
		throw-error: func [err [word! string! block!]][
			print [
				"*** Compilation Error:"
				either word? err [
					join uppercase/part mold err 1 " error"
				][reform err]
				"^/*** in file:" mold script
				either locals [join "^/*** in function: " func-name][""]
			]
			if pc [
				print [
					"*** at line:" calc-line lf
					"*** near:" mold copy/part pc 8
				]
			]
			quit-on-error
		]
		
		throw-warning: func [msg [string! block!] /near][
			print [
				"*** Warning:" 	reform msg
				"^/*** in:" 	mold script
				"^/*** at:" 	mold copy/part any [all [near back pc] pc] 8
			]
		]
		
		raise-level-error: func [kind [string!]][
			pc: back pc
			throw-error reform ["declaring" kind "at this level is not allowed"]
		]
		
		raise-casting-error: does [
			backtrack 'as
			throw-error "multiple type casting not allowed"
		]
		
		;raise-paren-error: does [
		;	pc: back pc
		;	throw-error "parens are only allowed nested in an expression"
		;]
		
		raise-runtime-error: func [error [integer!]][
			emitter/target/emit-get-pc				;-- get current CPU program counter address
			last-type: [integer!]					;-- emit-get-pc returns an integer! (required for next line)
			compiler/comp-call '***-on-quit reduce [error <last>] ;-- raise a runtime error
		]
		
		undecorate: func [value [word! path! set-word! set-path!] /local v pos][
			unless find v: mold value decoration [return value]
			
			while [pos: find v decoration][
				unless find ns-list to path! copy/part v pos [
					pos: next pos
					v: append replace/all copy/part head v pos decoration slash pos
					return load v
				]
				v: at v pos + 1
			]
			value
		]
		
		backtrack: func [value /local res][
			if find [word! path! set-word! set-path!] type?/word value [
				value: undecorate value
			]
			pc: any [res: find/only/reverse pc value pc]
			to logic! res
		]
		
		blockify: func [value][either block? value [value][reduce [value]]]

		literal?: func [value][
			not any [word? value get-word? value path? value block? value value = <last>]
		]
		
		not-initialized?: func [name [word!] /local pos][
			all [
				locals
				pos: find locals /local
				pos: find next pos name
				not find locals-init name
			]
		]
		
		get-alias-id: func [pos [hash!]][
			1000 + divide 1 + index? pos 2
		]
		
		get-type-id: func [value /local type alias][
			with-alias-resolution off [type: resolve-expr-type value]
			
			either alias: find-aliased/position type/1 [		
				get-alias-id alias
			][
				type: resolve-aliased type
				type: switch/default type/1 [
					any-pointer! ['int-ptr!]
					pointer! [pick [int-ptr! byte-ptr!] type/2/1 = 'integer!]
				][type/1]
				select emitter/datatype-ID type
			]
		]
		
		system-reflexion?: func [path [path! set-path!] /local def][
			if path/1 = 'system [
				switch path/2 [
					alias [
						unless path/3 [
							backtrack path
							throw-error "invalid system/alias path access"
						]
						unless def: find-aliased/position path/3 [
							backtrack path
							throw-error ["undefined alias name:" path/3]
						]
						last-type: [integer!]
						return get-alias-id def			;-- special encoding for aliases
					]
					words [
						unless path/3 [
							backtrack path
							throw-error "invalid system/words path access"
						]
						path: remove/part copy path 2
						return either 1 = length? path [
							either set-path? path [to set-word! path/1][path/1]
						][
							path
						]
					]
					; add new special reflective system path here
				]
			]
			none
		]
		
		base-type?: func [value][
			if block? value [value: value/1]
			to logic! find/skip emitter/datatypes value 3
		]
		
		unbox: func [value][
			either object? value [value/data][value]
		]
		
		clear-docstrings: func [spec [block!]][
			remove-each s spec [string? s]
			spec
		]
		
		get-return-type: func [name [word!] /check /local type spec][
			unless all [
				spec: find-functions name
				any [
					type: select spec/2/4 return-def
					check
				]
			][
				backtrack name
				throw-error ["return type missing in function:" name]
			]
			any [type none-type]
		]
		
		set-last-type: func [spec [block!]][
			if spec: select spec return-def [last-type: spec]
		]
		
		local-variable?: func [name [word!]][
			all [locals find locals name]
		]
		
		exists-variable?: func [name [word! set-word!]][
			name: to word! name
			to logic! any [
				local-variable? name
				find globals name
			]
		]
		
		select-globals: func [name [word!] /local pos][
			all [
				pos: find globals name
				pos/2
			]
		]
		
		get-variable-spec: func [name [word!]][
			any [
				all [locals select locals name]
				select-globals name
			]
		]
		
		get-arity: func [spec [block!] /local count][
			count: 0
			parse spec [opt block! any [word! block! (count: count + 1)]]
			count
		]
		
		any-path?: func [value][
			find [path! set-path! lit-path!] type?/word value
		]
		
		any-float?: func [type [block!]][
			find any-float! type/1
		]
		
		any-pointer?: func [type [block!]][
			type: first resolve-aliased type
			
			either find type-sets type [
				not empty? intersect get type any-pointer!
			][
				to logic! find any-pointer! type
			]
		]

		equal-types?: func [type1 [word!] type2 [word!]][
			type1: either find type-sets type1 [get type1][reduce [type1]]
			type2: either find type-sets type2 [get type2][reduce [type2]]
			not empty? intersect type1 type2
		]
		
		equal-types-list?: func [types [block!]][
			forall types [							;-- check if all last expressions are of same type
				unless types/1/1 [return none-type]	;-- test if type is defined
				types/1: resolve-aliased types/1	;-- reduce aliases and pseudo-types
				if all [
					not head? types
					not equal-types? types/-1/1 types/1/1
				][
					return none-type
				]
			]
			first head types						;-- all types equal, return the first one
		]
						
		with-alias-resolution: func [mode [logic!] body [block!] /local saved][
			saved: resolve-alias?
			resolve-alias?: mode	
			do body
			resolve-alias?: saved
		]
		
		find-aliased: func [type [word!] /prefix /position /local ns pos][
			if all [ns: resolve-ns type find aliased-types ns][type: ns]
			if prefix [return ns]
			pos: find aliased-types type
			either position [pos][all [pos pos/2]]
		]
		
		resolve-aliased: func [type [block!] /local name][
			name: type/1
			all [
				type/1								;-- ensure it is not [none]
				not base-type? name
				not find type-sets name
				not all [
					enum-type? name
					type: [integer!]
				]
				not type: find-aliased name
				throw-error ["unknown type:" type]
			]
			type
		]
		
		resolve-type: func [name [word!] /with parent [block! none!] /local type local?][
			type: any [
				all [parent select parent name]
				local?: all [locals select locals name]
				select-globals name
			]
			if all [not type find functions name][
				return reduce ['function! functions/(decorate-fun name)/4]
			]
			if any [
				all [not local?	any [enum-type? name enum-id? name]]
				all [type enum-type? type/1]
			][
				return [integer!]
			]
			unless any [not resolve-alias? none? type base-type? type/1][
				type: find-aliased type/1
			]
			type
		]
		
		resolve-struct-member-type: func [spec [block!] name [word!] /local type][
			unless type: select spec name [
				while [not all [any-path? pc/1 find pc/1 name]][pc: back pc]
				throw-error [
					"invalid struct member" to lit-word! name "in:" mold to path! pc/1
				]
			]
			either resolve-alias? [resolve-aliased type][type]
		]
		
		resolve-path-type: func [path [path! set-path!] /short /parent prev /local type path-error saved][
			path-error: [
				pc: skip pc -2
				throw-error "invalid path value"
			]
			either word? path/1 [
				either parent [
					resolve-struct-member-type prev path/1	;-- just check for correct member name
					with-alias-resolution on [
						type: resolve-type/with path/1 prev
					]
				][
					with-alias-resolution on [
						type: resolve-type path/1
					]
				]
			][
				type: reduce [type?/word path/1]
			]
			
			unless type path-error
			
			either tail? skip path 2 [
				switch/default type/1 [
					c-string! [
						check-path-index path 'string
						[byte!]
					]
					pointer!  [
						check-path-index path 'pointer
						reduce [type/2/1]				;-- return pointed value type
					]
					struct!   [
						unless word? path/2 [
							backtrack path
							throw-error ["invalid struct member" path/2]
						]
						type: resolve-struct-member-type type/2 path/2
						
						if all [
							not short
							not set-path? path
							type/1 = 'function!
						][
							type: select type/2 return-def
						]
						type
					]
				] path-error
			][
				either short [
					resolve-path-type/parent/short next path second type
				][
					resolve-path-type/parent next path second type
				]
			]
		]
		
		get-type: func [value /local type][
			switch/default type?/word value [
				none!	 [none-type]					;-- no type case (func with no return value)
				tag!	 [either value = <last> [last-type][ [logic!] ]]
				logic!	 [[logic!]]
				word! 	 [resolve-type value]
				char!	 [[byte!]]
				integer! [[integer!]]
				decimal! [[float!]]
				string!	 [[c-string!]]
				path!	 [resolve-path-type value]
				object!  [value/type]
				block!	 [
					if value/1 = 'not [return get-type value/2]	;-- special case for NOT multitype native
					
					either 'op = second get-function-spec value/1 [
						either base-type? type: get-return-type value/1 [
							type						;-- unique returned type, stop here
						][
							get-type value/2			;-- recursively search for left operand base type
						]
					][
						get-return-type value/1
					]
				]
				paren!	 [
					switch/default value/1 [
						struct!  [reduce pick [[value/2][value/1 value/2]] word? value/2]
						pointer! [reduce [value/1 value/2]]
					][
						next next reduce ['array! length? value	'pointer! get-type value/1]	;-- hide array size
					]
				]
				get-word! [
					type: resolve-type to word! value
					switch/default type/1 [
						function! [type]
						integer! byte! float! float32! [compose/deep [pointer! [(type/1)]]]
					][
						throw-error ["invalid datatype for a get-word:" mold type]
					]
				]
			][
				throw-error ["not accepted datatype:" type? value]
			]
		]
		
		enum-type?: func [name [word!] /local type][
			all [
				type: find/skip enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				reduce [next type]
			]
		]
		
		enum-id?: func [name [word!] /local pos][
			all [
				pos: find/skip next enumerations name 3
				reduce [pos/-1]
			]
		]

		get-enumerator: func [name [word!] /value /local pos][
			all [
				pos: find/skip next enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				pos/2
			]
		]
		
		set-enumerator: func [
			identifier [word!] name [word! block!] value [integer! word!] /local list v
		][
			store-ns-symbol identifier
			if ns-path [
				add-ns-symbol to set-word! identifier
				identifier: ns-prefix identifier
			]
			
			if word? name [name: reduce [name]]
			forall name [
				store-ns-symbol name/1
				if ns-path [
					add-ns-symbol to set-word! name/1
					name/1: ns-prefix name/1
				]
				check-enum-word name/1
			]
			name: head name
			
			if all [
				word? value
				none? value: get-enumerator resolve-ns value
			][
				throw-error ["cannot resolve literal enum value for:" form name]
			]
			forall name [
				if verbose > 3 [print ["Enum:" identifier "[" name/1 "=" value "]"]]
				repend enumerations [identifier name/1 value]
			]
			value: value + 1
		]

		resolve-expr-type: func [expr /quiet /local type func? spec][
			if block? expr [
				switch type?/word expr/1 [
					set-word! [expr: expr/2]			;-- resolve assigned value type
					set-path! [expr: to path! expr/1]	;-- resolve path type
				]
			]			
			func?: all [
				block? expr word? expr/1
				not find comparison-op expr/1
				spec: find functions expr/1 		 ;-- works for unary & binary functions only!
				spec: spec/2
			]
			type: case [
				object? expr [
					expr/type						 ;-- type casting case
				]
				all [func? find [op inline] spec/2][ ;-- works for unary & binary functions only!
					any [
						all [
							expr/1 <> 'not			;-- @@ issue with 'not return type
							spec: select spec/4 return-def
							base-type? spec/1		;-- determined return type
							spec
						]
						get-type expr/2				;-- recursively search for return type
					]
				]
				all [func? quiet][
					any [
						select spec/4 return-def	;-- workaround error throwing in get-return-value
						none-type
					]
				]
				'else [
					expr: get-type expr
					if resolve-alias? [expr: resolve-aliased expr]
					expr
				]
			]
			type
		]
		
		check-throw: does [
			unless any [locals positive? catch-level][
				backtrack 'throw
				throw-error "THROW used without a wrapping CATCH"
			]
		]
		
		push-call: func [action [word! set-word! set-path!]][
			append/only expr-call-stack action
			if verbose >= 4 [
				new-line/all expr-call-stack off
				?? expr-call-stack
			]
		]
		
		pop-calls: does [clear expr-call-stack]
		
		cast: func [obj [object!] /quiet /local value ctype type][
			value: obj/data
			ctype: resolve-aliased obj/type
			type: get-type value

			if all [not quiet type = obj/type type/1 <> 'function!][
				throw-warning/near [
					"type casting from" type/1 
					"to" obj/type/1 "is not necessary"
				] 'as
			]
			if any [
				all [type/1 = 'function! not find [function! integer!] ctype/1]
				all [find [float! float64!] ctype/1 not find [float! float64! float32!] type/1]
				all [find [float! float64!] type/1  not find [float! float64! float32!] ctype/1]
				all [type/1 = 'float32! not find [float! float64! integer!] ctype/1]
				all [ctype/1 = 'byte! find [c-string! pointer! struct!] type/1]
				all [
					find [c-string! pointer! struct!] ctype/1
					find [byte! logic!] type/1
				]
			][
				backtrack value
				throw-error [
					"type casting from" type/1
					"to" ctype/1 "is not allowed"
				]
			]	
			unless literal? value [return value]	;-- shield the following literal conversions
			
			switch ctype/1 [
				byte! [
					switch type/1 [
						integer! [value: to char! value and 255]
						logic! 	 [value: pick [#"^(01)" #"^(00)"] value]
					]
				]
				integer! [
					if find [byte! logic!] type/1 [
						value: to integer! value
					]
				]
				logic! [
					switch type/1 [
						byte! 	 [value: value <> null]
						integer! [value: value <> 0]
					]
				]
			]
			value
		]
		
		decorate-function: func [name [word!]][
			to word! join "_local_" form name
		]
		
		find-functions: func [name [word!]][
			if all [
				locals
				type: select locals name
				type/1 = 'function!
			][
				name: decorate-function name
			]
			any [
				find functions name
				find functions resolve-ns name
			]
		]

		get-function-spec: func [name [word!] /local spec][
			all [
				spec: find-functions name
				spec/2
			]
		]

		decorate-fun: func [name [word!] /local type][
			either all [
				locals
				type: select locals name
				block? type
				type/1 = 'function!
			][
				decorate-function name
			][
				name
			]
		]

		remove-func-pointers: has [vars name][
			vars: any [find/tail locals /local []]
			forall vars [
				if all [
					word? vars/1
					block? vars/2
					vars/2/1 = 'function!
				][
					name: decorate-function vars/1
					remove/part find functions name 2
				]
			]
		]
		
		init-local: func [name [word!] expr casted [block! none!] /local pos type][
			append locals-init name					;-- mark as initialized
			pos: find locals name
			unless block? pos/2 [					;-- if not typed, infer type
				insert/only at pos 2 type: any [
					casted
					resolve-expr-type expr
				]
				if verbose > 2 [print ["inferred type" mold type "for variable:" pos/1]]
			]
		]
		
		order-ctx-candidates: func [a b][				;-- order by increasing path size,
			to logic! not all [							;-- and word! before path!.
				path? a
				any [
					word? b
					all [path? b greater? length? a length? b]
				]
			]
		]
		
		store-ns-symbol: func [name [word!] /local pos][
			if ns-path [
				either pos: find/skip sym-ctx-table name 2 [
					either block? pos/2 [
						if find/only pos/2 ns-path [exit]
					][
						if ns-path = pos/2 [exit]
						pos/2: reduce [pos/2]
					]
					append/only pos/2 copy ns-path
					sort/compare pos/2 :order-ctx-candidates
				][
					append sym-ctx-table name
					append/only sym-ctx-table copy ns-path
				]
			]
		]
		
		add-ns-symbol: func [name [set-word!] /local ctx ns][
			name: to word! name
			if find second find/only ns-list ns-path name [exit]
			if ns-stack [
				ctx: tail ns-stack
				until [
					ctx: back ctx
					if all [
						ns: find/only ns-list to path! ctx/1
						find second ns name 
					][exit]
					head? ctx
				]
			]
			append second find/only ns-list ns-path name
		]
		
		add-symbol: func [name [word!] value type][
			unless type [type: get-type value]
			unless 'array! = first head type [type: copy type]
			append globals reduce [name type]
			type
		]
		
		add-function: func [type [word!] spec [block!] cc [word!]][
			repend functions [
				to word! spec/1 reduce [get-arity spec/3 type cc new-line/all spec/3 off]
			]
			if find-attribute spec/3 'callback [
				append last functions 'callback
			]
		]
		
		compare-func-specs: func [
			f-type [block!] c-type [block!] /with fun [word!] cb [get-word!] /local spec pos idx
		][
			if with [
				cb: to word! cb
				if functions/:cb/3 <> functions/:fun/3 [
					throw-error [
						"incompatible calling conventions between"
						fun "and" cb
					]
				]
			]
			if pos: find f-type /local [f-type: head clear copy pos] ;-- remove locals
			if block? f-type/1 [f-type: next f-type]	;-- skip optional attributes block
			if block? c-type/1 [c-type: next c-type]	;-- skip optional attributes block
			idx: 2
			foreach [name type] f-type [
				if type <> c-type/:idx [return false]
				idx: idx + 2
			]
			true
		]
		
		ns-decorate: func [path [path!] /global /set][
			to get pick [set-word! word!] to logic! set mold path	;-- unless / use: replace/all mold path slash decoration
		]

		ns-join: func [ns [path! word!] name [word! path! set-word! set-path!]][
			join ns to word! mold/flat name
		]

		ns-prefix: func [name [word! path! set-word! set-path!] /set][
			if set-word? name [name: to word! name]
			name: ns-join ns-path name
			either set [ns-decorate/set name][ns-decorate name]
		]
		
		check-enum-word: func [name [word!] /local error][
			case [
				all [find keywords name name <> 'context][
					error: ["attempt to redefine a protected keyword:" name]
				]
				find functions name [
					error: ["attempt to redefine existing function name:" name]
				]
				find definitions name [
					error:  ["attempt to redefine existing definition:" name]
				]
				find-aliased name [
					error:  ["attempt to redefine existing alias definition:" name]
				]
				base-type? name [
					error:  ["redeclaration of base type:" name ]
				]
				any [
					exists-variable? name
					get-variable-spec name
				][										;-- it's a variable
					error:  ["redeclaration of variable:" name]
				]
				enum-type? name [
					error:  ["redeclaration of enum identifier:" name ]
				]
				enum-id? name [
					error:  ["redeclaration of enumerator:" name ]
				]
			]
			if error [throw-error error]
		]
		
		check-keywords: func [name [word!]][
			if find keywords name [
				throw-error ["attempt to redefine a protected keyword:" name]
			]
		]
		
		check-path-index: func [path [path! set-path!] type [word!] /local ending enum-value][
			ending: path/2
			case [
				all [type = 'pointer ending = 'value][]	;-- pass thru case
				word? ending [
					either all [
						not local-variable? ending
						enum-value: get-enumerator ending
					][
						path/2: ending: enum-value
					][
						unless any [
							local-variable? ending
							find globals ending: resolve-ns ending
							get-enumerator ending
						][
							backtrack path
							throw-error ["undefined" type "index variable"]
						]
						if 'integer! <> first resolve-type ending [
							backtrack path
							throw-error [
								"attempt to use" type
								"indexing with a non-integer! variable"
							]
						]
					]
				]
				not integer? ending [
					backtrack path
					throw-error [
						"attempt to use" type
						"indexing with a non-integer! value"
					]
				]
			]
		]
		
		check-func-name: func [name [word!] /only][
			if find functions name [
				pc: back pc
				throw-error ["attempt to redefine existing function name:" name]
			]
			if any [enum-type? name	enum-id? name][
				pc: back pc
				throw-error ["attempt to redefine existing enumerator:" name]
			]
			if all [not only find any [locals globals] name][
				pc: back pc
				throw-error ["a variable is already using the same name:" name]
			]
		]
		
		check-duplicates: func [
			name [word!] args [block! none!] locs [block! none!]
			/local dups
		][
			if args [remove-each item args: copy args [not word? item]]
			if locs [remove-each item locs: copy locs [not word? item]]
			
			if any [
				all [args (length? unique args) <> length? args]
				all [locs (length? unique locs) <> length? locs]
				all [args locs not empty? dups: intersect args locs]
			][
				throw-error [
					"duplicate variable definition in function" name
					either dups [reform ["for:" mold/only new-line/all dups no]][""]
				]
			]
		]
		
		check-specs: func [
			name specs /extend
			/local type type-def spec-type attribs value args locs cconv pos
		][
			unless block? specs [
				throw-error "function definition requires a specification block"
			]
			cconv: ['cdecl | 'stdcall]
			attribs: [
				[cconv ['variadic | 'typed | 'custom]]
				| [['variadic | 'typed | 'custom] cconv]
				| 'catch | 'infix | 'variadic | 'typed | 'custom | 'callback | cconv
			]
			type-def: pick [[func-pointer | type-spec] [type-spec]] to logic! extend

			unless catch [
				parse specs [
					opt [								;-- function's attribute and main doc-string
						string! opt [into attribs]		;-- can be specified in any order
						| into attribs opt string!
					]
					pos: copy args any [pos: word! into type-def opt string!]	;-- arguments definition
					pos: opt [							;-- return type definition				
						set value set-word! (					
							rule: pick reduce [[into type-spec] fail] value = return-def
						) rule
						opt string!
					]
					pos: opt [/local copy locs some [pos: word! opt [into type-spec]]] ;-- local variables definition
				]
			][
				throw-error rejoin ["invalid definition for function " name ": " mold pos]
			]
			if block? args [
				clear-docstrings args
				foreach [name type] args [
					if enum-id? name [
						throw-warning ["function's argument redeclares enumeration:" name]
					]
				]
			]
			check-duplicates name args locs
		]
		
		check-conditional: func [name [word!] expr][
			if last-type/1 <> 'logic! [check-expected-type/key name expr [logic!]]
		]
		
		check-expected-type: func [name [word!] expr expected [block!] /ret /key /local type alias][
			unless any [not none? expr key][return none]   ;-- expr == none for special keywords
			if all [
				not all [object? expr expr/action = 'null] ;-- avoid null type resolution here
				not none? expr							;-- expr can be false, so explicit check for none is required
				first type: resolve-expr-type expr		;-- first => deep check that it's not [none]
			][											;-- check if a type is returned or none
				type: resolve-aliased type
				if alias: find-aliased expected/1 [expected: alias]
			]
			if all [
				ret
				block? expr
				any [set-word? expr/1 set-path? expr/1]
			][
				type: none
			]
			unless any [
				all [
					object? expr
					expr/action = 'null
					type: either expected/1 = 'any-type! [expr/type][expected]	;-- morph null type to expected
					any-pointer? expected
				]
				all [
					type
					any [
						find type-sets expected/1
						find type-sets type/1
					]
					equal-types? type/1 expected/1		;-- internal polymorphic case
				]
				all [
					type
					type/1 = 'function!
					any [
						find [any-type! any-pointer!] expected/1
						all [
							expected/1 = 'function!
							compare-func-specs/with type/2 expected/2 name expr	 ;-- callback case
						]
					]
				]
				expected = type 						;-- normal single-type case
				all [
					type
					type/1 = 'integer!
					enum-type? expected/1				;-- TODO: add also a value check for enums
				]
			][
				if expected = type [type: 'null]		;-- make null error msg explicit
				any [
					backtrack any [all [block? expr expr/1] expr]
					backtrack name
				]
				throw-error [
					reform case [
						ret   [["wrong return type in function:" name]]
						key   [[
							uppercase form name "requires a conditional expression"
							either find [while until] name ["as last expression"][""]
						]]
						'else [["argument type mismatch on calling:" name]]
					]
					"^/*** expected:" join mold expected #","
					"found:" mold new-line/all any [type [none]] no
				]
			]
			type
		]
		
		check-arguments-type: func [name args /local entry spec list type][
			if find [set-word! set-path!] type?/word name [exit]
			
			entry: find functions name
			if all [
				not empty? spec: entry/2/4 
				block? spec/1
			][
				spec: next spec							;-- jump over attributes block
			]
			list: clear []
			forall args [
				either all [decimal? args/1 spec/2/1 = 'float32!][
					args/1:	make action-class [			;-- inject type casting to float32!
						action: 'type-cast
						type: [float32!]
						data: args/1					;-- literal float!
					]
					append/only list spec/2				;-- pass-thru for float! values used as float32! arguments
				][
					append/only list check-expected-type name args/1 spec/2
				]
				spec: skip spec	2
			]
			if all [
				any [
					find emitter/target/comparison-op name
					find emitter/target/bitwise-op name
				]
				not equal-types? list/1/1 list/2/1		;-- allow implicit casting for math ops only
			][
				backtrack name
				throw-error [
					"left and right argument must be of same type for:" name
					"^/*** left:" join list/1/1 #"," "right:" list/2/1
				]
			]
			if find emitter/target/math-op name	[
				case [
					any [
						all [list/1/1 = 'byte! any-pointer? list/2]
						all [list/2/1 = 'byte! any-pointer? list/1]
					][
						backtrack name
						throw-error [
							"arguments must be of same size for:" name
							"^/*** left:" join list/1/1 #"," "right:" list/2/1
						]
					]
					any [string? unbox args/1 string? unbox args/2][
						backtrack name
						throw-error "a literal string cannot be used with a math operator"
					]
				]
			]
		]
		
		check-variable-arity?: func [spec [block!] /local attribs][
			all [
				attribs: get-attributes spec
				any [
					all [find attribs 'variadic 'variadic]
					all [find attribs 'typed 'typed]
					all [find attribs 'custom 'custom]
				]
			]
		]
		
		check-body: func [body][
			case/all [
				not block? :body [throw-error "expected a block of code"]
				empty? body  	 [throw-error "expected a non-empty block of code"]
			]
		]
		
		fetch-into: func [								;-- compile sub-block
			code [block! paren!] body [block!] /root
			/local save-pc level
		][
			if root [
				level: block-level						;-- save block level from parent context
				clear expr-call-stack
			]
			save-pc: pc
			pc: code
			do body
			if root [block-level: level]
			next pc: save-pc
		]
		
		get-attributes: func [spec [block!]][
			any [
				all [block? spec/1 spec/1]
				all [string? spec/1 block? spec/2 spec/2]
			]
		]
		
		find-attribute: func [spec [block!] name [word!]][
			either list: get-attributes spec [
				to logic! find list name
			][
				false
			]
		]
		
		get-cconv: func [specs [block!]][
			pick [cdecl stdcall] to logic! all [
				not empty? specs
				find-attribute specs 'cdecl
			]
		]
		
		fetch-func: func [name /local specs type cc attribs][
			name: to word! name
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			if ns-path [name: ns-prefix name]
			check-func-name name
			check-specs name specs: pc/2
			specs: copy specs
			clear-docstrings specs
			
			type: 'native
			cc:   'stdcall								;-- default calling convention
			
			if all [
				not empty? specs
				attribs: get-attributes specs
			][
				case [
					find attribs 'infix [
						if 2 <> get-arity specs [
							throw-error [
								"infix function requires 2 arguments, found"
								get-arity specs "for" name
							]
						]
						type: 'infix
					]
					find attribs 'cdecl   [cc: 'cdecl]
					find attribs 'stdcall [cc: 'stdcall]	;-- get ready when fastcall will be the default cc
				]
			]
			add-function type reduce [name none specs] cc
			emitter/add-native name
			repend natives [
				name specs pc/3 script
				all [ns-path copy ns-path]
				all [ns-stack copy/deep ns-stack]		;@@ /deep doesn't work on paths
			]
			pc: skip pc 3
		]
		
		reduce-logic-tests: func [expr /local test value][
			test: [logic? expr/2 logic? expr/3]
			
			if all [
				block? expr
				find [= <>] expr/1
				any test
			][
				expr: either all test [
					do expr								;-- let REBOL reduce the expression
				][
					expr: copy expr
					if any [
						all [expr/1 = '= not all [expr/2 expr/3]]
						all [expr/1 = first [<>] any [expr/2 = true expr/3 = true]]
					][
						insert expr 'not
					]
					remove-each v expr [any [find [= <>] v logic? v]]
					if any [
						all [
							word? expr/1
							any [
								get-variable-spec expr/1
								enum-id? expr/1
							]
						]
						paren? expr/1
						block? expr/1
						object? expr/1
					][
						expr: expr/1					;-- remove outer brackets if variable
					]
					expr
				]
			]
			expr
		]
		
		process-export: has [defs cc ns func? spec][
			if word? pc/2 [
				unless find [stdcall cdecl] cc: pc/2 [
					throw-error ["invalid calling convention specifier:" cc]
				]
				pc: next pc
			]
			foreach name pc/2 [
				func?: no
				unless any [word? name path? name][
					throw-error ["invalid exported symbol:" mold name]
				]
				if path? name [name: resolve-ns-path name]
				unless any [
					find globals name
					func?: find-functions name
				][
					throw-error ["undefined exported symbol:" mold name]
				]
				append exports name
				
				if func? [
					spec: select functions name
					spec/3: any [cc 'cdecl]
					unless spec/5 = 'callback [append spec 'callback]
				]
			]
		]
		
		process-import: func [defs [block!] /local lib list cc name specs spec id reloc pos][
			unless block? defs [throw-error "#import expects a block! as argument"]
			
			unless parse defs [
				some [
					pos: set lib string! (
						unless list: select imports lib [
							repend imports [lib list: make block! 10]
						]
					)
					pos: set cc ['cdecl | 'stdcall]		;-- calling convention	
					pos: into [
						some [
							specs:						;-- new function mapping marker
							pos: set name set-word! (
								name: to word! name
								store-ns-symbol name
								if ns-path [
									add-ns-symbol to set-word! name
									name: ns-prefix name
								]
								check-func-name name
							)
							pos: set id   string!   (repend list [id reloc: make block! 1])
							pos: set spec block!    (
								check-specs/extend name spec
								clear-docstrings spec
								specs: copy specs
								specs/1: name
								add-function 'import specs cc
								emitter/import-function name reloc
							)
						]
					]
				]
			][
				throw-error ["invalid import specification at:" pos]
			]		
		]
		
		process-syscall: func [defs [block!] /local name id spec pos][
			unless block? defs [throw-error "#syscall expects a block! as argument"]
			unless parse defs [
				some [
					pos: set name set-word! (check-func-name name: to word! name)
					pos: set id   integer!
					pos: set spec block!    (
						check-specs/extend name spec
						spec: copy spec
						clear-docstrings spec
						add-function 'syscall reduce [name none spec] 'syscall
						append last functions id		;-- extend definition with syscode
					)
				]
			][
				throw-error ["invalid syscall specification at:" pos]
			]
		]
		
		process-enum: func [name value /local enum-value enum-names][
			unless word? name [throw-error "enumeration expected a word as name"]
			
			either block? value [
				check-enum-word name 					;-- first checking enumeration identifier possible conflicts
				parse value [
					(enum-value: 0)
					any [
						[
							copy enum-names word!
							| (enum-names: make block! 10) some [
								set enum-name set-word!
								(append enum-names to word! enum-name)
							]	set enum-value [integer! | word!]
						] 
						(enum-value: set-enumerator name enum-names enum-value)
						| set enum-name 1 skip (
							throw-error ["invalid enumeration:" to word! enum-name]
						)
					]
				]
			][
				throw-error ["invalid enumeration (block required!):" mold value]
			]
		]
		
		process-get: func [code [block!] /local value][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #get directive
				return none
			]
			red/process-get-directive code/2 pc
			fetch-expression
		]
		
		process-in: func [code [block!] /local value][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #in directive
				return none
			]
			red/process-in-directive code/2 code/3 pc
			fetch-expression
		]
		
		process-call: func [code [block!] /local mark][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #call directive
				return none
			]
			mark: tail red/output
			red/process-call-directive code/2 yes
			remove/part pc 2
			insert pc mark
			clear mark
			none										;-- do not return an expression to compile
		]
		
		comp-chunked: func [body [block!]][
			emitter/chunks/start
			do body
			emitter/chunks/stop
		]

		comp-directive: has [body][
			switch/default pc/1 [
				#import  [process-import  pc/2  pc: skip pc 2]
				#export  [process-export  pc/2  pc: skip pc 2]
				#syscall [process-syscall pc/2	pc: skip pc 2]
				#call	 [process-call	  pc]
				#get	 [process-get	  pc]
				#in		 [process-in	  pc]
				#enum	 [process-enum pc/2 pc/3 pc: skip pc 3]
				#verbose [set-verbose-level pc/2 pc: skip pc 2]
				#script	 [								;-- internal compiler directive
					unless pc/2 = 'in-memory [
						compiler/script: secure-clean-path pc/2	;-- set the origin of following code
					]
					pc: skip pc 2
				]
			][
				throw-error ["unknown directive" pc/1]
			]
		]
		
		comp-print-debug: has [out][
			unless word? name: pc/2 [
				throw-error "?? needs a word as argument"
			]
			out: next next compose/deep [
				2 (to pair! reduce [calc-line 1])		;-- hidden line offset header
				print-line [
					2 (to pair! reduce [calc-line 1])	;-- hidden line offset header
					(join name ": ") (name)
				]
			]
			out/2: next next out/2
			change/part pc out 2
			none
		]
		
		comp-comment: does [
			pc: next pc
			either block? pc/1 [pc: next pc][fetch-expression]
			none
		]
		
		comp-with: has [ns list with-ns words res ctx][
			ns: pc/2
			unless all [any [word? ns block? ns] block? pc/3][
				throw-error "WITH invalid argument"
			]
			unless block? ns [ns: reduce [ns]]
			
			forall ns [
				ns/1: either path? ctx: resolve-ns/path ns/1 [ctx][to path! ctx]
				unless find/only ns-list ns/1 [throw-error ["undefined context" ns/1]]
			]
			with-ns: unique copy ns
			
			list: clear []
			foreach ns with-ns [
				either empty? res: intersect list words: to block! second find/only ns-list ns [
					append list words
				][
					throw-warning rejoin [
						"contexts are using identical word"
						pick ["s: " ": "] 1 < length? res
						res
					]
				]
			]

			list: copy with-ns
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack list
			
			fetch-into/root pc/3 [comp-dialect]
			
			pc: skip pc 3
			clear skip tail ns-stack negate length? list
			if empty? ns-stack [ns-stack: none]
			
			none
		]
		
		comp-context: has [name level][
			unless block? pc/2 [throw-error "context specification block is missing"]
			unless set-word? pc/-1 [throw-error "context's name setting is missing"]
			unless zero? block-level [
				pc: back pc
				throw-error "context has to be declared at root level"
			]
			
			check-keywords name: to word! pc/-1
			if any [										;@@ factorize this out
				all [locals find locals name]
				find globals name
				find functions name
				find aliased-types name
				find definitions name
				find enumerations name
			][
				pc: back pc
				throw-error "context name is already taken"
			]
			pc: next pc
			
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack to word! mold/flat name
			
			either ns-path [
				append ns-path to word! mold/flat name
			][
				ns-path: to lit-path! mold/flat name		;-- workaround newline flag remanence issue
			]
			either find/only ns-list ns-path [
				throw-error ["context" name "already defined"]
			][
				repend ns-list [copy ns-path make hash! 32]
			]

			fetch-into/root pc/1 [comp-dialect]
			
			remove back tail ns-path
			if empty? ns-path [ns-path: none]
			remove back tail ns-stack
			if empty? ns-stack [ns-stack: none]
			
			pc: next pc
			none
		]
		
		comp-declare: has [rule value pos offset ns][
			unless find [set-word! set-path!] type?/word pc/-1 [
				throw-error "assignment expected before literal declaration"
			]
			value: to paren! reduce either find [pointer! struct!] pc/2 [
				rule: get pick [struct-syntax pointer-syntax] pc/2 = 'struct!
				unless catch [parse pos: pc/3 rule][
					throw-error ["invalid literal syntax:" mold pos]
				]
				if all [
					pc/2 = 'struct!
					(length? pc/3) <> (length? unique/skip pc/3 2)
				][
					throw-error ["duplicate member name in struct:" mold pc/3]
				]
				if pc/3/1 = 'float64! [pc/3/1: 'float!]
				offset: 3
				[pc/2 pc/3]
			][
				unless all [word? pc/2 resolve-aliased reduce [pc/2]][
					throw-error ["declaring literal for type" pc/2 "not supported"]
				]
				value: pc/2
				if all [ns-path ns: find-aliased/prefix value][value: ns]
				offset: 2
				['struct! value]
			]
			pc: skip pc offset
			value
		]
		
		comp-null: does [
			pc: next pc
			make action-class [action: 'null type: [any-pointer!] data: 0]
		]
		
		comp-as: has [ctype ptr? expr type][
			ctype: pc/2
			if ptr?: find [pointer! struct! function!] ctype [ctype: reduce [pc/2 pc/3]]
			
			unless any [
				parse blockify ctype [func-pointer | type-syntax]
				find-aliased ctype
			][
				throw-error ["invalid target type casting:" ctype]
			]
			pc: skip pc pick [3 2] to logic! ptr?
			expr: fetch-expression

			if all [
				block? ctype
				ctype/1 = 'function!
				type: get-type expr
				type/1 = 'function!
			][
				unless compare-func-specs ctype/2 copy type/2 [
					throw-error "invalid functions casting: specifications not matching"
				]
			]
			if all [object? expr expr/action = 'null][
				pc: back pc
				throw-error "type casting on null value is not allowed"
			]
			make action-class [
				action: 'type-cast
				type: blockify ctype
				data: expr
			]
		]
		
		comp-assert: has [expr line][
			either job/debug? [
				line: calc-line
				pc: next pc
				expr: fetch-expression/final
				check-conditional 'assert expr			;-- verify conditional expression
				expr: process-logic-encoding expr yes

				insert/only pc next next compose [
					2 (to pair! reduce [line 1])			;-- hidden line offset header
					***-on-quit 98 as integer! system/pc
				]
				set [unused chunk] comp-block-chunked		;-- compile TRUE block
				emitter/set-signed-state expr				;-- properly set signed/unsigned state
				emitter/branch/over/on chunk reduce [expr/1] ;-- branch over if expr is true
				emitter/merge chunk
				last-type: none-type
				<last>
			][
				pc: next pc
				fetch-expression							;-- consume next expression
				none
			]
		]
		
		comp-alias: has [name pos][
			unless set-word? pc/-1 [
				throw-error "assignment expected for ALIAS"
			]
			unless find [struct! function!] pc/2 [
				throw-error "ALIAS only allowed for struct! and function!"
			]
			name: to word! pc/-1
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			all [
				not base-type? name
				ns-path
				name: ns-prefix name
			]
			if find aliased-types name [
				pc: back pc
				throw-error reform [
					"alias name already defined as:"
					mold aliased-types/:name
				]
			]
			if base-type? name [
				pc: back pc
				throw-error "a base type name cannot be defined as an alias name"
			]
			repend aliased-types [name reduce [pc/2 pc/3]]
			switch pc/2 [
				struct! [
					unless catch [parse pos: pc/3 struct-syntax][
						throw-error ["invalid struct syntax:" mold pos]
					]
				]
				function! [check-specs 'pointer pc/3]
			]
			pc: skip pc 3
			none
		]
		
		comp-size?: has [type expr][
			pc: next pc
			unless all [
				word? expr: pc/1
				type: any [
					all [base-type? expr expr]
					all [enum-type? expr [integer!]]
					find-aliased expr
				]
				pc: next pc
			][
				expr: fetch-expression/final	
				type: resolve-expr-type expr
			]
			emitter/get-size type expr
		]
		
		comp-exit: func [/value /local expr type ret][
			unless locals [
				throw-error [pc/1 "is not allowed outside of a function"]
			]
			pc: next pc
			ret: select locals return-def
			
			either value [				
				unless ret [							;-- check if return: declared
					throw-error [
						"RETURN keyword used without return: declaration in"
						func-name
					]
				]
				expr: fetch-expression/final/keep		;-- compile expression to return
				type: check-expected-type/ret func-name expr ret
				ret: either type [last-type: type <last>][none]
			][
				if ret [throw-error "EXIT keyword is not compatible with declaring a return value"]
			]
			emitter/target/emit-exit
			ret
		]
		
		comp-catch: has [offset locals-size][
			pc: next pc
			fetch-expression/keep/final
			if any [not last-type last-type <> [integer!]][
				backtrack 'catch
				throw-error "CATCH expects a threshold value of type integer!"
			]
			unless block? pc/1 [
				backtrack 'catch
				throw-error "CATCH requires a body block as 2nd argument"
			]
			
			catch-level: catch-level + 1
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			catch-level: catch-level - 1
			
			offset: emitter/target/emit-open-catch length? chunk/1
			foreach ptr chunk/2 [ptr/1: ptr/1 + offset]	;-- account for (catch-frame + push) opcodes
			emitter/merge chunk
			
			locals-size: either locals [
				abs last emitter/stack
			][
				emitter/target/locals-offset
			]
			emitter/target/emit-close-catch locals-size
			
			last-type: none-type
			none
		]

		comp-block-chunked: func [/only /test name [word!] /local expr][
			emitter/chunks/start
			expr: either only [
				fetch-expression/final					;-- returns first expression
			][
				comp-block/final						;-- returns last expression
			]
			if test [
				check-conditional name expr				;-- verify conditional expression
				expr: process-logic-encoding expr no
			]
			reduce [
				expr 
				emitter/chunks/stop						;-- returns a chunk block!
			]
		]
		
		process-logic-encoding: func [expr invert? [logic!]][	;-- preprocess logic values
			case [
				logic? expr [ [#[true]] ]
				find [word! path!] type?/word expr  [
					emitter/target/emit-integer-operation '= [<last> 0]
					reduce [not invert?]
				]
				object? expr [
					expr: cast expr
					unless find [word! path!] type?/word any [
						all [block? expr expr/1] expr 
					][
						emitter/target/emit-integer-operation '= [<last> 0]
					]
					process-logic-encoding expr invert?
				]
				block? expr [
					case [
						find comparison-op expr/1 [expr]
						'else [process-logic-encoding expr/1 invert?]
					]
				]
				tag? expr [
					either last-type/1 = 'logic! [
						emitter/target/emit-integer-operation '= [<last> 0]
						reduce [not invert?]
					][expr] 
				]
				'else [expr]
			]
		]
		
		comp-if: has [expr unused chunk][		
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'if expr					;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
	
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/on chunk expr/1			;-- insert IF branching			
			emitter/merge chunk
			last-type: none-type
			<last>
		]
		
		comp-either: has [expr e-true e-false c-true c-false offset t-true t-false ret][
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'either expr				;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
			check-body pc/2								;-- check FALSE block
			
			set [e-true c-true]   comp-block-chunked	;-- compile TRUE block
			set [e-false c-false] comp-block-chunked	;-- compile FALSE block

			t-true:  resolve-expr-type/quiet e-true
			t-false: resolve-expr-type/quiet e-false

			last-type: either all [
				t-true/1 t-false/1
				t-true:  resolve-aliased t-true			;-- alias resolution is safe here
				t-false: resolve-aliased t-false
				equal-types? t-true/1 t-false/1
			][t-true][none-type]						;-- allow nesting if both blocks return same type

			if any [
				all [
					locals								;-- if in function body
					tail? pc							;-- and if at tail of body
					ret: select locals return-def		;-- and if function returns something
					ret/1 = 'logic!						;-- and if it returns a logic! value
				]
				all [
					not empty? expr-call-stack
					last-type/1 = 'logic!				;-- and if EITHER returns a logic! too
				]
			][
				if block? e-true  [emitter/logic-to-integer/with e-true  c-true]
				if block? e-false [emitter/logic-to-integer/with e-false c-false]
			]
		
			offset: emitter/branch/over c-false
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/adjust/on c-true negate offset expr/1	;-- skip over JMP-exit
			emitter/merge emitter/chunks/join c-true c-false
			<last>
		]
		
		comp-case: has [cases list test body op bodies offset types][
			pc: next pc
			cases: pc/1
			list:  make block! 8
			types: make block! 8
			
			until [										;-- collect and pre-compile all cases
				append expr-call-stack #test			;-- marker for disabling expression post-processing
				fetch-into cases [						;-- compile case test
					append/only list comp-block-chunked/only/test 'case
					cases: pc							;-- set cursor after the expression
				]
				clear find expr-call-stack #test
				
				append expr-call-stack #body			;-- marker for enabling expression post-processing
				fetch-into cases [						;-- compile case body
					append/only list body: comp-block-chunked
					append/only types resolve-expr-type/quiet body/1
				]
				clear find expr-call-stack #body
				tail? cases: next cases
			]
			
			bodies: comp-chunked [raise-runtime-error 100] ;-- raise a runtime error if unmatched value
			
			list: tail list								;-- point to last case test
			until [										;-- left join all cases in reverse order			
				list: skip list -2
				set [test body] list					;-- retrieve case-test and case-body chunks

				emitter/set-signed-state test/1			;-- properly set signed/unsigned state
				offset: negate emitter/branch/over bodies		;-- insert case exit branching
				emitter/branch/over/on/adjust body/2 test/1/1 offset	;-- insert case test branching
				
				body: emitter/chunks/join test/2 body/2	;-- join case test with case body
				bodies: emitter/chunks/join body bodies	;-- left join case with other cases
				head? list		
			]	
			emitter/merge bodies						;-- commit all to main code buffer
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-switch: has [expr save-type spec value values body bodies list types default pos][
			pc: next pc
			expr: fetch-expression/keep/final			;-- compile argument
			if any [none? expr last-type = none-type][
				throw-error "SWITCH argument has no return value"
			]
			save-type: last-type			
			check-body spec: pc/1
			foreach w [values list types][set w make block! 8]
			forall spec [								;-- resolve possible enumeration symbols
				if all [word? spec/1 spec/1 <> 'default][
					check-enum-symbol spec
				]
			]
			
			;-- check syntax and store parts in different lists
			unless parse spec [
				some [
					pos: copy value some [integer! | char!] 
					(repend values [value none])		;-- [value body-offset ...]
					pos: block! (
						fetch-into pos [				;-- compile action body
							body: comp-block-chunked
							append/only list body/2		
							append/only types resolve-expr-type/quiet body/1
						]
					)
				]
				opt [
					'default pos: block! (
						fetch-into pos [				;-- compile default body
							default: comp-block-chunked
							append/only types resolve-expr-type/quiet default/1
						]
					)
				]
			][
				throw-error ["wrong syntax in SWITCH block at:" copy/part pos 4]
			]

			;-- assemble all actions together, with exit at end for each one
			bodies: emitter/chunks/empty
			list: tail list								;-- point to last action
			until [										;-- left join all actions in reverse order		
				body: first list: back list
				unless empty? bodies/1 [
					emitter/branch/over bodies			;-- insert case exit branching
				]
				bodies: emitter/chunks/join body bodies	;-- left join action with other actions		
				change at values 2 * index? list length? bodies/1
				head? list		
			]
			
			;-- insert default clause or jump to runtime error
			either default [
				emitter/branch/over bodies          	;-- insert default exit branching
				bodies: emitter/chunks/join default/2 bodies ;-- insert default action
			][
				body: comp-chunked [raise-runtime-error 101] ;-- raise a runtime error if unmatched value
				bodies: emitter/chunks/join body bodies
			]

			;-- construct tests + branching and insert them at head
			last-type: save-type
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			values: tail values
			until [
				values: skip values -2
				foreach v values/1 [					;-- process multiple values per action
					body: comp-chunked [
						emitter/target/emit-integer-operation '= reduce [<last> v]
					]
					emitter/branch/over/on/adjust bodies [=] values/2	;-- insert action branching			
					bodies: emitter/chunks/join body bodies
				]
				head? values
			]
			emitter/merge bodies						;-- commit all to main code buffer	
			
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-until: has [expr chunk][
			pc: next pc
			check-body pc/1
			set [expr chunk] comp-block-chunked/test 'until
			emitter/branch/back/on chunk expr/1	
			emitter/merge chunk	
			last-type: none-type
			<last>
		]
		
		comp-while: has [expr unused cond body offset bodies][
			pc: next pc
			check-body pc/1								;-- check condition block
			check-body pc/2								;-- check body block
			
			set [expr cond]   comp-block-chunked/test 'while	;-- Condition block
			set [unused body] comp-block-chunked		;-- Body block
			
			if logic? expr/1 [expr: [<>]]				;-- re-encode test op
			offset: emitter/branch/over body			;-- Jump to condition
			bodies: emitter/chunks/join body cond
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/back/on/adjust bodies reduce [expr/1] offset ;-- Test condition, exit if FALSE
			emitter/merge bodies
			last-type: none-type
			<last>
		]
		
		comp-expression-list: func [/_all /local list offset bodies op][
			pc: next pc
			check-body pc/1								;-- check body block
			
			list: make block! 8
			pc: fetch-into pc/1 [
				while [not tail? pc][					;-- comp all expressions in chunks
					append/only list comp-block-chunked/only/test pick [all any] to logic! _all
				]
			]
			list: back tail list
			set [offset bodies] emitter/chunks/make-boolean			;-- emit ending FALSE/TRUE block
			if _all [emitter/branch/over/adjust bodies offset/1]	;-- conclude by a branch on TRUE
			offset: pick offset not _all				;-- branch to TRUE or FALSE 
			
			until [										;-- left join all expr in reverse order			
				op: either logic? list/1/1/1 [first [<>]][list/1/1/1]
				unless _all [op: reduce [op]]			;-- do not invert the test if ANY
				emitter/set-signed-state list/1/1		;-- properly set signed/unsigned state
				emitter/branch/over/on/adjust bodies op offset		;-- first emit branch				
				bodies: emitter/chunks/join list/1/2 bodies			;-- then left join expr
				also head? list	list: back list
			]	
			emitter/merge bodies
			last-type: [logic!]
			<last>
		]
		
		comp-assignment: has [name value n enum ns][
			push-call name: pc/1
			pc: next pc
			if set-word? name [
				n: to word! name
				unless any [locals local-variable? n][store-ns-symbol n]
				
				unless all [
					local-variable? n
					n = 'context						;-- explicitly allow 'context name for local variables
				][
					check-keywords n					;-- forbid keywords redefinition
				]
				if find definitions n [
					backtrack name
					throw-error ["redeclaration of definition" name]
				]
				if all [
					not local-variable? n
					enum: enum-id? n
				][
					backtrack name
					throw-error ["redeclaration of enumerator" name "from" enum]
				]
				if all [
					get-word? pc/1
					find functions to word! pc/1
				][
					throw-error "storing a function! requires a type casting"
				]
				unless local-variable? n [
					if all [ns-path none? locals][add-ns-symbol pc/-1]
					if all [ns: resolve-ns n ns <> n][name: to set-word! ns]
					check-func-name/only to word! name	;-- avoid clashing with an existing function name		
				]
			]
			if set-path? name [
				unless any [name/1 = 'system local-variable? name/1][
					name: resolve-ns-path name
				]
				if all [series? name value: system-reflexion? name][name: value]
			]
			
			either none? value: fetch-expression [		;-- explicitly test for none!
				none
			][
				new-line/all reduce [name value] no
			]
		]
		
		comp-func-args: func [name [word!] entry [hash!] /local attribute fetch expr args n pos][
			push-call name
			pc: next pc							;-- it's a function
			either attribute: check-variable-arity? entry/2/4 [
				fetch: [
					pos: pc
					expr: fetch-expression
					either attribute = 'typed [
						if all [expr = <last> none? last-type/1][
							pc: pos
							throw-error "expression has no defined return type"
						]
						append args id: get-type-id expr
						append/only args expr
						append args pick [#_ 0] id = emitter/datatype-ID/float! ;-- 32-bit padding
					][
						append/only args expr
					]
				]
				args: make block! 1
				either block? pc/1 [
					fetch-into pc/1 [until [do fetch tail? pc]]
					pc: next pc					;-- jump over arguments block
				][
					do fetch
				]
				reduce [name to-issue attribute args]
			][									;-- fixed arity case
				args: make block! n: entry/2/1
				loop n [append/only args fetch-expression]	;-- fetch n arguments
				new-line/all head insert/only args name no
			]
		]
		
		resolve-ns-path: func [path [path! set-path!] /local new pos][
			new: resolve-ns/path path/1					;-- try to prefix path/1

			either find/only ns-list to path! new [		;-- check if (prefixed) path/1 is a namespace
				new: to path! new
				until [									;-- collect all ns prefixes from head
					path: next path
					append new path/1					;-- move each path value to new one
					not find/only ns-list new			;-- while the new path is still a namespace
				]
				new: ns-decorate new					;-- prefix and convert to word 
				unless tail? next path [				;-- if non-ns remains in path
					new: append to path! new next path	;-- convert back to path by adding non-ns remain 
				]
				if set-path? path [
					new: to either word? new [set-word!][set-path!] new
				]
				new
			][
				unless word? new [path/1: ns-decorate new]	;-- only prefix+convert path/1 if required
				path
			]
		]
		
		comp-path: has [path value ns type name][
			path: pc/1
			if #":" = first mold path/1 [
				throw-error "get-path! syntax is not supported"
			]
			either all [
				not local-variable? path/1
				path: resolve-ns-path path
				word? path
			][
				if value: get-enumerator path [
					last-type: [integer!]
					pc: next pc
					return value
				]
				comp-word/with path
			][
				case [
					value: system-reflexion? path [
						either path/2 = 'words [
							return comp-word/with/root value ;-- re-route to global word resolution
						][
							pc: next pc
						]
					]
					'function! = first type: resolve-path-type/short path [
						name: to word! form path
						check-specs name type/2
						clear-docstrings type/2
						add-function 'routine reduce [name none type/2] get-cconv type/2
						append last functions reduce [path 'local]
						return comp-func-args name skip tail functions -2
					]
					'else [
						comp-word/path path/1				;-- check if root word is defined
						last-type: resolve-path-type path
					]
				]
				any [value path]
			]
		]
		
		comp-get-word: has [spec name ns symbol][
			name: resolve-ns to word! pc/1
			comp-word/with/check name
			
			if all [
				spec: find functions name
				spec: spec/2
			][
				unless find [native routine] spec/2 [
					throw-error "get-word syntax only reserved for native functions for now"
				]
				if all [
					symbol: last expr-call-stack
					spec: find functions symbol
					spec/2/2 = 'import					;-- only flag it when passed to external calls
					spec/2/5 <> 'callback
				][
					append spec/2 'callback				;@@ force cdecl ????
				]
			]
			also to get-word! name pc: next pc
		]
		
		direct-match-ns: func [ctx [path!] name [word!] path /local ns][
			if all [
				any [
					all [ns-stack find/only ns-stack ctx]
					all [ns-path find/only ns-path ctx]
				]
				ns: find/only ns-list ctx
				find ns/2 name
			][
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join ctx name
			]
		]
		
		match-ns: func [name [word!] ctx [word! path!] path /local pos][
			either pos: find ns-stack either path? ctx [ctx/1][ctx][ ;-- match (1st) context with stack
				if path? ctx [							;-- context hierarchy to match with stack
					foreach level ctx [					;-- match each context with next one on stack
						if pos/1 <> level [return none]	;-- if doesn't match, prefix doesn't apply
						pos: next pos					;-- next stack entry
					]
				]
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join to path! ctx name	;-- prefix and convert back to word
			][
				none									;-- no match on stack
			]
		]
		
		resolve-ns: func [name [word!] /path /local ctx pos][
			unless ns-stack [return name]				;-- no current ns, pass-thru

			if ctx: find/skip sym-ctx-table name 2 [	;-- fetch context candidates
				ctx: ctx/2								;-- SELECT/SKIP on hash! unreliable!
				either block? ctx [						;-- more than one candidate
					all [								;-- try direct matching first
						pos: find/only ctx to path! load mold ns-stack	;-- safer to-path conversion
						return either path [
							ns-join to path! first pos name
						][
							ns-decorate ns-join first pos name
						]
					]
					ctx: tail ctx						;-- start from last defined context
					until [
						ctx: back ctx
						if value: any [
							match-ns name ctx/1 path 
							direct-match-ns ctx/1 name path
						][
							return value				;-- prefix name if context on stack
						]
						head? ctx
					]									;-- no match found, pass-thru
				][										;-- one parent context only
					name: any [
						match-ns name ctx path		 	;-- prefix name if context is on stack
						direct-match-ns ctx name path
						name
					]
				]
			]
			name
		]
	
		comp-word: func [
			/path symbol [word!]
			/with word [word!]
			/root										;-- system/words/* pass-thru
			/check										;-- check word validity, do not consume input
			/local entry name local? spec type
		][
			name: pc/1
			if name = shift-right-sym [name: '-**]		;-- replace '>>> words produced by Red layer

			name: any [
				word
				symbol
				all [local-variable? name name]			;-- pass-thru for locals
				all [not root resolve-ns name]
				name
			]
			local?: local-variable? name
			case [
				all [
					not all [local? name = 'context]
					entry: select keywords name			;-- it's a reserved word
				][
					if find calling-keywords name [push-call pc/1]
					unless check [do entry]
				]
				any [
					all [
						local?
						any [
							all [						;-- block local function pointers
								block? type: select locals name
								'function! <> type/1
							]
							not block? type				;-- pass-thru
						]
					]
					all [
						find globals name
						'function! <> first get-type name	;-- block function pointers
					]
				][										;-- it's a variable
					if not-initialized? name [
						throw-error ["local variable" name "used before being initialized!"]
					]
					last-type: resolve-type name
					unless check [also name pc: next pc]
				]
				type: enum-type? name [
					last-type: type
					if verbose >= 3 [print ["ENUMERATOR" name "=" last-type]]
					unless check [also name pc: next pc]
				]
				all [
					not path
					entry: find-functions name
				][
					spec: entry/2/4
					if all [
						find-attribute spec 'infix
						path? pc/1
					][
						throw-error "infix functions cannot be called using a path"
					]
					unless check [comp-func-args name entry]
				]
				'else [throw-error ["undefined symbol:" mold name]]
			]
		]
		
		cast-null: func [variable [set-word! set-path!] /local casting][
			unless all [
				attempt [
					casting: get-type any [
						all [set-word? variable	to word! variable]
						to path! variable
					]
				]
				any-pointer? casting
			][
				backtrack variable
				throw-error "Invalid null assignment"
			]			
			casting
		]
		
		order-args: func [name [word!] args [block!]][
			if any [
				all [
					find [import native infix routine] functions/:name/2
					find [stdcall cdecl] functions/:name/3
				]
				all [
					functions/:name/2 = 'syscall
					job/syscall = 'BSD
				]
				all [
					functions/:name/2 = 'syscall		
					job/target = 'ARM					;-- odd, but required for Linux/ARM syscalls
					job/syscall = 'Linux
				]
			][		
				reverse args
			]
		]
		
		external-call?: func [spec [block!] /local attribs][
			to logic! any [
				spec/5 = 'callback
				all [
					attribs: get-attributes spec/4
					any [find attribs 'cdecl find attribs 'stdcall]
				]
			]
		]

		comp-call: func [
			name [word!] args [block!] /sub
			/local list type res align? left right dup var-arity? saved? arg expr spec
		][
			name: decorate-fun name
			list: either issue? args/1 [				;-- bypass type-checking for variable arity calls
				args/2
			][
				check-arguments-type name args
				args
			]
			order-args name list						;-- reorder argument according to cconv

			spec: functions/:name
			align?: all [
				args/1 <> #custom
				any [
					spec/2 = 'import					;@@ syscalls don't seem to need special alignment??
					all [spec/2 = 'routine external-call? spec]
				]
			]
			if align? [emitter/target/emit-stack-align-prolog args]
			
			if args/1 <> #custom [
				type: functions/:name/2
				either type <> 'op [
					forall list [						;-- push function's arguments on stack
						expr: list/1
						if block? unbox expr [comp-expression expr yes]	;-- nested call
						if object? expr [cast expr]
						if type <> 'inline [
							emitter/target/emit-argument expr functions/:name ;-- let target define how arguments are passed
						]
					]
				][										;-- nested calls as op argument require special handling
					if block? unbox list/1 [comp-expression list/1 yes]	;-- nested call
					left:  unbox list/1
					right: unbox list/2
					if saved?: all [block? left any [block? right path? right]][
						emitter/target/emit-save-last	;-- optionally save left argument result
					]
					if block? unbox list/2 [comp-expression list/2 yes]	;-- nested call
					if saved? [emitter/target/emit-restore-last]
				]
			]
			res: emitter/target/emit-call name args to logic! sub

			either res [
				last-type: res
			][
				set-last-type functions/:name/4			;-- catch nested calls return type
			]
			if align? [emitter/target/emit-stack-align-epilog args]
			res
		]
				
		comp-path-assign: func [
			set-path [set-path!] expr casted [block! none!]
			/local type new value
		][
			value: unbox expr
			if find [block! path! tag!] type?/word value [
				emitter/target/emit-move-path-alt		;-- save assigned value
			]
			if all [
				not local-variable? set-path/1
				enum-id? set-path/1
			][
				backtrack set-path
				throw-error ["enumeration cannot be used as path root:" set-path/1]
			]
			unless get-variable-spec set-path/1 [
				backtrack set-path
				throw-error ["unknown path root variable:" set-path/1]
			]
			type: resolve-path-type set-path			;-- check path validity
			new: resolve-aliased get-type expr		

			if type <> any [casted new][
				backtrack set-path
				throw-error [
					"type mismatch on setting path:" to path! set-path
					"^/*** expected:" mold type
					"^/*** found:" mold any [casted new]
				]
			]		
			emitter/access-path set-path either any [block? value path? value][
				 <last>
			][
				expr
			]
		]
		
		comp-variable-assign: func [
			set-word [set-word!] expr casted [block! none!]
			/local name type new value fun-name
		][
			name: to word! set-word		
			if find aliased-types name [
				backtrack set-word
				throw-error "name already used for as an alias definition"
			]
			if not-initialized? name [
				init-local name expr casted				;-- mark as initialized and infer type if required
			]

			if all [
				casted
				casted/1 = 'function!
				local-variable? name
			][
				fun-name: decorate-function name
				add-function 'routine reduce [fun-name none casted/2] get-cconv casted/2
				append last functions reduce [name 'local]
			]
			
			either type: any [
				get-variable-spec name					;-- test if known variable (local or global)	
				enum-id? name
			][
				type: resolve-aliased type
				value: get-type expr
				if block? expr [parse value [type-spec]] ;-- prefix return type if required	
				new: resolve-aliased value
				
				if type <> any [casted new][
					backtrack set-word
					throw-error [
						"attempt to change type of variable:" name
						"^/*** from:" mold type
						"^/***   to:" mold any [casted new]
					]
				]
			][
				unless zero? block-level [
					backtrack set-word
					throw-error "variable not declared"
				]
				if any [
					all [casted casted/1 = 'function!]
					all [expr = <last> casted: last-type last-type/1 = 'function!]
				][
					add-function 'routine reduce [name none casted/2] get-cconv casted/2
				]
				type: add-symbol name unbox expr casted  ;-- if unknown add it to global context	
			]
			if none? type/1 [
				backtrack set-word
				throw-error ["unable to determine a type for:" name]
			]
			value: unbox expr
			if any [block? value path? value][value: <last>]
			emitter/store name value type
		]
		
		comp-expression: func [expr keep? [logic!] /local variable boxed casting new? type][
			;-- preprocessing expression
			if all [block? expr find [set-word! set-path!] type?/word expr/1][
				variable: expr/1
				expr: expr/2							;-- switch to assigned expression
				if set-word? variable [
					new?: not exists-variable? variable
				]
			]			
			if object? expr [							;-- unbox type-casting object
				if all [variable expr/action = 'null][
					casting: cast-null variable
				]
				boxed: expr
				expr: either any-float? boxed/type [cast/quiet expr][cast expr]
			]
			
			;-- dead expressions elimination
			if all [
				not keep?
				not any [tail? pc variable]				;-- not last expression nor assignment value
				1 >= length? expr-call-stack			;-- one (for math op) or no parent call
				'switch <> pick tail expr-call-stack -1
				any [
					all [
						any [
							word? expr 					;-- variable alone
							literal? expr				;-- literal, but not logic value
						]
						'logic! <> first get-type expr
					]
					all [
						block? expr
						functions/(decorate-fun expr/1)/2 = 'op	;-- math expression
						any [							;-- no return value, or return value type <> logic!
							not type: find functions/(expr/1)/4 return-def
							type/2/1 <> 'logic!
						]
					]
				]
			][exit]

			;-- emitting expression code
			either block? expr [
				type: comp-call expr/1 next expr 		;-- function call case (recursive)
				if type [last-type: type]				;-- set last-type if not already set
				if all [
					variable boxed						;-- process casting if result assigned to variable
					last-type/1 = 'logic!
					boxed/type  = 'integer!				;-- fixes #967
				][
					emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
					last-type: boxed/type
				]
			][
				last-type: either not any [
					all [new? literal? unbox expr]		;-- if new variable, value will be store in data segment
					all [set-path? variable not path? expr]	;-- value loaded at lower level
					tag? unbox expr
				][
					emitter/target/emit-load either boxed [boxed][expr]	;-- emit code for single value
					either all [boxed not decimal? unbox expr][
						emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
						boxed/type
					][
						resolve-expr-type expr
					]
				][
					resolve-expr-type expr
				]
			]
			
			;-- postprocessing result
			if all [
				any [
					keep?
					variable							;-- result needs to be stored
					all [
						'case = pick tail expr-call-stack -3
						#test <> pick tail expr-call-stack -2
						4 <= length? expr-call-stack
					]
				]
				block? expr								;-- and if expr is a function call		
				last-type/1 = 'logic!					;-- which return type is logic!
			][
				emitter/logic-to-integer expr/1			;-- runtime logic! conversion before storing
			]
			
			if all [									;-- clean FPU stack when required
				not any [keep? variable]
				block? expr
				word? expr/1
				any-float? get-return-type/check expr/1
				any [
					not find functions/(expr/1)/4 return-def	;-- clean if no return value
					1 = length? expr-call-stack					;-- or if return value not used
				]
			][
				emitter/target/emit-float-trash-last	;-- avoid leaving a x86 FPU slot occupied,
			]											;-- if return value is not used.
			
			;-- storing result if assignement required
			if variable [
				if all [boxed not casting][
					casting: resolve-aliased boxed/type
				]
				unless boxed [boxed: expr]
				switch type?/word variable [
					set-word! [comp-variable-assign variable expr casting]
					set-path! [comp-path-assign		variable boxed casting]
				]
			]
		]
		
		check-enum-symbol: func [code [any-block!] /local value][
			if all [									;-- if enum, replace it with its integer value
				word? code/1
				not local-variable? code/1
				value: get-enumerator resolve-ns code/1
			][
				change code value
			]
		]
		
		infix?: func [pos [block! paren!] /local specs][
			all [
				not tail? pos
				word? pos/1
				specs: find functions resolve-ns pos/1
				specs: specs/2
				find [op infix] specs/2
			]
		]
		
		check-infix-operators: has [pos][
			if infix? pc [
				either infix? back tail expr-call-stack [
					exit								;-- infix op already processed
				][
					throw-error "invalid use of infix operator"
				]
			]
			if infix? next pc [
				either find [set-word! set-path! struct!] type?/word pc/1 [
					throw-error "can't use infix operator here"
				][
					pos: 0								;-- relative index of next infix op
					until [								;-- search for all dependent infix op
						pos: pos + 2					;-- target next infix possible position
						insert pc pc/:pos				;-- transform to prefix notation
						remove at pc pos + 1
						not infix? at pc pos + 2		;-- exit when no more infix op found
					]
				]
			]
		]
		
		fetch-expression: func [/final /keep /local expr pass value][
			check-infix-operators
			
			if verbose >= 4 [print ["<<<" mold pc/1]]
			pass: [also pc/1 pc: next pc]
			
			if tail? pc [
				pc: back pc
				throw-error "missing argument"
			]
			if job/debug? [store-dbg-lines]
			
			check-enum-symbol pc

			expr: switch/default type?/word pc/1 [
				set-word!	[comp-assignment]
				word!		[comp-word]
				get-word!	[comp-get-word]
				path! 		[comp-path]
				set-path!	[comp-assignment]
				paren!		[comp-block/only]
				char!		[do pass]
				integer!	[do pass]
				string!		[do pass]
				decimal!	[do pass]
				block!		[also to paren! pc/1 pc: next pc]
				issue!		[comp-directive]
			][
				throw-error "datatype not allowed"
			]
			expr: reduce-logic-tests expr

			if final [
				if verbose >= 3 [?? expr]
				unless find [none! tag!] type?/word expr [
					comp-expression expr to logic! keep
				]
			]
			expr
		]
		
		comp-block: func [/final /only /local expr save-pc][
			block-level: block-level + 1
			save-pc: pc
			pc: pc/1

			either only [
				expr: either final [fetch-expression/final][fetch-expression]
				unless tail? pc [
					throw-error "more than one expression found in parentheses"
				]
			][
				while [not tail? pc][
					;if all [paren? pc/1 not infix? at pc 2][raise-paren-error]
					expr: either final [fetch-expression/final][fetch-expression]
					unless tail? pc [pop-calls]
				]
			]
			pc: next save-pc
			
			block-level: block-level - 1
			expr
		]
		
		comp-dialect: has [expr][
			block-level: 0
			while [not tail? pc][
				case [
					issue? pc/1 [comp-directive]
					all [
						set-word? pc/1
						find [func function] pc/2
					][
						pc: next pc
						fetch-func pc/-1				;-- allow function declaration at root level only
					]
					all [set-word? pc/1 pc/2 = 'alias][
						pc: next pc
						comp-alias						;-- allow alias declaration at root level only
					]
					paren? pc/1 [
						;unless infix? at pc 2 [raise-paren-error]
						expr: fetch-expression/final/keep
					]
					'else [expr: fetch-expression/final/keep]
				]
				pop-calls
				emitter/target/on-root-level-entry
			]
			expr
		]
		
		comp-func-body: func [
			name [word!] spec [block!] body [block!]
			/local args-sz local-sz expr ret
		][
			locals: spec
			func-name: name
			set [args-sz local-sz] emitter/enter name locals ;-- build function prolog
			pc: body
			
			expr: comp-dialect							;-- compile function's body
			
			if ret: select spec return-def [
				check-expected-type/ret name expr ret	;-- validate return value type
				if all [
					object? expr 
					find [block! tag!] type?/word expr/data
				][
					emitter/target/emit-casting expr no	;-- insert runtime type casting when required
					last-type: expr/type
				]
			]
			emitter/leave name locals args-sz local-sz	;-- build function epilog
			remove-func-pointers
			clear locals-init
			locals: func-name: none
		]
		
		comp-natives: does [			
			foreach [name spec body origin ns nss] natives [
				if verbose >= 2 [
					print [
						"---------------------------------------^/"
						"function:" name newline
						"---------------------------------------"
					]
				]
				script: origin
				ns-path: ns
				ns-stack: nss
				comp-func-body name spec body
			]
		]
		
		comp-header: has [pos][
			unless pc/1 = 'Red/System [
				throw-error "source is not a Red/System program"
			]
			pc: next pc
			unless block? pc/1 [
				throw-error "missing Red/System program header"
			]
			unless parse pc/1 [any [pos: set-word! skip]][
				throw-error ["invalid program header at:" mold pos]
			]
			pc: next pc
		]
		
		get-proto: func [name [word!]][
			switch/default job/OS [
				Windows [
					[handle [integer!]]
				]
				MacOSX [
					pick [
						[
							argc	[integer!]
							argv	[struct! [s [c-string!]]]
							envp	[struct! [s [c-string!]]]
							apple	[struct! [s [c-string!]]]
							pvars	[program-vars!]
						]
						[[cdecl]]
					] name = 'on-load
				]
			][											;-- Linux
				[[cdecl]]
			]
		]
		
		add-dll-callbacks: has [list code exp][			;-- add missing callbacks
			list: copy [on-load on-unload]
			if job/OS = 'Windows [
				append list [on-new-thread on-exit-thread]
			]
			code: make block! 1
			exp:  make block! 1
			
			foreach fun list [
				unless find/skip natives fun 6 [
					repend code [
						to set-word! fun 'func get-proto fun []	;-- stdcall
					]
				]
			]
			unless empty? code [
				pc: code
				comp-dialect
			]
		]

		run: func [obj [object!] src [block!] file [file!] /no-header /runtime /no-events][
			runtime: to logic! runtime
			job: obj
			pc: src
			script: secure-clean-path file
			unless no-header [comp-header]
			unless no-events [emitter/target/on-global-prolog runtime job/type]
			comp-dialect
			unless no-events [
				case [
					runtime [
						emitter/target/on-global-epilog yes	job/type ;-- postpone epilog event after comp-runtime-epilog
					]
					not job/runtime? [
						emitter/target/on-global-epilog no job/type
					]
				]
			]
		]
		
		finalize: does [
			if verbose >= 2 [print "^/---^/Compiling native functions^/---"]
			if job/type = 'dll [
				if empty? exports [
					throw-error "missing #export directive for library production"
				]
				add-dll-callbacks 						;-- make sure they are defined
			]
			comp-natives
			emitter/target/on-finalize
			if verbose >= 2 [print ""]
			emitter/reloc-native-calls
		]
	]
	
	set-verbose-level: func [level [integer!]][
		foreach ctx reduce [
			self
			loader
			compiler
			emitter
			emitter/target
			linker
		][
			ctx/verbose: level
		]
	]
	
	output-logs: does [
		case/all [
			verbose >= 1 [
				print [
					nl
					"-- compiler/globals --" nl mold new-line/all/skip to-block compiler/globals yes 2 nl
					"-- emitter/symbols --"  nl mold new-line/all/skip to-block emitter/symbols yes 2 nl
				]
			]
			verbose >= 2 [
				print [
					"-- compiler/functions --" nl mold new-line/all/skip to-block compiler/functions yes 2 nl
				]
			]
			verbose >= 6 [
				print [
					"-- emitter/code-buf --" nl mold emitter/code-buf nl
					"-- emitter/data-buf --" nl mold emitter/data-buf nl
					"as-string:"        	 nl mold as-string emitter/data-buf nl
				]
			]
		]
	]
	
	emit-main-prolog: has [name spec][
		either job/type = 'exe [
			emitter/target/on-init
		][												;-- wrap global code in a function
			name: '***-main
			compiler/add-function 'native reduce [name none []] 'stdcall
			spec: emitter/add-native name
			spec/2: 1
			emitter/target/emit-prolog name [] 0
		]
	]

	comp-start: has [script][
		emitter/libc-init?: yes
		emitter/start-prolog
		script:	either encap? [
			set-cache-base %system/runtime/
			%start.reds
		][
			secure-clean-path runtime-path/start.reds
		]
 		compiler/run/no-events job loader/process/own script script
 		emitter/start-epilog
 
		;-- selective clean-up of compiler's internals
 		remove/part find compiler/globals 'system 2		;-- avoid 'system redefinition clash
 		remove/part find emitter/symbols 'system 4
		clear compiler/definitions
		clear compiler/aliased-types
		emitter/libc-init?: no
	]
	
	comp-runtime-prolog: func [red? [logic!] /local script][
		script: either encap? [
			set-cache-base %system/runtime/
			%common.reds
		][
			secure-clean-path runtime-path/common.reds
		]
 		compiler/run/runtime job loader/process/own script script
 		
 		if red? [
 			unless empty? red/sys-global [
				set-cache-base %./
				compiler/run job loader/process red/sys-global %***sys-global.reds
 			]
 			set-cache-base %runtime/
 			script: pick [%red.reds %../runtime/red.reds] encap?
 			compiler/run job loader/process/own script script
 		]
 		set-cache-base none
	]
	
	comp-runtime-epilog: does [
		either job/need-main? [
			emitter/target/on-global-epilog no job/type	;-- emit main() epilog
		][
			switch job/type [
				exe [compiler/comp-call '***-on-quit [0 0]]	;-- call runtime exit handler
				dll [emitter/target/emit-epilog '***-main [] 0 0]
				drv [emitter/target/emit-epilog '***-main [] 0 0]
			]
		]
	]
	
	clean-up: does [
		compiler/ns-path: 
		compiler/ns-stack: 
		compiler/locals: none
		compiler/resolve-alias?:  yes
		
		clear compiler/imports
		clear compiler/exports
		clear compiler/natives
		clear compiler/ns-list
		clear compiler/sym-ctx-table
		clear compiler/globals
		clear compiler/definitions
		clear compiler/enumerations
		clear compiler/aliased-types
		clear compiler/user-functions
		clear compiler/debug-lines/records
		clear compiler/debug-lines/files
		clear emitter/symbols
	]
	
	make-job: func [opts [object!] file [file!] /local job][
		job: construct/with third opts linker/job-class	
		file: last split-path file					;-- remove path
		file: to-file first parse file "."			;-- remove extension
		case [
			none? job/build-basename [
				job/build-basename: file
			]
			slash = last job/build-basename [
				append job/build-basename file
			]
		]
		job
	]
	
	set 'dt func [code [block!] /local t0][
		t0: now/time/precise
		do code
		now/time/precise - t0
	]
	
	compile: func [
		files [file! block!]							;-- source file or block of source files
		/options
			opts [object!]
		/loaded 										;-- source code is already in LOADed format
			src	[block!]
		/local
			comp-time link-time err output
	][
		comp-time: dt [
			unless block? files [files: reduce [files]]
			
			unless opts [opts: make options-class []]
			job: make-job opts last files				;-- last input filename is retained for output name
			emitter/init opts/link? job
			if opts/verbosity >= 10 [set-verbose-level opts/verbosity]
			
			clean-up
			loader/init
			emit-main-prolog
			
			job/need-main?: to logic! any [
				job/need-main?							;-- pass-thru if set in config file
				all [
					job/type = 'exe
					not find [Windows MacOSX] job/OS
				]
			]
			
			if all [
				job/need-main?
				not opts/use-natives?
				opts/runtime?
			][
				comp-start								;-- init libC properly
			]
			
			if opts/runtime? [comp-runtime-prolog to logic! loaded]
			
			set-verbose-level opts/verbosity
			foreach file files [
				src: either loaded [
					loader/process/with src file
				][
					loader/process file
				]
				compiler/run job src file
			]
			set-verbose-level 0
			if opts/runtime? [comp-runtime-epilog]
			
			set-verbose-level opts/verbosity
			compiler/finalize							;-- compile all functions
			set-verbose-level 0
		]
		if verbose >= 5 [
			print [
				"-- emitter/code-buf (empty addresses):"
				nl mold emitter/code-buf nl
			]
		]

		if opts/link? [
			link-time: dt [
				job/symbols: emitter/symbols
				job/sections: compose/deep/only [
					code   [- 	(emitter/code-buf)]
					data   [- 	(emitter/data-buf)]
					import [- - (compiler/imports)]
				]
				if not empty? compiler/exports [
					append job/sections compose/deep/only [
						export [- - (compiler/exports)]
					]
				]
				if opts/debug? [
					job/debug-info: reduce ['lines compiler/debug-lines]
				]
				output: linker/build job
			]
		]
		
		set-verbose-level opts/verbosity
		output-logs
		if opts/link? [clean-up]

		reduce [
			comp-time
			link-time
			any [all [job/buffer length? job/buffer] 0]
			output
		]
	]
]
#!/usr/bin/Rscript

library(lme4)
library(coefplot2)
library(glmmADMB)
library(Hmisc)
library(ggplot2)

load('flows-checkpoint3.RData')

## Refit with glmmadmb due to warnings about gradients above tolerance with lme4 fits

modNames <- c('glmeundirhmax', 'glmedirhmax', 'glmehmax')
fFin <- f[modNames]

tmpf <- function(x) {
    test <- !is.na(om$cases1WksAgo)
    data <- om[test, ]
    glmmadmb(x, data=data, family='nbinom')
}
mFin <- lapply(fFin, tmpf)
save.image('flows-checkpoint4.RData')

## Plot of predicted cases vs flow

scales <- c(week=iqr(om$weekCent),
            internal=iqr(log(om$internalFlow)),
            cmedDense=iqr(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=iqr(log(om$undirectedFlow)),
            directeted=iqr(log(om$directedFlow)))
sink(file='scales.txt')
print(scales)
sink()

centers <- c(week=mean(om$weekCent),
            internal=mean(log(om$internalFlow)),
            cmedDense=mean(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=mean(log(om$undirectedFlow)),
            directeted=mean(log(om$directedFlow)))

fund <- fortify(m$glmeundirhmax, data=model.frame(m$glmeundirhmax))
stopifnot(all.equal(attributes(fund$logUndirectedFlowScaled)[["scaled:center"]], centers[['undirected']]))
stopifnot(all.equal(attributes(fund$logUndirectedFlowScaled)[["scaled:scale"]][["75%"]], scales[['undirected.75%']]))

theme_set(new=theme_classic())
fund$flow <- exp(scales['undirected.75%'] * as.numeric(fund$logUndirectedFlowScaled) + centers['undirected'])
fund$predCases <- exp(fund$.fitted)
fund$smoothpred <- predict(loess(predCases~flow, data=fund))

g <- ggplot(data=fund, aes(x=flow, y=predCases))
g <- g + geom_line(aes(y=smoothpred))
g <- g + geom_point(aes(x=I(flow + runif(flow, min=-5e5, max=5e5)), y=cases), col='red', alpha=0.5)
g <- g + labs(x='Flow (swine / year)', y='Cases')
g <- g + coord_trans(y="log1p") + ylim(0,100)
ggsave('flows-prediction.eps', width=4, height=4, pointsize=18, device=cairo_ps)
ggsave('flows-prediction.pdf', width=4, height=4, pointsize=18, device=cairo_pdf)

## Plots of fixed effects

ct <- lapply(mFin, function(x) coeftab(x)[, 1:2])

extractEsts <- function(pattern, type) {
  tmpf <- function(x) grep(pattern, rownames(x))
  inds <- lapply(ct, tmpf)
  res <- list()
  mapply(function(x, y) x[y, type], ct, inds)
}
  
patterns <- list(flow='Flow', dense='logCmedDenseScaled', week='weekCent', inf='Inf')
ests <- sapply(patterns, extractEsts, type='Estimate')
sds <- sapply(patterns, extractEsts, type='Std. Error')
weekIqr <- iqr(model.frame(m$glmedirhmax)$weekCent)
ests[, 'week'] <- ests[, 'week']*weekIqr
sds[, 'week'] <- sds[, 'week']*weekIqr

stopifnot(rownames(ests) == c('glmeundirhmax', 'glmedirhmax', 'glmehmax'))
ests <- cbind(ests, baseline=c(hund$maximum, hdir$maximum, hint$maximum))
sds <- cbind(sds, baseline=0)

tmpf <- function() {
    longnames <- c(flow='Scaled transport flow', inf='Cases last week', week='Scaled week', dense='Scaled farm density', baseline='Baseline risk') 
    pal <- c('black', 'orange', 'blue')
    pch <- 15:17
    for(i in seq_len(nrow(ests))){
        coefplot2(ests[i, ], sds[i, ], varnames=longnames[colnames(ests)],
                  offset=(i-1)/10, col=pal[i], add=i>1, pch=pch[i],
                  main="Regression estimates")
    }
    legend('topright', legend=c('undirected', 'directed', 'none'), col=pal, pch=pch, title='Interstate flow')
}

pdf('coefplot.pdf', width=5,height=4)
tmpf()
dev.off()
## This works better than making the ps with R for some reason
system('pdftops coefplot.pdf')

res <- 100
png('coefplot.png', width=5*res, height=4*res, res=res)
tmpf()
dev.off()


## Table of likelihoods, dispersion, parameters, random effects

getNBTheta <- function(x) {
    if(inherits(x, 'glmmadmb')) {
        summary(x)$alpha
    } else {
        as.numeric(strsplit(family(x)$family, split='\\(|\\)')[[1]][2])
    }
}
getLL <- function(x) as.numeric(logLik(x))
getSD <- function(x) as.numeric(sqrt(VarCorr(x)$stateF))
getdf <- function(x) attr(logLik(x), 'df')
getintercept <- function(x) fixef(x)['(Intercept)']

modList <- c(mFin, m[c('nbme', 'nbmeN')])
disp <- sapply(modList, getNBTheta)
llik <- sapply(modList, getLL)
resd <- sapply(modList, getSD)
df <- sapply(modList, getdf)
int <- sapply(modList, getintercept)

tmpf <- function() {
  tab <- data.frame(baseline=I('no'), int=unname(int), disp, resd, df, llik)
  rownames(tab) <- names(modList)
  tab[c('glmeundirhmax', 'glmedirhmax', 'glmehmax'), 'baseline'] <- 'yes'
  tab[, 'df'] <- tab[, 'df'] + ifelse(tab[, 'baseline'] == 'yes', 1, 0)
  aic <- 2*-tab[, 'llik'] + 2*tab[, 'df']
  tab <- cbind(tab, deltaAIC = aic - min(aic))
  flowTerm <- c(glmeundirhmax='undirected', glmedirhmax='directed', glmehmax='internal',
                nbme='internal', nbmeN='none')
  tab <- data.frame(flowTerm=flowTerm[rownames(tab)], tab)
  tf <- format.df(tab)
  align <- paste(attr(tf, "col.just"), collapse="|")
  align <- paste('|', align, '|', sep='')
  longnames <- c(flowTerm='\\bf Flow term', baseline='\\bf Fit $\\eta$',
                 disp='\\bf Intercept', df='\\bf d.f.', llik='\\bf Log lik.',
                 deltaAIC='\\bf $\\Delta$ AIC', resd='\\bf $\\hat{\\sigma}$',
                 int='{\\bf Intercept}')
  colnames(tab) <- longnames[colnames(tf)]
  tab <- latexTabular(tab, helvetica=FALSE, align=align, translate=FALSE,
                   cdec=c(0,0,1,2,2,0,1,1))
  tab <- gsub('\\\\multicolumn\\{1\\}\\{c\\}', '', tab)
  tab <- gsub('(\\\\)\\s?(\n)', '\\1\\\\hline\\2', tab)
  tab <- gsub('(\\n)(\\{\\\\bf Flow term\\})', '\\1\\\\hline\\2', tab)
  cat(tab, file='tab.tex')
  list(aic=aic, tab=tab)
}
tables <- tmpf()

## Dotplot of AICs

tmpf <- function() {
    tab <- tables$tab
    aic <- tables$aic
    flowTerm <- c(glmeundirhmax='Within-state + undirected between state',
                  glmedirhmax='Within-state + directed between state',
                  glmehmax='Within-state only',
                  nbme='Within-state only, fixed other risks ',
                  nbmeN='No flow, fixed other risks')
    labels <- flowTerm[rownames(tab)]
    dotchart2(tables$aic, labels=labels, xlab='AIC (i.e., Estimated information loss)', dotsize=2)
}
png('aic.png', width=7*res, height=4*res, res=res)
tmpf()
dev.off()

save.image('flows-checkpoint5.RData')

                                             
#!/usr/bin/Rscript

library(lme4)
library(coefplot2)
library(glmmADMB)
library(Hmisc)
library(ggplot2)

load('flows-checkpoint3.RData')

## Refit with glmmadmb due to warnings about gradients above tolerance with lme4 fits

modNames <- c('glmeundirhmax', 'glmedirhmax', 'glmehmax')
fFin <- f[modNames]

tmpf <- function(x) {
    test <- !is.na(om$cases1WksAgo)
    data <- om[test, ]
    glmmadmb(x, data=data, family='nbinom')
}
mFin <- lapply(fFin, tmpf)

## Plot of predicted cases vs flow

fund <- fortify(m$glmeundirhmax, data=model.frame(m$glmeundirhmax))
theme_set(new=theme_classic())

g <- ggplot(data=fund, aes(x=exp(logUndirectedFlowScaled), y=exp(.fitted)))
g <- g + geom_smooth(method='loess', alpha=0, size=2, color='black')
g <- g + geom_point(aes(x=I(runif(nrow(fund), min=-.1,max=.1) + exp(logUndirectedFlowScaled)),
                        y=cases), col='black', alpha=0.5)
g <- g + labs(x='Flow (swine / pairs / year)', y='Cases')
g <- g + coord_trans(y="log1p") + ylim(0,100)
ggsave('flows-prediction.eps', width=4, height=4, pointsize=18, device=cairo_ps)
ggsave('flows-prediction.pdf', width=4, height=4, pointsize=18, device=cairo_pdf)

## Plots of fixed effects

ct <- lapply(mFin, function(x) coeftab(x)[, 1:2])

extractEsts <- function(pattern, type) {
  tmpf <- function(x) grep(pattern, rownames(x))
  inds <- lapply(ct, tmpf)
  res <- list()
  mapply(function(x, y) x[y, type], ct, inds)
}
  
patterns <- list(flow='Flow', dense='logCmedDenseScaled', week='weekCent', inf='Inf')
ests <- sapply(patterns, extractEsts, type='Estimate')
sds <- sapply(patterns, extractEsts, type='Std. Error')
weekIqr <- iqr(model.frame(m$glmedirhmax)$weekCent)
ests[, 'week'] <- ests[, 'week']*weekIqr
sds[, 'week'] <- sds[, 'week']*weekIqr

stopifnot(rownames(ests) == c('glmeundirhmax', 'glmedirhmax', 'glmehmax'))
ests <- cbind(ests, baseline=c(hund$maximum, hdir$maximum, hint$maximum))
sds <- cbind(sds, baseline=0)

tmpf <- function() {
    longnames <- c(flow='Scaled transport flow', inf='Cases last week', week='Scaled week', dense='Scaled farm density', baseline='Baseline risk') 
    pal <- c('black', 'orange', 'blue')
    pch <- 15:17
    for(i in seq_len(nrow(ests))){
        coefplot2(ests[i, ], sds[i, ], varnames=longnames[colnames(ests)],
                  offset=(i-1)/10, col=pal[i], add=i>1, pch=pch[i],
                  main="Regression estimates")
    }
    legend('topright', legend=c('undirected', 'directed', 'none'), col=pal, pch=pch, title='Interstate flow')
}

pdf('coefplot.pdf', width=5,height=4)
tmpf()
dev.off()
## This works better than making the ps with R for some reason
system('pdftops coefplot.pdf')

res <- 100
png('coefplot.png', width=5*res, height=4*res, res=res)
tmpf()
dev.off()


## Table of likelihoods, dispersion, parameters, random effects

getNBTheta <- function(x) {
    if(inherits(x, 'glmmadmb')) {
        summary(x)$alpha
    } else {
        as.numeric(strsplit(family(x)$family, split='\\(|\\)')[[1]][2])
    }
}
getLL <- function(x) as.numeric(logLik(x))
getSD <- function(x) as.numeric(sqrt(VarCorr(x)$stateF))
getdf <- function(x) attr(logLik(x), 'df')
getintercept <- function(x) fixef(x)['(Intercept)']

modList <- c(mFin, m[c('nbme', 'nbmeN')])
disp <- sapply(modList, getNBTheta)
llik <- sapply(modList, getLL)
resd <- sapply(modList, getSD)
df <- sapply(modList, getdf)
int <- sapply(modList, getintercept)

tmpf <- function() {
  tab <- data.frame(baseline=I('no'), int=unname(int), disp, resd, df, llik)
  rownames(tab) <- names(modList)
  tab[c('glmeundirhmax', 'glmedirhmax', 'glmehmax'), 'baseline'] <- 'yes'
  tab[, 'df'] <- tab[, 'df'] + ifelse(tab[, 'baseline'] == 'yes', 1, 0)
  aic <- 2*-tab[, 'llik'] + 2*tab[, 'df']
  tab <- cbind(tab, deltaAIC = aic - min(aic))
  flowTerm <- c(glmeundirhmax='undirected', glmedirhmax='directed', glmehmax='internal',
                nbme='internal', nbmeN='none')
  tab <- data.frame(flowTerm=flowTerm[rownames(tab)], tab)
  tf <- format.df(tab)
  align <- paste(attr(tf, "col.just"), collapse="|")
  align <- paste('|', align, '|', sep='')
  longnames <- c(flowTerm='\\bf Flow term', baseline='\\bf Fit $\\eta$',
                 disp='\\bf Intercept', df='\\bf d.f.', llik='\\bf Log lik.',
                 deltaAIC='\\bf $\\Delta$ AIC', resd='\\bf $\\hat{\\sigma}$',
                 int='{\\bf Intercept}')
  colnames(tab) <- longnames[colnames(tf)]
  tab <- latexTabular(tab, helvetica=FALSE, align=align, translate=FALSE,
                   cdec=c(0,0,1,2,2,0,1,1))
  tab <- gsub('\\\\multicolumn\\{1\\}\\{c\\}', '', tab)
  tab <- gsub('(\\\\)\\s?(\n)', '\\1\\\\hline\\2', tab)
  tab <- gsub('(\\n)(\\{\\\\bf Flow term\\})', '\\1\\\\hline\\2', tab)
  cat(tab, file='tab.tex')
}
tmpf()

Scales <- C(week=iqr(om$weekCent),
            internal=iqr(log(om$internalFlow)),
            cmedDense=iqr(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=iqr(log(om$undirectedFlow)),
            directeted=iqr(log(om$directedFlow)))
sink(file='scales.txt')
print(scales)
sink()

## Dotplot of AICs

flowTerm <- c(glmeundirhmax='Within-state + undirected between state',
              glmedirhmax='Within-state + directed between state',
              glmehmax='Within-state only',
              nbme='Within-state only, fixed other risks ',
              nbmeN='No flow, fixed other risks')

png('aic.png', width=7*res, height=4*res, res=res)
dotchart2(aic, labels=flowTerm[rownames(tab)], xlab='AIC (i.e., Estimated information loss)', dotsize=2)
dev.off()

save.image('flows-checkpoint4.RData')

                                             
library = function (...) suppressMessages(base::library(..., quietly = TRUE))

library(knitr)
library(modules)
library(ggplot2)
library(reshape2)
library(dplyr)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot2

theme_set(theme_bw())

# Add more functionality to ggplot2

# Inverse hyperbolic sine gives a nice y scale, similar to log but which is also
# defined for zero values (and negative values).

asinh_trans = function ()
    scales::trans_new('asinh', asinh, sinh, domain = c(-Inf, Inf))

scale_y_asinh = function (...)
    scale_y_continuous(..., trans = asinh_trans())

# Manual boxplot, since ggplot2’s doesn’t support coloured outliers.
# <http://stackoverflow.com/q/8499378/1968>

geom_box = function (...) {
    fullbox = function (x) {
        box = setNames(quantile(x, c(0.25, 0.5, 0.75)),
                       c('lower', 'middle', 'upper'))
        iqr = box[3] - box[1]
        ymin = min(x[x >= box[1] - 1.5 * iqr])
        ymax = max(x[x <= box[3] + 1.5 * iqr])
        c(ymin = ymin, box, ymax = ymax)
    }
    stat_summary(fun.data = fullbox, geom = 'boxplot', ...)
}

geom_outliers = function (...) {
    outliers = function (x) {
        box = quantile(x, c(0.25, 0.75))
        iqr = box[2] - box[1]
        x[(x < box[1] - 1.5 * iqr) | (x > box[2] + 1.5 * iqr)]
    }
    stat_summary(fun.y = outliers, geom = 'point', ...)
}

# A boxplot with nice defaults

gg_boxplot = function (data, col_data) {
    data = melt(data, id.vars = 'Gene', variable.name = 'DO',
                value.name = 'Count') %>%
        inner_join(col_data, by = 'DO')
    ggplot(data, aes(factor(DO), Count, color = Celltype)) +
        geom_box() + geom_outliers(size = 1) +
        xlab('Library') +
        scale_y_asinh() +
        scale_fill_manual(values = celltype_colors) +
        theme_bw()
}

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(6,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL)
                                   ),
                            column(6,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map')
                                                    )

                                   )
                            ),

                          uiOutput('mapOrSetUI'),
                          conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                           jscolorInput('aesValueColor')),

                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          textInput('plotTitle', 'Plot Title'),
                          fluidRow(
                            column(6,
                                   textInput('plotXlab', 'X Axis Title')
                            ),
                            column(6,
                                   textInput('plotYlab', 'Y Axis Title')
                            )),
                          h4('Formatting'),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem')
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    strong('Font Color'), br(),
                                                    jscolorInput('textColor'), br(),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    strong('Border Color'), br(),
                                                    jscolorInput('rectColor'), br(),
                                                    strong('Fill'), br(),
                                                    jscolorInput('rectFill'), br(),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    strong('Line Color'), br(),
                                                    jscolorInput('lineColor'), br(),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   )

                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv'))


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(6,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL)
                                   ),
                            column(6,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map')
                                                    )

                                   )
                            ),

                          uiOutput('mapOrSetUI'),
                          conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                           jscolorInput('aesValueColor')),

                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          navlistPanel(id='customizeItem1', well=FALSE,
                                       tabPanel('Plot Title', value='plot.title',
                                                textInput('plotTitle', '')
                                       ),
                                       tabPanel('X Axis Title', value='axis.title.x',
                                                textInput('plotXlab', '')
                                       ),
                                       tabPanel('Y Axis Title', value='axis.title.y',
                                                textInput('plotYlab', '')
                                       )
                          ),
                          fluidRow(
                            column(6,
                                   shinyTree('customizeItem')
                                   ),
                            column(6,
                                   conditionalPanel('output.ggElementType!="unit" && output.ggElementType!="character" && output.ggElementType!=""',
                                                    checkboxInput('elementBlank', 'Hide Element', value=FALSE)),
                                   conditionalPanel('output.ggElementType=="element_text"',
                                                    selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                                    selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                                    strong('Font Color'), br(),
                                                    jscolorInput('textColor'), br(),
                                                    numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1),
                                                    numericInput('textHjust', 'Horizontal Adjustment', value=NULL, step=0.1),
                                                    numericInput('textVjust', 'Vertical Adjustment', value=NULL, step=0.1),
                                                    numericInput('textAngle', 'Angle (in [0,360])', value=NULL, step=1),
                                                    numericInput('textLineheight', 'Text Line Height', value=NULL, step=0.1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_rect"',
                                                    strong('Border Color'), br(),
                                                    jscolorInput('rectColor'), br(),
                                                    strong('Fill'), br(),
                                                    jscolorInput('rectFill'), br(),
                                                    numericInput('rectSize', 'Border Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('rectLinetype', 'Border Line Type', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="element_line"',
                                                    strong('Line Color'), br(),
                                                    jscolorInput('lineColor'), br(),
                                                    numericInput('lineSize', 'Line Width (pts)', value=NULL, step=0.1),
                                                    numericInput('lineLinetype', 'Line Type', value=NULL, step=1),
                                                    numericInput('lineLineend', 'Line End', value=NULL, step=1)
                                   ),
                                   conditionalPanel('output.ggElementType=="unit"',
                                                    numericInput('unitX', 'Value', value=NULL, step=0.1),
                                                    selectInput('unitUnits', 'Unit', choices=UnitChoices)
                                   )

                                   )
                            ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),


  tabPanel(title='Settings',

           if(!extrafontsImported){
             list(actionButton('importFonts', 'Import System Fonts'),
                  helpText('Import fonts from the operating system so that they are available for shinyData. This can take a few minutes.'))
           }

  ),

  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)
library(magrittr)
library(hexbin)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# spatial analysis see if county assignment went right
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.05), maptype='toner-lite') +
  guides(colour = guide_legend(override.aes = list(alpha=1)))

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 1700, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))


# tiemline
# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  theme(axis.text.x = element_text(angle=45, hjust=1))

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  coord_flip()

# smoothing
smooth <- function(y, x) {
  as.numeric(predict(gam(y ~ s(x), na.action = na.exclude)))
}

bigsum <- plyr::ddply(bigsum, plyr::.(city), transform,
                price_s = smooth(price, as.numeric(date)))
ggplot(bigsum, aes(date, price_s /1e6, group=city)) +
  geom_line()

index <- function(y, x) {
  y / y[order(x)[1]]
}
bigsum <- plyr::ddply(bigsum, plyr::.(city), transform,
                price_si = index(price_s, date))
ggplot(bigsum, aes(date, price_si /1e6, group=city, color=city)) +
  geom_line()

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city)

# get the peak and last price
covar <- arrange(bigsum, city, date) %>%
  group_by(city) %>%
  summarise(
    peak = max(price_si),
    plummet = last(price_si)
  )

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city)

ggplot(covar, aes(peak, plummet)) +
  geom_point()library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# spatial analysis see if county assignment went right
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.1), maptype='toner-lite')

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 100, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.3))

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))


# tiemline
# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  theme(axis.text.x = element_text(angle=45, hjust=1))

qplot(factor(date), m_price, data=big_monthly, geom="boxplot") +
  coord_flip()

# smooth
bigsum %>% do(model = gam(as.numeric(date) ~ s(price), data = .))


library = function (...) suppressMessages(base::library(...))
assign('library', library, globalenv())

library(knitr)
library(modules)
library(ggplot2)

options(stringsAsFactors = FALSE,
        import.path = c('scripts', file.path(Sys.getenv('HOME'), 'Projects/R')))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

# Configure ggplot

theme_set(theme_bw())

# Load standard helpers

local({base = import('ebits/base')}, globalenv())
local({io = import('ebits/io')}, globalenv())
local({fs = import('fs')}, globalenv())
REBOL [
	Title:   "Red Lexical Scanner"
	Author:  "Nenad Rakocevic"
	File: 	 %lexer.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

lexer: context [
	verbose: 0
	
	line: 	none									;-- source code lines counter
	lines:	[]										;-- offsets of newlines marker in current block
	count?: yes										;-- if TRUE, lines counter is enabled
	cnt:	none									;-- counts nested {} in multi-line strings
	pos:	none									;-- source input position (error reporting)
	s:		none									;-- mark start position of new value
	e:		none									;-- mark end position of new value
	value:	none									;-- new value
	fail?:	none									;-- used for failing some parsing rules
	type:	none									;-- define the type of the new value
	rs?:	no 										;-- if TRUE, do lexing for Red/System
	neg?:	no										;-- if TRUE, denotes a negative number value
	
	;====== Parsing rules ======

	four:  charset "01234"
	half:  charset "012345"
    non-zero: charset "123456789"
    digit: union non-zero charset "0"
    dot: #"."
    comma: #","

	byte: [
		"25" half
		| "2" four digit
		| "1" digit digit
		| non-zero digit
		| digit
	]

	hexa:  union digit charset "ABCDEF"
	hexa-char: union hexa charset "abcdef"
	
	;-- UTF-8 encoding rules from: http://tools.ietf.org/html/rfc3629#section-4
	UTF-8-BOM: #{EFBBBF}
	ws-ASCII:  charset " ^-^M"						;-- ASCII common whitespaces
	ws-U+2k:   charset [#"^(80)" - #"^(8A)"]		;-- Unicode spaces in the U+2000-U+200A range
	UTF8-tail: charset [#"^(80)" - #"^(BF)"]
	UTF8-1:    charset [#"^(00)" - #"^(7F)"]
	
	UTF8-2: reduce [
		charset [#"^(C2)" - #"^(DF)"]
		UTF8-tail
	]
	
	UTF8-3: reduce [
		#{E0} 	 charset [#"^(A0)" - #"^(BF)"] UTF8-tail
		'| 		 charset [#"^(E1)" - #"^(EC)"] 2 UTF8-tail
		'| #{ED} charset [#"^(80)" - #"^(9F)"] UTF8-tail
		'| 		 charset [#"^(EE)" - #"^(EF)"] 2 UTF8-tail
	]
	
	UTF8-4: reduce [
		#{F0} 	 charset [#"^(90)" - #"^(BF)"] 2 UTF8-tail
		'| 		 charset [#"^(F1)" - #"^(F3)"] 3 UTF8-tail
		'| #{F4} charset [#"^(80)" - #"^(8F)"] 2 UTF8-tail
	]
	
	UTF8-char: [pos: UTF8-1 | UTF8-2 | UTF8-3 | UTF8-4]
	
	not-word-char:  charset {/\^^,[](){}"#%$@:;}
	not-word-1st:	union union not-word-char digit charset {'}
	not-file-char:  charset {[](){}"@:;}
	not-url-char:	charset {[](){}";}
	not-str-char:   #"^""
	not-mstr-char:  #"}"
	caret-char:	    charset [#"^(40)" - #"^(5F)"]
	non-printable-char: charset [#"^(00)" - #"^(1F)"]
	integer-end:	charset {^{"[]);}
	stop: 		    none

	control-char: reduce [
		charset [#"^(00)" - #"^(1F)"] 				;-- ASCII control characters
		'| #"^(C2)" charset [#"^(80)" - #"^(9F)"] 	;-- C2 control characters
	]
	
	UTF8-filtered-char: [
		[pos: stop :pos (fail?: [end skip]) | UTF8-char e: (fail?: none)]
		fail?
	]
	
	UTF8-printable: [
		[non-printable-char | not-str-char (fail?: [end skip]) | UTF8-char (fail?: none)]
		fail?
	]
	
	;-- Whitespaces list from: http://en.wikipedia.org/wiki/Whitespace_character
	ws: [
		pos: #"^/" (
			if count? [
				line: line + 1 
				append/only lines to block! stack/tail?
			]
		)
		| ws-ASCII									;-- only the common whitespaces are matched
		| #{C2} [
			#{85}									;-- U+0085 (Newline)
			| #{A0}									;-- U+00A0 (No-break space)
		]
		| #{E1} [
			#{9A80}									;-- U+1680 (Ogham space mark)
			| #{A08E}								;-- U+180E (Mongolian vowel separator)
		]
		| #{E2} [
			#{80} [
				ws-U+2k								;-- U+2000-U+200A range
				| #{A8}								;-- U+2028 (Line separator)
				| #{A9}								;-- U+2029 (Paragraph separator)
				| #{AF}								;-- U+202F (Narrow no-break space)
			]
			| #{819F}								;-- U+205F (Medium mathematical space)
		]
		| #{E38080}									;-- U+3000 (Ideographic space)
	]
	
	newline-char: [
		#"^/"
		| #{C285}									;-- U+0085 (Newline)
		| #{E280} [
			#{A8}									;-- U+2028 (Line separator)
			| #{A9}									;-- U+2029 (Paragraph separator)
		]
	]
	
	counted-newline: [pos: #"^/" (line: line + 1)]
	
	ws-no-count: [(count?: no) ws (count?: yes)]
	
	any-ws: [pos: any ws]
	
	symbol-rule: [
		(stop: [not-word-char | ws-no-count | control-char])
		some UTF8-filtered-char e:
	]
	
	begin-symbol-rule: [							;-- 1st char in symbols is restricted
		(stop: [not-word-1st | ws-no-count | control-char])
		UTF8-filtered-char
		opt symbol-rule
	]
	
	path-rule: [
		pos: slash :pos (							;-- path detection barrier
			stack/push path!
			stack/push to type copy/part s e		;-- push 1st path element
		)
		some [
			slash
			s: [
				integer-number-rule
				| begin-symbol-rule			(type: word!)
				| paren-rule 				(type: paren!)
				| #":" s: begin-symbol-rule	(type: get-word!)
				;@@ add more datatypes here
			] (
				stack/push either type = paren! [	;-- append path element
					value
				][
					to type copy/part s e
				]
				type: path!
			)
			opt [#":" (type: set-path!)]
		]
		(value: stack/pop type)
	]
	
	word-rule: 	[
		(type: word!)
		#"%" ws-no-count (value: "%")				;-- special case for remainder op!
		| s: begin-symbol-rule [
			url-rule
			| path-rule 							;-- path matched
			| (value: copy/part s e)				;-- word matched
			  opt [#":" (type: set-word!)]
		] 
	]
	
	get-word-rule: [
		#":" (type: get-word!) s: begin-symbol-rule [
			path-rule (
				value/1: to get-word! value/1		;-- workaround missing get-path! in R2
			)
			| (
				type: get-word!
				value: copy/part s e				;-- word matched
			)
		]
	]
	
	lit-word-rule: [
		#"'" (type: word!) s: begin-symbol-rule [
			path-rule (type: lit-path!)				;-- path matched
			| (
				type: lit-word!
				value: copy/part s e				;-- word matched
			)
		]
	]
	
	issue-rule: [#"#" (type: issue!) s: symbol-rule]
	
	refinement-rule: [slash (type: refinement!) s: symbol-rule]
	
	slash-rule: [s: [slash opt slash] e:]
	
	hexa-rule: [2 8 hexa e: #"h" (type: integer!)]

	sticky-word-rule: [
		pos: [										;-- protection rule from typo with sticky words
			[integer-end | ws-no-count | end] (fail?: none)
			| skip (fail?: [end skip])
		] :pos
		fail?
	]

	tuple-value-rule: [
		(type: tuple!)
		byte dot byte 1 8 [dot byte | dot] e:
	]

	tuple-rule: [
		tuple-value-rule
		sticky-word-rule
	]
		
	integer-number-rule: [
		(type: integer!)
		opt [#"-" | #"+"] digit any [digit | #"'" digit] e:
	]
	
	integer-rule: [
		decimal-special									;-- escape path for NaN, INFs
		| integer-number-rule
		  opt [decimal-number-rule | decimal-exp-rule e: (type: decimal!)]
		  sticky-word-rule
	]

	decimal-special: [
		s: "-0.0" e: (type: issue!) |
			(neg?: no) opt [#"-" (neg?: yes)] "1.#" s: [
				[[#"N" | #"n"] [#"a" | #"A"] [#"N" | #"n"]]
				| [[#"I" | #"i"] [#"N" | #"n"] [#"F" | #"f"]]
		] e: (type: issue!)
	]
	
	decimal-exp-rule: [
		[[#"e" | #"E"] opt [#"-" | #"+"] 1 3 digit]
	]
	
	decimal-number-rule: [
		[dot | comma] digit any [digit | #"'" digit]
		opt decimal-exp-rule e: (type: decimal!)
	]

	decimal-rule: [
		decimal-number-rule
		sticky-word-rule
	]
		
	block-rule: [#"[" (stack/push block!) any-value #"]" (value: stack/pop block!)]
	
	paren-rule: [#"(" (stack/push paren!) any-value	#")" (value: stack/pop paren!)]
	
	escaped-char: [
		"^^(" [
			[										;-- special case first
				"null" 	 (value: #"^(00)")
				| "back" (value: #"^(08)")
				| "tab"  (value: #"^(09)")
				| "line" (value: #"^(0A)")
				| "page" (value: #"^(0C)")
				| "esc"  (value: #"^(1B)")
				| "del"	 (value: #"^(7F)")
			]
			| pos: [2 6 hexa-char] e: (				;-- Unicode values allowed up to 10FFFFh
					either rs? [
						value: to-char to-integer debase/base copy/part pos e 16
					][value: encode-UTF8-char pos e]
			)
		] #")"
		| #"^^" [
			[
				#"/" 	(value: #"^/")
				| #"-"	(value: #"^-")
				| #"?" 	(value: #"^(del)")
				| #"^^" (value: #"^^")				;-- caret escaping case
				| #"{"	(value: #"{")
				| #"}"	(value: #"}")
				| #"^""	(value: #"^"")
			]
			| pos: caret-char (value: pos/1 - 64)
		]
	]
	
	char-rule: [
		{#"} (type: char!) [
			s: escaped-char
			| copy value UTF8-printable (value: as-binary value)
			| #"^-" (value: s/1)
		] {"}
	]
	
	line-string: [
		{"} s: (type: string! stop: [not-str-char | newline-char])
		any [{^^"} | escaped-char | UTF8-filtered-char]
		e: {"}
	]
	
	nested-curly-braces: [
		(cnt: 1 fail?: none)
		any [
			[
				counted-newline 
				| "^^{" | "^^}"
				| #"{" (cnt: cnt + 1)
				| e: #"}" (if zero? cnt: cnt - 1 [fail?: [end skip]])
				| UTF8-char
			] fail?
		]
		#"}"
	]
	
	multiline-string: [#"{" s: (type: string!) nested-curly-braces]
	
	string-rule: [line-string | multiline-string]
	
	binary-rule: [
		"#{" (type: binary!) 
		s: any [counted-newline | 2 hexa-char | ws-no-count | comment-rule]
		e: #"}"
	]
	
	file-rule: [
		#"%" (type: file! stop: [not-file-char | ws-no-count])
		s: any UTF8-filtered-char e:
	]

	url-rule: [
		#":" (type: url! stop: [not-url-char | ws-no-count])
		some UTF8-filtered-char e: (value: dehex copy/part s e)
	]

	escaped-rule: [
		"#[" any-ws [
			  "true"  (value: true)
			| "false" (value: false)
			| s: [
				"none!" | "logic!" | "block!" | "integer!" | "word!" 
				| "set-word!" | "get-word!" | "lit-word!" | "refinement!"
				| "binary!" | "string!"	| "char!" | "bitset!" | "path!"
				| "set-path!" | "lit-path!" | "native!"	| "action!"
				| "issue!" | "paren!" | "function!"
			] e: (value: get to word! copy/part s e)
			| "none" (value: none)
		]  any-ws #"]"
	]
	
	comment-rule: [#";" [to #"^/" | to end]]
	
	wrong-delimiters: [
		pos: [
			  #"]" (value: #"[") | #")" (value: #"(")
			| #"[" (value: #"]") | #"(" (value: #")")
		] :pos
		(throw-error/with ["missing matching" value])
	]

	literal-value: [
		pos: (e: none) s: [
			comment-rule
			| escaped-rule    (stack/push value)
			| integer-rule	  (stack/push load-number    copy/part s e)
			| decimal-rule	  (stack/push load-decimal	 copy/part s e)
			| tuple-rule	  (stack/push to tuple!		 copy/part s e)
			| hexa-rule		  (stack/push decode-hexa	 copy/part s e)
			| word-rule		  (stack/push to type value)
			| lit-word-rule	  (stack/push to type value)
			| get-word-rule	  (stack/push to type value)
			| refinement-rule (stack/push to refinement! copy/part s e)
			| slash-rule	  (stack/push to word! 	   	 copy/part s e)
			| issue-rule	  (stack/push to issue!	   	 copy/part s e)
			| file-rule		  (stack/push load-file		 copy/part s e)
			| char-rule		  (stack/push decode-UTF8-char value)
			| block-rule	  (stack/push value)
			| paren-rule	  (stack/push value)
			| string-rule	  (stack/push load-string s e)
			| binary-rule	  (stack/push load-binary s e)
		]
	]
	
	any-value: [pos: any [literal-value | ws]]

	header: [
		pos: thru "Red" opt ["/System" (rs?: yes stack/push 'Red/System)]
		any-ws block-rule (stack/push value)
		| (throw-error/with "Invalid Red program") end skip
	]

	program: [
		pos: opt UTF-8-BOM
		header
		any-value
		opt wrong-delimiters
	]
	
	;====== Helper functions ======
	
	stack: context [
		stk: []
		
		push: func [value][
			either any [value = block! value = paren! value = path!][
				if value = path! [value: block!]
				insert/only tail stk value: make value 1
				value
			][
				insert/only tail last stk :value
			]
		]
		
		pop: func [type [datatype!]][
			if any [type = path! type = set-path!][type: block!]
			
			if type <> type? last stk [
				throw-error/with ["invalid" mold type "closing delimiter"]
			]
			also last stk remove back tail stk
		]
		
		tail?: does [tail last stk]
		reset: does [clear stk]
	]
	
	throw-error: func [/with msg [string! block!]][
		print rejoin [
			"*** Syntax Error: " either with [
				uppercase/part reform msg 1
			][
				reform ["Invalid" mold type "value"]
			]
			"^/*** line: " line
			"^/*** at: " mold copy/part pos 40
		]
		either encap? [quit][halt]
	]

	add-line-markers: func [blk [block!]][	
		foreach pos lines [new-line pos yes]
		clear lines
	]
	
	pad-head: func [s [string!]][
		head insert/dup s #"0" 8 - length? s
	]
	
	encode-UTF8-char: func [s [string!] e [string!] /local c code new][
		c: debase/base pad-head copy/part s e 16
		while [c/1 = 0][c: next c]					;-- trim heading zeros
		code: to integer! c
		
		case [
			code <= 127  [
				new: to char! code					;-- c <= 7Fh
			]
			code <= 2047 [							;-- c <= 07FFh
				new: (shift/left (shift code 6) or #"^(C0)" 8)
						or (code and #"^(3F)") or #"^(80)"
			]
			code <= 65535 [							;-- c <= FFFFh
				new: (shift/left (shift code 12) or #"^(E0)" 16)
						or (shift/left (shift code 6) and #"^(3F)" or #"^(80)" 8)
						or (code and #"^(3F)") or #"^(80)"
			]
			code <= 1114111 [						;-- c <= 10FFFFh
				new: (shift/left (shift code 18) or #"^(F0)" 24)
						or (shift/left (shift code 12) and #"^(3F)" or #"^(80)" 16)
						or (shift/left (shift code 6)  and #"^(3F)" or #"^(80)" 8)
						or (code and #"^(3F)") or #"^(80)"
			]
			'else [
				throw-error/with "Codepoints above U+10FFFF are not supported"
			]
		]
		if integer? new [
			new: debase/base to-hex new 16
			remove-each byte new [byte = #"^(null)"]
		]	
		new
	]
	
	decode-UTF8-char: func [value][
		if char? value [return encode-char to integer! value]
		
		value: switch/default length? value [
			1 [value]
			2 [
				value: value and #{1F3F}
				value: add shift/left value/1 6 value/2
			]
			3 [
				value: value and #{0F3F3F}
				value: add add
					shift/left value/1 12
					shift/left value/2 6
					value/3
			]
			4 [
				value: value and #{073F3F3F}
				value: add add add
					shift/left value/1 18
					shift/left value/2 12
					shift/left value/3 6
					value/4
			]
		][
			throw-error/with "Unsupported or invalid UTF-8 encoding"
		]	
		
		encode-char to integer! value				;-- special encoding for Unicode char!
	]
	
	decode-UTF8-string: func [str [string!] /local new s e][
		new: make string! length? str
		parse str [
			some [
				s: UTF8-char e: (
					append new debase/base skip decode-UTF8-char as-binary copy/part s e 7 16
				)
			]
		]
		head change/part str new tail str
	]
	
	encode-char: func [value [integer!]][
		head insert to-hex value #"'"
	]
	
	decode-hexa: func [s [string!]][
		to integer! debase/base s 16
	]

	load-number: func [s [string!]][
		switch/default type [
			#[datatype! decimal!][s: load-decimal s]
			#[datatype! issue!  ][
				if s = "-0.0" [s: "0-"]					;-- reencoded for consistency
				s: to issue! join "." s
				if neg? [append s #"-"]
			]
		][
			unless integer? s: to integer! s [throw-error]
		]
		s
	]

	load-decimal: func [s [string!]][
		unless attempt [s: to decimal! s][throw-error]
		s
	]

	load-string: func [s [string!] e [string!] /local new filter][
		new: make string! offset? s e				;-- allocated size close to final size
		filter: get pick [UTF8-char UTF8-filtered-char] s/-1 = #"{"

		parse/all/case copy/part s e [
			any [
				escaped-char   (insert tail new value)
				| s: filter e: (insert/part tail new s e)
			]										;-- exit on matching " or }
		]
		new
	]
	
	load-binary: func [s [string!] e [string!] /local new byte][
		new: make binary! (offset? s e) / 2			;-- allocated size above final size

		parse/all/case s [
			some [
				copy byte 2 hexa-char (insert tail new debase/base byte 16)
				| ws | comment-rule
				| #"}" end skip
			]
		]
		new
	]

	load-file: func [s [string!]][
		to file! dehex s
	]
	
	process: func [src [string! binary!] /local blk][
		line: 1
		count?: yes
		
		blk: stack/push block!						;-- root block

		unless parse/all/case src program [throw-error]
		
		add-line-markers blk
		stack/reset
		blk
	]
]# Command line tools don’t want to clutter their output with unnecessary noise.
library = function (...)
    suppressMessages(base::library(...))

#' The command line arguments
args = commandArgs(trailingOnly = TRUE)

#' The name of the script
script_name = local({
    file = grep('^--file=', commandArgs(trailingOnly = FALSE), value = TRUE)
    sub('--file=', '', file)
})

#' Quit the program
#'
#' @param code numeric exit code (default: \code{0})
exit = function (code = 0)
    quit(save = 'no', status = if (is.null(code)) 0 else code)

#' Execute the \code{entry_point} function defined by the caller
#'
#' Execute an entry point function, but only if the calling code is executed as
#' a stand-alone script, not when it is imported as a module.
#'
#' @param entry_point code or function to run (default: \code{main})
#' @return This function is called for its side-effect. If the calling code was
#' imported as a module, then return nothing. Otherwise, this function
#' \emph{does not return}; instead, it quits the script.
#'
#' @details The argument may either be a function (the default is assumed to be
#' a function called \code{main} in the calling code’s scope) or a
#' brace-enclosed expression. It is executed in the calling code’s scope.
#'
#' @examples
#' \dontrun{
#' main = function () { … }
#' # Run function `main`
#' sys$run()
#'
#' # Run the specified function
#' sys$run(function () { … })
#'
#' # Run the specified code
#' sys$run({ … })
#' }
run = function (entry_point = main) {
    caller = parent.frame()
    caller_name = evalq(modules::module_name(), envir = caller)

    if (is.null(caller_name)) {
        if (class(substitute(entry_point)) == '{')
            exit(entry_point)

        exit(eval(substitute(main(), list(main = entry_point)), envir = caller))
    }
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' @examples
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}# Command line tools don’t want to clutter their output with unnecessary noise.
library = function (...)
    suppressMessages(base::library(...))

#' The command line arguments
args = commandArgs(trailingOnly = TRUE)

#' Quit the program
#'
#' @param code numeric exit code (default: \code{0})
exit = function (code = 0)
    quit(save = 'no', status = if (is.null(code)) 0 else code)

#' Execute the \code{entry_point} function defined by the caller
#'
#' Execute an entry point function, but only if the calling code is executed as
#' a stand-alone script, not when it is imported as a module.
#'
#' @param entry_point code or function to run (default: \code{main})
#' @return This function is called for its side-effect. If the calling code was
#' imported as a module, then return nothing. Otherwise, this function
#' \emph{does not return}; instead, it quits the script.
#'
#' @details The argument may either be a function (the default is assumed to be
#' a function called \code{main} in the calling code’s scope) or a
#' brace-enclosed expression. It is executed in the calling code’s scope.
#'
#' @examples
#' \dontrun{
#' main = function () { … }
#' # Run function `main`
#' sys$run()
#'
#' # Run the specified function
#' sys$run(function () { … })
#'
#' # Run the specified code
#' sys$run({ … })
#' }
run = function (entry_point = main) {
    caller = parent.frame()
    caller_name = evalq(modules::module_name(), envir = caller)

    if (is.null(caller_name)) {
        if (class(substitute(entry_point)) == '{')
            exit(entry_point)

        exit(eval(substitute(main(), list(main = entry_point)), envir = caller))
    }
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @note Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' Prepare the datapoll
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H))
      stop("H should be a square matrix")
   if(NROW(P) != NCOL(P))
      stop("P should be a square matrix")
   if(NROW(H) != NROW(HP)){
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)?
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)?
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]

    if (length(l.) == 1 && length(required) == 1)
        names(l.) = required

    provided = names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    sdiff = unlist(setdiff(required, provided))
    if (length(sdiff) > 0 && sdiff != '...')
        stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
library(dplyr)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) { #TODO: name columns in layout df properly (formals if no names)
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) {
        layout$result = setNames(rep(list(NA),nrow(layout)), 1:nrow(layout))
        result = Qget(fail.on.error=fail.on.error)
        layout$result[names(result)] = result
    }
    layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=function(job, res) res)
    else
        result = reduceResultsList(reg, fun=function(job, res) res)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)
.b = import('../base')

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), get=T, expand.grid=FALSE,
        memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA, seed=123, fail.on.error=TRUE) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) { #TODO: move this to array (with: -1=last dim)
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid) {
        layout = expand.grid(lapply(l., .b$descriptive_index))
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    } else {
        layout = as.data.frame(lapply(l., .b$descriptive_index))
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    }

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(regs=reg, n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    
    if (get) # merge layout+results list
        Qget(regs=reg, fail.on.error=fail.on.error)[[1]]
    else
        layout
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
#' @param regs        list of registries to include; default: all local
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T, regs=Qregs()) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param regs            list of registries to include; default: all local
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=TRUE, regs=Qregs(), fail.on.error=TRUE) {
    reg = get('Qreg', envir=parent.env(environment()))

    waitForJobs(reg, ids=getJobIds(reg))
    print(showStatus(reg, errors=100L))
    retrieve = function(job, res) setNames(res, job)
    if (fail.on.error)
        result = reduceResultsList(reg, ids=getJobIds(reg), fun=retrieve)
    else
        result = reduceResultsList(reg, fun=retrieve)

    if (clean)
        Qclean()

    result
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)

#' Registry object the module is working on
.Qreg = NULL

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param grid.sep        separator to use when assembling names from expand.grid
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @param set.names       try to name result or keep numbers? (default: \code{fail.on.error})
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), name=NULL, run=T, get=T,
             memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA,
             expand.grid=F, grid.sep=":", seed=123, fail.on.error=T,
             set.names=fail.on.error) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) {
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    # name every vector so we can identify them afterwards
    ln = lapply(l., names)
    lnFull = lapply(1:length(ln), function(i)
        if (is.character(l.[[i]]) && length(l.[[i]][1])==1 && is.null(ln[[i]]))
            l.[[i]]
        else if (is.null(ln[[i]]))
            1:length(l.[[i]])
        else
            ln[[i]]
    )
 
    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg=reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid)
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    else
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))

    if (expand.grid || is.null(unlist(ln)))
        resultNames = apply(expand.grid(lnFull), 1, function(x) paste(x,collapse=grid.sep))
    else
        resultNames = as.matrix(apply(do.call(cbind, ln), 1, unique))
    save(resultNames, name, set.names, file=file.path(tmpdir, "names.RData"))

    assign('Qreg', reg, envir=parent.env(environment()))

    Qrun(regs=reg, n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    if (get)
        Qget(regs=reg, fail.on.error=fail.on.error)[[1]]
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
#' @param regs        list of registries to include; default: all local
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T, regs=Qregs()) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    reg = get('Qreg', envir=parent.env(environment()))

    ids = getJobIds(reg)
    if (!is.null(n.chunks))
        ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
    if (!is.null(chunk.size))
        ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

    if (is.null(memory))
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
    else
        submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                   resources=list(memory=memory))
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param regs            list of registries to include; default: all local
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=T, regs=Qregs(), fail.on.error=T) {
    if (class(regs) == 'Registry')
        regs = list(regs)

    getResult = function(reg) {
        waitForJobs(reg, ids=getJobIds(reg))
        print(showStatus(reg, errors=100L))
        if (fail.on.error)
            result = reduceResultsList(reg, ids=getJobIds(reg),
                                       fun=function(job, res) res)
        else
            result = reduceResultsList(reg, fun=function(job, res) res)
        load(file.path(reg$file.dir, 'names.RData')) # resultNames
        if (clean)
            Qclean(reg)
        if (set.names)
            setNames(result, resultNames[as.integer(names(result))])
        else
            result
    }

    setNames(lapply(regs, getResult), names(regs))
}

#' Delete the registry the module is working on
Qclean = function() {
    reg = get('Qreg', envir=parent.env(environment()))
    unlink(reg$file.dir, recursive=T)
}
# BatchJobsWrapper.r
#
# Rationale
#  This script uses BatchJobs to run functions either locally, on multiple cores, or LSF,
#  depending on your BatchJobs configuration. It has a simpler interface, does more error
#  checking than the library itself, and is able to queue different function calls. The
#  function supplied *MUST* be self-sufficient, i.e. load libraries and scripts.
#  BatchJobs on the EBI cluster is already set up when using the gentoo prefix.
#
# Usage
#  * Q()     : create a new registry with that vectorises a function call and optionally runs it
#  * Qrun()  : run all registries in the current working directory
#  * Qget()  : extract the results from the registry and returns them
#  * Qclean(): delete all registries in the current working directory
#  * Qregs() : list all registries in the current working directory
#
# Examples
#  > s = function(x) x
#  > Q(s, x=c(1:3), get=T)
#  returns list(1,2,3)
#
#  > t = function(x) sum(x)
#  > a = matrix(3:6, nrow=2)
#  > Q(t, a)
#  > Qget()
#  splits a by columns, sums each column, and returns list(7, 11)
#
# TODO list
#  * handle failed jobs? (e.g.: save layout to registry dir to rerun failed jobs) [rerun option?]

library(stringr)
library(BatchJobs)

.QLocalRegistries = list()

#' Submit function calls as cluster jobs
#'
#' This function takes the function \code{` fun`} and calls it with each element of the iterable
#' \code{...}, either in order or as grid. Depending on how \emph{BatchJobs} is set up, these
#' function calls are processed either sequentially, on multicore, or as LSF/SGE/etc. jobs.
#'
#' For normal usage, this is the only function necessary to call explicitly (set \code{get=T} to
#' get the function results returned).
#'
#' @param ` fun`          the function to call
#' @param ...             arguments to vectorise over
#' @param more.args       arguments not to vectorise over
#' @param export          objects to export to computing nodes
#' @param name            the name of the function call if more than one are submitted
#' @param run             submit the function on the queuing system (default:T)
#' @param get             returns the result of the run (default:T)
#' @param memory          how many Mb of memory should be reserved to run the job
#' @param split.array.by  how to split matrices/arrays in \code{...} (default: last dimension)
#' @param expand.grid     do every combination of arguments to vectorise over
#' @param grid.sep        separator to use when assembling names from expand.grid
#' @param seed            random seed for the function to run
#' @param n.chunks        how much jobs to split functions calls into (default: number of calls)
#' @param chunk.size      how many function calls in one job (default: 1)
#' @param fail.on.error   if jobs fail, return all successful or throw overall error?
#' @param set.names       try to name result or keep numbers? (default: \code{fail.on.error})
#' @return                list of job results if get=T
Q = function(` fun`, ..., more.args=list(), export=list(), name=NULL, run=T, get=T,
             memory=NULL, n.chunks=NULL, chunk.size=NULL, split.array.by=NA,
             expand.grid=F, grid.sep=":", seed=123, fail.on.error=T,
             set.names=fail.on.error) {
    # summarise arguments
    l. = list(...)
    fun = match.fun(` fun`)
    funargs = formals(fun)
    required = names(funargs)[unlist(lapply(funargs, function(f) class(f)=='name'))]
    provided= names(c(l., more.args))

    # perform checks that BatchJobs doesn't do
    if ('reg' %in% provided || 'fun' %in% provided)
        stop("'reg' and 'fun' are reserved and thus not allowed as argument to ` fun`")
    if (any(grepl("^ ", provided)))
        stop("Arguments starting with space are not allowed")
    if (expand.grid && length(l.) == 1)
        stop("Can not expand.grid on one vector")

    if (length(provided) > 1) {
        if (sum(nchar(provided) == 0) > 1) #TODO: check if potential issues
            stop("At most one arugment can be unnamed in the function call")

        sdiff = unlist(setdiff(required, provided))
        if (length(sdiff) > 0 && sdiff != '...')
            stop(paste("Argument required but not provided:", paste(sdiff, collapse=" ")))
    }

    sdiff = unlist(setdiff(provided, names(funargs)))
    if (length(sdiff) > 0 && ! '...' %in% names(funargs))
        stop(paste("Argument provided but not accepted by function:", paste(sdiff, collapse=" ")))
    dups = duplicated(provided)
    if (any(dups))
        stop(paste("Argument duplicated:", paste(provided[[dups]], collapse=" ")))

    # convert matrices to lists so they can be vectorised over
    split_mat = function(X) {
        if (is.array(X) && length(dim(X)) > 1) {
            if (is.na(split.array.by))
                setNames(plyr::alply(X, length(dim(X))), dimnames(X)[[length(dim(X))]])
            else
                setNames(plyr::alply(X, split.array.by), dimnames(X)[[split.array.by]])
        } else
            X
    }
    l. = lapply(l., split_mat)

    # name every vector so we can identify them afterwards
    ln = lapply(l., names)
    lnFull = lapply(1:length(ln), function(i)
        if (is.character(l.[[i]]) && length(l.[[i]][1])==1 && is.null(ln[[i]]))
            l.[[i]]
        else if (is.null(ln[[i]]))
            1:length(l.[[i]])
        else
            ln[[i]]
    )
 
    tmpdir = tempdir()
    reg = makeRegistry(id=basename(tmpdir), file.dir=tmpdir, seed=seed)

    # export objects to nodes if desired
    if (length(export) > 0)
        do.call(batchExport, c(list(reg), export))

    # fill the registry with function calls, save names as well
    if (expand.grid)
        do.call(batchExpandGrid, c(list(reg=reg, fun=fun, more.args=more.args), l.))
    else
        do.call(batchMap, c(list(reg=reg, fun=fun, more.args=more.args), l.))

    if (expand.grid || is.null(unlist(ln)))
        resultNames = apply(expand.grid(lnFull), 1, function(x) paste(x,collapse=grid.sep))
    else
        resultNames = as.matrix(apply(do.call(cbind, ln), 1, unique))
    save(resultNames, name, set.names, file=file.path(tmpdir, "names.RData"))

    assign('.QLocalRegistries', c(.QLocalRegistries, setNames(list(reg), name)), 
           envir=parent.env(environment()))

    if (run)
        Qrun(regs=reg, n.chunks=n.chunks, chunk.size=chunk.size, memory=memory)
    if (run && get)
        Qget(regs=reg, fail.on.error=fail.on.error)[[1]]
}

#' Run all registries if \code{run=F} in \code{Q()}
#'
#' @param n.chunks    number of chunks (cores, LSF jobs) to split each registry into
#' @param chunk.size  number of calls to put into one core/LSF job (do not use with n.chunks)
#' @param memory      how many Mb of memory should be reserved to run the job
#' @param shuffle     if chunking, shuffle the order of calls
#' @param regs        list of registries to include; default: all local
Qrun = function(n.chunks=NULL, chunk.size=NULL, memory=NULL, shuffle=T, regs=Qregs()) {
    if (!is.null(n.chunks) && !is.null(chunk.size))
        stop("Can not take both n.chunks and chunk.size")

    if (class(regs) == 'Registry')
        regs = list(regs)

    for (reg in regs) {
        ids = getJobIds(reg)
        if (!is.null(n.chunks))
            ids = chunk(ids, n.chunks=n.chunks, shuffle=shuffle)
        if (!is.null(chunk.size))
            ids = chunk(ids, chunk.size=chunk.size, shuffle=shuffle)

        if (is.null(memory))
            submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf)
        else
            submitJobs(reg, ids, chunks.as.arrayjobs=F, job.delay=T, max.retries=Inf,
                       resources=list(memory=memory))
    }
}

#' Get all results if \code{get=F} in \code{Q()}
#'
#' @param clean           delete the registry when done
#' @param regs            list of registries to include; default: all local
#' @param fail.on.errors  whether to get only successful results or throw overall error
#' @return                a list of results of the function called with different arguments
Qget = function(clean=T, regs=Qregs(), fail.on.error=T) {
    if (class(regs) == 'Registry')
        regs = list(regs)

    getResult = function(reg) {
        waitForJobs(reg, ids=getJobIds(reg))
        print(showStatus(reg, errors=100L))
        if (fail.on.error)
            result = reduceResultsList(reg, ids=getJobIds(reg),
                                       fun=function(job, res) res)
        else
            result = reduceResultsList(reg, fun=function(job, res) res)
        load(file.path(reg$file.dir, 'names.RData')) # resultNames
        if (clean)
            Qclean(reg)
        if (set.names)
            setNames(result, resultNames[as.integer(names(result))])
        else
            result
    }

    setNames(lapply(regs, getResult), names(regs))
}

#' Delete all registries if \code{clean=F} in \code{Qget()}
#'
#' @param regs  list of registries to include; default: all local
Qclean = function(regs=Qregs()) {
    if (class(regs) == 'Registry')
        regs = list(regs)

    for (reg in regs)
        unlink(reg$file.dir, recursive=T)
}

#' Lists all registries in the current working directory
#'
#' @param name       regular expression specifying the registry name
#' @param directory  regular expression specifying the directories to look for registries
#' @param local      only return registries created in this R session
#' @return           a list of registry objects
Qregs = function(name=".*", directory="Rtmp[0-9a-zA-Z]+", local=T) {
    if (local)
        return(.QLocalRegistries)
    
    regdirs = list.files(pattern=directory, include.dirs=T)
    if (length(regdirs) == 0) return(list())
    regfun = function(path) list.files(path=path, pattern="^registry.RData$", full.names=T)
    details = file.info(sapply(regdirs, regfun))
    regfiles = rownames(details[with(details, order(as.POSIXct(mtime))),])
    
    getRegistry = function(rdir) {
        load(file.path(rdir, 'registry.RData'))
        load(file.path(rdir, 'names.RData'))
        list(name, reg)
    }
    regs = lapply(regdirs, getRegistry)
    regs = setNames(lapply(regs, function(x) x[[2]]), sapply(regs, function(x) x[[1]]))
    regs[grepl(name, names(regs))]
}   

source("colors.r")

########################################

plotHistogram <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    pdfFilePath <- "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath <- pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=color,
      border=borderColor,
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      lty=1,
      cex=1)
    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotHistogramNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot", breaks = 10) {
    pdfFilePath <- "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath <- pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    h <- hist(dataArray, plot=FALSE, breaks=breaks)
    h$counts <- h$counts/sum(h$counts)
    plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
    type = 'n', bty = 'n', ann=FALSE, axes=FALSE)

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    hist(dataArray,
      add=TRUE,
      axes=FALSE,
      col=color,
      border=borderColor,
      ylab='',
      xlab='',
      main='',
      breaks=breaks,
      freq=FALSE,
      lty=1,
      cex=1)

    x <- seq(min(-10.0, min(dataArray) * 0.5) , max(max(dataArray) * 1.5, 100), length=10000)
    y <- dnorm(x, mean=mean(dataArray), sd=sd(dataArray))

    par(new=TRUE)

    plot(x,y,
         type="l",
         lwd=3,
         axes=FALSE,
         col=thillux_green,
         xlim = c(min(h$mids) * 0.9, max(h$mids) * 1.1),
         ylab='',
         xlab='',
         main=''
    )

    polygon(x, y,
            col=thillux_green,
            border="#4ACAA8",
            ylab='',
            xlab='',
            main=''
    )

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotQQNormal <- function(dataArray, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(qqnorm(dataArray, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    qqline(sort(dataArray), ylab='',
      xlab='', col=thillux_green, lwd=2)

    par(new=TRUE)

    qq <- qqnorm(sort(dataArray), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotQQ <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(qqplot(dataArray1, dataArray2, plot.it=FALSE, ylab='',
      xlab=''), ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='');

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    qq <- qqplot(sort(dataArray1), sort(dataArray2), plot.it=FALSE,ylab='',
      xlab='')

    plot(qq$x, qq$y,
      type="b",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotPoints <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    plot(dataArray1, dataArray2,
      type="p",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

########################################

plotSmoothLine <- function(dataArray1, dataArray2, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
        pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
        margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
        margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
        margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    plot(dataArray1, dataArray2, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
      xlab='',
      main='')

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    plot(smooth.spline(dataArray1, dataArray2),
      type="l",
      axes=FALSE,
      col=borderColor,
      bg=color,
      ylab='',
      xlab='',
      main=NULL,
      lty=1,
      pch=21,
      cex=1,
      lwd=1)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}

plotWithConfidence <- function(xData, yData, e, mainTitle=NULL, xTitle=NULL, yTitle=NULL, pdfFile=NULL, pdfTitle="thillux plot") {
    pdfFilePath = "hist.pdf"
    if(!is.null(pdfFile)) {
      pdfFilePath = pdfFile
    }
    pdf(pdfFilePath, pointsize=10, width=7, height=5, title = pdfTitle)

    margins <- par()$mar
    if(is.null(mainTitle)) {
      margins[3] <- 1.0
    }
    if(is.null(xTitle)) {
      margins[1] <- 2.5
    }
    if(is.null(yTitle)) {
      margins[2] <- 2.5
    }
    margins[4] <- 1.0
    par(mar=margins)

    xLim <- range(x) + c(-0.1,0.1)
    yLim <- range(c(y+e,y-e)) + c(-0.1,0.1)

    plot(xData, yData, ann=FALSE, type="n", bty="n", axes=FALSE, ylab='',
    xlab='',
    main='',
    xlim=xLim,
    ylim=yLim)

    u <- par("usr")
    rect(u[1], u[3], u[2], u[4], col = bgColor, border = FALSE)

    par(col.lab=thillux_grey)

    grid(col=thillux_grey, lty=3, lwd=0.5)

    par(new=TRUE)

    plot(xData, yData,
    type="p",
    axes=FALSE,
    col=borderColor,
    bg=color,
    ylab='',
    xlab='',
    main=NULL,
    lty=1,
    pch=20,
    cex=1,
    lwd=1,,
    xlim=xLim,
    ylim=yLim)

    widthToInch = 96.0
    arrowLength = 0.1

    arrows(xData,yData-e,xData,yData+e,lend=1,angle=90,code=3, col="#E7746F",xlim=xLim,
    ylim=yLim, length=arrowLength)
    arrows(xData,yData-e,xData,yData+e,lend=1,angle=90,code=0, col="#E7746F5F",xlim=xLim,
    ylim=yLim, lwd=2*arrowLength*widthToInch)

    frame <- data.frame(xData,yData)
    frame <- frame[order(xData),]
    lines(frame$xData, frame$yData, col=color,lty=2)

    box(col = thillux_grey, bty="l")
    title(main=mainTitle, col=thillux_grey, xlab=xTitle, ylab=yTitle)
    axis(1, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)
    axis(2, col="#00000000", col.axis = thillux_grey, col.ticks = thillux_grey)

    noOut <- dev.off()
}
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')


# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot")

# geogrphic analysis
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.1), maptype='toner-lite')

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

# cleaning the data
select(bigc_geo, year) %>% distinct()
bigc_geo %<>% filter(year > 100, year < 2015)

qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.3))

# look at SF
sf_geo <- filter(bigc_geo, city == "San Francisco")
qmplot(long, lat, data=sf_geo, color=year, alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5))
# what about the corelation between the age and the price?
qmplot(long, lat, data=sf_geo, color=year, size=price,
       alpha=I(0.1), maptype='toner-lite') +
  scale_color_gradientn(colours=heat.colors(10, alpha=0.5)) +
  scale_size_area()

qmplot(long, lat, data=sf_geo, alpha=I(0.5), stat="binhex", geom="hex",
       maptype='toner-lite')+
  scale_fill_gradientn(colours=heat.colors(16))
#' Prepare the data
#' Simple wrapper to make sure that the matrices are sorted accordingly
#' @param H Host distance matrix 
#' @param P Parasite distance matrix 
#' @param HP Host-parasite association matrix, hosts in rows
#' @return A list with objects H, P, HP
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
prepare_paco_data <- function(H, P, HP)
{
   if(NROW(H) != NCOL(H)) stop("H should be a square matrix")
   if(NROW(P) != NCOL(P)) stop("P should be a square matrix")
   if(NROW(H) != NROW(HP))
   {
      warning("The HP matrix should have hosts in rows. It has been translated.")
      HP <- t(HP)
   }
   H <- H[rownames(HP),rownames(HP)]
   P <- P[colnames(HP),colnames(HP)]
   HP[HP>0] <- 1
   return(list(H=H, P=P, HP=HP))
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @examples
#' @notes Internal function coordpcoa is a modified version of ape::pcoa, utilising vegan::eigenvals
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    D.eig$values <- vegan::eigenvals(D.eig)
    zero.eig <- which(D.eig$values < epsilon)
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            toto.cor$values <- vegan::eigenvals(toto.cor)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}## Selecting plot element for customizaiton
observe({
  v <- input$customizeItem
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']] <<- v
    }
  })
})
observe({
  updateInput[['customizeItem']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
  } else ''
  updateTabsetPanel(session, 'customizeItem', selected=null2String(s))
})

## modify plotTitle and other text fields
lapply(c('plotTitle', 'plotXlab', 'plotYlab'),
       function(inputId){
         assign(paste0('observer_', inputId, '_push'),
                observe({
                  v <- input[[inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)){
                      sheetList[[currentSheet]][['dynamicProperties']][[inputId]] <<- v
                    }
                  })

                }),
                sessionEnv)
         assign(paste0('observer_', inputId, '_pull'),
                observe({
                  updateInput[[inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- if(!isEmpty(currentSheet)){
                    isolate(sheetList[[currentSheet]][['dynamicProperties']][[inputId]])
                  } else ''
                  updateTextInput(session, inputId, value=null2String(s))
                }),
                sessionEnv)
       })



###########################
## Text Formatting

lapply(list(list(inputId='textFamily', inputType='select'),
            list(inputId='textFace', inputType='select'),
            list(inputId='textColor', inputType='color'),
            list(inputId='textSize', inputType='numeric'),
            list(inputId='textHjust', inputType='numeric'),
            list(inputId='textVjust', inputType='numeric'),
            list(inputId='textAngle', inputType='numeric'),
            list(inputId='textLineheight', inputType='numeric')),
       function(x){
         assign(paste0('observer_', x$inputId, '_push'),
                observe({
                  v <- input[[x$inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)) {
                      customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
                      if(!isEmpty(customizeItem)){
                        if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
                        }
                        if(x$inputId=='textColor' && !isEmpty(v)) v <- paste0("#", v)
                        if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]]))
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]] <<- v
                      }
                    }
                  })
                }),
                sessionEnv)
         if(x$inputId=='textColor') return() ## no updateJsColorInput is available yet
         assign(paste0('observer_', x$inputId, '_pull'),
                observe({
                  updateInput[[x$inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- ''
                  if(!isEmpty(currentSheet)){
                    customizeItem <- (sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
                    if(!isEmpty(customizeItem) && !is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]])
                    }
                  }

                  switch(x$inputType,
                         'numeric'=updateNumericInput(session, x$inputId, value=null2String(s)),
                         'select'=updateSelectInput(session, x$inputId, selected=null2String(s)))

                }),
                sessionEnv)
       })


## End of Text Formatting
###########################

install.packages("methods", dependencies = TRUE)
install.packages("ggplot2", dependencies = TRUE)
install.packages("knitr", dependencies = TRUE)
install.packages("base64enc", dependencies = TRUE)
library(devtools)
options(unzip = "internal")
install_github("ramnathv/rCharts@dev")
# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            names(dimnames(l.[[i]])) = dimnames[1:length(dim(l.[[i]]))]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=names(l.)[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>%
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)
library(lubridate)

# read house sales data
sales <- read.csv('./data/house-sales.csv', stringsAsFactors=FALSE)

# read geolocation data
ad <- read.csv('./data/addresses.csv', stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
# old-style R
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))
# new-style R
sales$date %<>% ymd()

# prices into numeric values
# old-style R
sales$price <- as.numeric(sales$price)
# new-style R
sales$price %<>% as.numeric()

# zip codes into numeric values
ad$zip %<>% as.numeric()

# check if there are missing vaules in sales or date
# old-style R
any(is.na(sales$price))
any(is.na(sales$date))
any(is.na(ad$zip))
# new-style R
sales$price %>% is.na() %>% any()
sales$date %>% is.na() %>% any()

# remove records with missing important fields
# old-style R
sales <- sales[!is.na(sales$price), ]
sales <- sales[!is.na(sales$date), ]
ad <- ad[!is.na(ad$zip), ]
# new-style R
sales %<>% filter(!is.na(price), !is.na(date))
ad %<>% filter(!is.na(zip))

# combine geo information with sales
geo <- inner_join(ad, sales)

# choose only records with good quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- filter(geo, quality %in% precise_qual)

# choose cities with at least 10 sales a week
# how many weeks does our dataset cover?
date_range <- range(precise$date)
weeks <- as.integer(date_range[2] - date_range[1]) / 7

# calculate sales per city
cities <- group_by(precise, city) %>%
  summarise(freq = n())

big_cities <- filter(cities, freq > weeks * 10)

# see what we actually pick up
ggplot(cities, aes(freq)) +
  geom_histogram(binwidth=250, alpha=I(0.7)) +
  geom_vline(xintercept=weeks*10, color=I("red"))

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- filter(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')


# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_monthly <- bigsum %>%
  group_by(city, year, month) %>%
  summarise(m_price = mean(price),
            date = date[1])

qplot(factor(date), m_price, data=big_monthly, geom="boxplot")

# geogrphic analysis
qmplot(long, lat, data=bigc_geo, color=county, alpha=I(0.1), maptype='toner-lite')

# age of houses geolocated
qmplot(long, lat, data=bigc_geo, color=year, alpha=I(0.1), maptype='toner-lite')

library(plyr)
library(ggplot2)
library(ggmap)
library(dplyr)
library(mgcv)

# read house sales data
path = system.file(package='RIntroBayarea')
sales_file <- paste0(path, "/extdata/house-sales.csv")
sales <- read.csv(sales_file, stringsAsFactors=FALSE)

# read in geolocation data
ad_file <- paste0(path, '/extdata/addresses.csv')
ad <- read.csv(ad_file, stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))

# and prices into numeric values
sales$price <- as.numeric(sales$price)

# check if there are missing vaules in sales or date
any(is.na(sales$price))
any(is.na(sales$date))

# remove missing rows with missing dates
sales <- sales[!is.na(sales$date), ]

# combine sales data with geospatial information
names(sales)
names(ad)

# by common columns
intersect_cols <- intersect(names(sales), names(ad))
geo <- join(sales, ad, by = intersect_cols)

# choose only records with goog quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- subset(geo, quality %in% precise_qual)

# choose cities with at least 20 sales a week
# how many weeks does our dataset cover?
n_weeks <- as.integer((max(precise$date) - min(precise$date)) / 7)

# calculate sales per city
cities <- as.data.frame(table(precise$city))
names(cities) <- c('city', 'freq')

big_cities <- subset(cities, freq > n_weeks * 20)

# see what we actually pick up
ggplot(geo, aes(city)) +
  geom_histogram() +
  geom_hline(yintercept=n_weeks*20)

# add interesting cities
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- subset(geo, city %in% selected)

# see the locations of the sales on the map
qmplot(long, lat, data=bigc_geo, color=I('red'), alpha=I(0.1))
qmplot(long, lat, data=bigc_geo, color=I('red'),
       maptype='toner-lite', geom='density2d')

# calculate average price and number of sales per city per day
bigsum <- bigc_geo %>%
          group_by(city, date) %>%
          summarise(n=n(),price=mean(price))

# plot number of sales in time
qplot(date, n, data=bigsum, geom='line', group=city)
qplot(date, n, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# and average price in time
qplot(date, price, data=bigsum, geom='line', group=city)
qplot(date, price, data=bigsum, geom='line', group=city) + facet_wrap(~city)

# extract day and year from date (for easier manupulations)
get_month <- function(x) as.POSIXlt(x)$mon + 1
get_year <- function(x) as.POSIXlt(x)$year + 1900

# look at the distribution of monthly averages
bigsum$month <- get_month(bigsum$date)
bigsum$year <- get_year(bigsum$date)

big_montly <- bigsum %>%
group_by(city, year, month) %>%
summarise(m_price = mean(price))

qplot(factor(year + month/12), m_price, data=big_montly, geom="boxplot")

# the distribution of prices is wide, it's right skewed 
qplot(price, data = geo, geom="histogram", binwidth = 1e4, xlim = c(0, 2e6))
fp <- geom_freqpoly(aes(y = ..density..), binwidth = .05)

# distribution within each year
ggplot(geo, aes(log10(price))) + fp + aes(colour = factor(year))
# distributions by month
ggplot(geo, aes(log10(price))) + fp + aes(colour = factor(month))

# split into months within each year
ggplot(geo, aes(log10(price))) + fp + facet_grid(year ~ month)

# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Function to melt data.frame from one or multiple arrays
#'
#' @param ...       Array[s] or data.frame[s] to be melted
#' @param dimnames  List of names along the dimensions (instead of `VarX`)
#' @param na_rm     Remove rows with NAs
melt = function(..., dimnames=NULL, na_rm=TRUE) {
    l. = list(...)
    l.names = as.character(substitute(list(...)))[-1L]

    for (i in seq_along(l.)) {
        if (!is.null(dimnames))
            dimnames(l.[[i]]) = dimnames[[i]]
        l.[[i]] = reshape2::melt(l.[[i]], value.name=l.names[i], na.rm=na_rm)
    }

    Reduce(function(a,b) merge(a,b,all=!na_rm), l.)
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>%
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
library(pcapack)

set.seed(1234)

m <- 10
n <- 50
m <- 50
n <- 10

x <- matrix(rnorm(m*n), m, n)


test <- function()
{
  mdl1 <- prcomp(x)
  mdl2 <- pca(x, method="svd")
#  mdl3 <- pca(x, method="svd", retx=FALSE)
  
#  all.equal(mdl1, mdl2)
  print(all.equal(mdl1$sdev, mdl2$sdev))
  print(all.equal(mdl1$rotation, mdl2$rotation))
  
  invisible()
}



test()

require(illuminaio) ## for readIDAT
require(IlluminaHumanMethylation450kmanifest)
require(MASS) ## for huber
require(limma) ## lm.fit


meffil.extract.control.matrix <- function(basenames, probes=probe.info()) {
    basenames <- sub("_Grn\\.idat$", "", basenames)
    basenames <- sub("_Red\\.idat$", "", basenames)
    basenames <- unique(basenames)
    
    msg("Samples \n", paste(basenames, collapse="\n "))
    
    sapply(basenames, function(basename) {
        rg <- read.rg(basename)
        collect.controls(rg, probes)
    })
}


meffil.compute.normalization.object <- function(basenames, control.matrix,
                                                number.pcs=2, number.quantiles=500,
                                                probes=probe.info()) {
    stopifnot(length(basenames) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    stopifnot(number.quantiles >= 100)

    colnames(control.matrix) <- basenames

    msg("calculating reference dye intensity") ## must happen before the control matrix gets scaled
    dye.reference <- which.min(abs(control.matrix["dye.bias",]-1))
    dye.intensity <- mean(control.matrix[c("normA","normT","normC","normG"), dye.reference])
    
    msg("cleaning up the control matrix")
    control.matrix <- impute.matrix(control.matrix)
    control.matrix <- scale(t(control.matrix))
    control.matrix[control.matrix > 3] <- 3
    control.matrix[control.matrix < -3] <- -3
    control.matrix <- t(scale(control.matrix))

    quantile.sets <- expand.grid(target=c("M","U"), type=c("iR","iG","ii"),
                                        stringsAsFactors=F)
    
    msg("compute probe quantiles")
    quantiles <- sapply(basenames, function(basename) {
        rg <- read.rg(basename)
        rg.correct <- background.correct(rg, probes)        
        rg.correct <- dye.bias.correct(rg.correct, dye.intensity, probes)
        mu <- rg.to.mu(rg.correct, probes)

        sapply(1:nrow(quantile.sets), function(i) {
            target <- quantile.sets$target[i]
            type <- quantile.sets$type[i]
            msg("computing quantiles of", target, type, "probes")
            probe.names <- probes$name[which(probes$target == target
                                             & probes$type3 == type
                                             & probes$chr.type == "autosomal")]
            probs <- seq(0,1,length.out=number.quantiles)
            quantile(mu[[target]][probe.names], probs=probs, na.rm=T)
        })
    }, simplify=F)

    msg("merging corresponding sample quantiles into matrices")
    quantile.sets$quantiles <- lapply(1:nrow(quantile.sets), function(i) 
                                   sapply(quantiles, function(sample) sample[,i]))
    
    msg("normalizing quantiles")
    quantile.sets$norm <- lapply(quantile.sets$quantiles, function(original) { 
        normalize.quantiles(original, control.matrix, number.pcs)
    })
    
    list(origin="meffil.compute.normalization.object",
         basenames=basenames,
         control.matrix=control.matrix,
         quantile.sets=quantile.sets,
         dye=list(reference=names(dye.reference), intensity=dye.intensity))
}

is.normalization.object <- function(object) {
    (all(c("control.matrix", "quantile.sets","dye","origin","basenames") %in% names(object))
     && all(colnames(object$control.matrix) == object$basenames)
     && object$origin == "meffil.compute.normalization.object")
}

meffil.normalize <- function(object,probes=probe.info()) {
    stopifnot(is.normalization.object(object))


    probe.names <- unique(na.omit(probes$name))

    U <- M <- matrix(NA_integer_,
                     ncol=length(object$basenames),
                     nrow=length(probe.names),
                     dimnames=list(probe.names,object$basenames))
    
    x.ignore <- sapply(object$basenames, function(basename) {
        sample.idx <- which(object$basenames == basename)
        rg <- read.rg(basename)
        rg.correct <- background.correct(rg, probes)
        rg.correct <- dye.bias.correct(rg.correct, object$dye$intensity, probes)
        mu <- rg.to.mu(rg.correct, probes)
        
        mu$M <- mu$M[probe.names]
        mu$U <- mu$U[probe.names]

        for (i in 1:nrow(object$quantile.sets)) {
            target <- object$quantile.sets$target[i]
            type <- object$quantile.sets$type[i]
            msg("normalizing", target, type, "probes for", basename)

            probe.idx <- which(names(mu[[target]])
                                     %in% probes$name[which(probes$target == target
                                                            & probes$type3 == type)])

            is.autosomal <- (names(mu[[target]])[probe.idx]
                             %in% probes$name[which(probes$chr.type=="autosomal")])
            
            mu[[target]][probe.idx] <- normalize.sample(mu[[target]][probe.idx],
                                                        object$quantile.sets$quantiles[[i]][,sample.idx],
                                                        object$quantile.sets$norm[[i]][,sample.idx],
                                                        is.autosomal)
        }
        U[names(mu$U),basename] <<- mu$U
        M[names(mu$M),basename] <<- mu$M
        NULL
    })

    list(M=M,U=U)

}


msg <- function(..., verbose=T) {
    x <- paste(list(...))
    name <- sys.call(sys.parent(1))[[1]]
    cat(paste("[", name, "]", sep=""), date(), x, "\n")
}

read.rg <- function(basename) {
    rg <- list(G=read.idat(paste(basename, "_Grn.idat", sep = "")),
               R=read.idat(paste(basename, "_Red.idat", sep="")))
}

probe.info <- function() {
    probe.locations <- function(array="IlluminaHumanMethylation450k",annotation="ilmn12.hg19") {
        annotation <- paste(array, "anno.", annotation, sep="")

        msg("loading probe genomic location annotation", annotation)
            
        require(annotation,character.only=T)
        data(list=annotation)
        as.data.frame(get(annotation)@data$Locations)
    }
    probe.characteristics <- function(type) {
        msg("extracting", type)
        getProbeInfo(IlluminaHumanMethylation450kmanifest, type=type)
    }
    
    type1.R <- probe.characteristics("I-Red")
    type1.G <- probe.characteristics("I-Green")
    type2 <- probe.characteristics("II")
    controls <- probe.characteristics("Control")

    msg("reorganizing type information")
    ret <- rbind(data.frame(type="i",target="M", dye="R", address=type1.R$AddressB, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="M", dye="G", address=type1.G$AddressB, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="M", dye="G", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="U", dye="R", address=type1.R$AddressA, name=type1.R$Name,ext=NA),
                 data.frame(type="i",target="U", dye="G", address=type1.G$AddressA, name=type1.G$Name,ext=NA),
                 data.frame(type="ii",target="U", dye="R", address=type2$AddressA, name=type2$Name,ext=NA),
                 
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="G", address=type1.R$AddressB, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressA, name=NA,ext=NA),
                 data.frame(type="i",target="OOB", dye="R", address=type1.G$AddressB, name=NA,ext=NA),
                 
                 data.frame(type="control",target=controls$Type,dye="R",address=controls$Address, name=NA,ext=controls$ExtendedType),
                 data.frame(type="control",target=controls$Type,dye="G",address=controls$Address, name=NA,ext=controls$ExtendedType))

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])

    locations <- probe.locations()
    ret <- cbind(ret, locations[match(ret$name, rownames(locations)),])
    
    ret$chr.type <- ret$chr
    ret$chr.type[with(ret,which(chr.type !="chrX" & chr.type !="chrY"))]<-"autosomal"
    
    ret$type3 <- ret$type
    ret$type3[which(ret$type == "i" & ret$dye == "R")] <- "iR"
    ret$type3[which(ret$type == "i" & ret$dye == "G")] <- "iG"

    for (col in setdiff(colnames(ret), "pos")) ret[,col] <- as.character(ret[,col])
    ret
}


read.idat <- function(filename) {
    msg("Reading", filename)
    
    if (!file.exists(filename))
        stop("Filename does not exist:", filename)
    readIDAT(filename)$Quants[,"Mean"]
}

is.rg <- function(rg) {
    (all(c("R","G") %in% names(rg))
     && is.vector(rg$R) && is.vector(rg$G)
     #&& length(rg$R) == length(rg$G)
     && length(names(rg$G)) == length(rg$G)
     && length(names(rg$R)) == length(rg$R))
     ##&& all(names(rg$R) == names(rg$G)))
}

rg.to.mu <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg("converting red/green to methylated/unmethylated signal")
    probes.M.R <- probes[which(probes$target == "M" & probes$dye == "R"),]
    probes.M.G <- probes[which(probes$target == "M" & probes$dye == "G"),]
    probes.U.R <- probes[which(probes$target == "U" & probes$dye == "R"),]
    probes.U.G <- probes[which(probes$target == "U" & probes$dye == "G"),]
    
    M <- c(rg$R[probes.M.R$address], rg$G[probes.M.G$address])
    U <- c(rg$R[probes.U.R$address], rg$G[probes.U.G$address])
    
    names(M) <- c(probes.M.R$name, probes.M.G$name)
    names(U) <- c(probes.U.R$name, probes.U.G$name)
    
    U <- U[names(M)]
    list(M=M,U=U)
}

background.correct <- function(rg, probes=probe.info(), offset=15) {
    stopifnot(is.rg(rg))
    
    lapply(c(R="R",G="G"), function(dye) {
        msg("background correction for dye =", dye)
        addresses <- probes$address[which(probes$target != "OOB" & probes$dye == dye)]
        xf <- rg[[dye]][addresses]
        xf[which(xf <= 0)] <- 1
        
        addresses <- probes$address[which(probes$target == "OOB" & probes$dye == dye)]
        oob <- rg[[dye]][addresses]
        
        ests <- MASS::huber(oob) 
        mu <- ests$mu
        sigma <- log(ests$s)
        alpha <- log(max(MASS::huber(xf)$mu - mu, 10))
        xf.bkg <- limma::normexp.signal(as.numeric(c(mu,sigma,alpha)), xf) + offset
        names(xf.bkg) <- names(xf)
        xf.bkg
    })
}

dye.bias.correct <- function(rg, reference, probes=probe.info()) {
    stopifnot(is.rg(rg))
    msg()
    addresses <- probes$address[which(probes$target %in% c("NORM_A","NORM_T")
                                      & probes$dye == "R")]
    factor.R <- mean(rg$R[addresses],na.rm=T)
    
    addresses <- probes$address[which(probes$target %in% c("NORM_C","NORM_G")
                                      & probes$dye == "G")]
    factor.G <- mean(rg$G[addresses],na.rm=T)

    rg$R <- rg$R * reference/factor.R
    rg$G <- rg$G * reference/factor.G
    rg
}

collect.controls <- function(rg, probes=probe.info()) {
    stopifnot(is.rg(rg))

    msg()
    
    probes.G <- probes[which(probes$dye == "G"),]
    probes.R <- probes[which(probes$dye == "R"),]
    probes.G <- probes.G[match(names(rg$G), probes.G$address),]
    probes.R <- probes.R[match(names(rg$R), probes.R$address),]
    
    bisulfite2 <- mean(rg$R[which(probes.R$target == "BISULFITE CONVERSION II")], na.rm=T)
    
    bisulfite1.G <- rg$G[which(probes.G$target == "BISULFITE CONVERSION I"
                               & probes.G$ext
                               %in% sprintf("BS Conversion I%sC%s", c(" ", "-", "-"), 1:3))]
    bisulfite1.R <- rg$R[which(probes.R$target == "BISULFITE CONVERSION I"
                               & probes.R$ext %in% sprintf("BS Conversion I-C%s", 4:6))]
    bisulfite1 <- mean(bisulfite1.G + bisulfite1.R, na.rm=T)
    
    stain.G <- rg$G[which(probes.G$target == "STAINING" & probes.G$ext == "Biotin (High)")]
    
    stain.R <- rg$R[which(probes.R$target == "STAINING" & probes.R$ext == "DNP (High)")]
    
    extension.R <- rg$R[which(probes.R$target == "EXTENSION"
                              & probes.R$ExternalType %in% sprintf("Extension (%s)", c("A", "T")))]
    extension.G <- rg$G[which(probes.G$target == "EXTENSION"
                              & probes.G$ExternalType %in% sprintf("Extension (%s)", c("C", "G")))]
    
    hybe <- rg$G[which(probes.G$target == "HYBRIDIZATION")]
    
    targetrem <- rg$G[which(probes.G$target %in% "TARGET REMOVAL")]
    
    nonpoly.R <- rg$R[which(probes.R$target == "NON-POLYMORPHIC"
                            & probes.R$ext %in% sprintf("NP (%s)", c("A", "T")))]
    
    nonpoly.G <- rg$G[which(probes.G$target == "NON-POLYMORPHIC"
                            & probes.G$ext %in% sprintf("NP (%s)", c("C", "G")))]
    
    spec2.G <- rg$G[which(probes.G$target == "SPECIFICITY II")]
    spec2.R <- rg$R[which(probes.R$target == "SPECIFICITY II")]
    spec2.ratio <- mean(spec2.G,na.rm=T)/mean(spec2.R,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 1:3)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio1 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    ext <- sprintf("GT Mismatch %s (PM)", 4:6)
    spec1.G <- rg$G[which(probes.G$target == "SPECIFICITY I" & probes.G$ext %in% ext)]
    spec1.R <- rg$R[which(probes.R$target == "SPECIFICITY I" & probes.R$ext %in% ext)]
    spec1.ratio2 <- mean(spec1.R,na.rm=T)/mean(spec2.G,na.rm=T)
    
    spec1.ratio <- (spec1.ratio1 + spec1.ratio2)/2
    
    normA <- mean(rg$R[which(probes.R$target == "NORM_A")], na.rm = TRUE)
    normT <- mean(rg$R[which(probes.R$target == "NORM_T")], na.rm = TRUE)
    normC <- mean(rg$G[which(probes.G$target == "NORM_C")], na.rm = TRUE)
    normG <- mean(rg$G[which(probes.G$target == "NORM_G")], na.rm = TRUE)

    dye.bias <- (normA + normT)/(normC + normG)
    
    probs <- c(0.01, 0.5, 0.99)
    oob.G <- quantile(rg$G[with(probes.G, which(target == "OOB" & dye == "G"))], na.rm=T, probs=probs)
    oob.R <- quantile(rg$R[with(probes.R, which(target == "OOB" & dye == "R"))], na.rm=T, probs=probs)
    oob.ratio <- oob.G[["50%"]]/oob.R[["50%"]]
    
    model.matrix <- c(bisulfite1=bisulfite1,
                      bisulfite2=bisulfite2,
                      extension.G=extension.G,
                      extension.R=extension.R,
                      hybe=hybe,
                      stain.G=stain.G,
                      stain.R=stain.R,
                      nonpoly.G=nonpoly.G,
                      nonpoly.R=nonpoly.R,
                      targetrem=targetrem,
                      spec1.G=spec1.G,
                      spec1.R=spec1.R,
                      spec2.G=spec2.G,
                      spec2.R=spec2.R,
                      spec1.ratio1=spec1.ratio1,
                      spec1.ratio=spec1.ratio,
                      spec2.ratio=spec2.ratio,
                      spec1.ratio2=spec1.ratio2,
                      normA=normA,
                      normC=normC,
                      normT=normT,
                      normG=normG,
                      dye.bias=dye.bias,
                      oob.G=oob.G,
                      oob.ratio=oob.ratio)
}




impute.matrix <- function(x, FUN=function(x) mean(x, na.rm=T)) {
    idx <- which(is.na(x), arr.ind=T)
    if (length(idx) > 0) {
        na.rows <- unique(idx[,"row"])
        v <- apply(x[na.rows,],1,FUN)
        v[which(is.na(v))] <- FUN(v) ## if any row imputation is NA ...
        x[idx] <- v[match(idx[,"row"],na.rows)]
    }
    x
}


normalize.quantiles <- function(quantiles, control.matrix, number.pcs) {
    stopifnot(is.matrix(quantiles))
    stopifnot(is.matrix(control.matrix))
    stopifnot(ncol(quantiles) == ncol(control.matrix))
    stopifnot(number.pcs >= 2)
    
    quantiles[1,] <- 0
    ## quantiles[nrow(quantiles),] <- quantiles[nrow(quantiles)-1,] + 1000
    
    mean.quantiles <- rowMeans(quantiles)
    control.components <- prcomp(t(control.matrix))$x[,1:number.pcs,drop=F]
    design <- model.matrix(~control.components-1)
    fits <- lm.fit(x=design, y=t(quantiles - mean.quantiles))
    mean.quantiles - t(residuals(fits))
}


compute.quantiles.target <- function(quantiles) {
    n <- length(quantiles)
    unlist(lapply(1:(n-1), function(j) {
        start <- quantiles[j]
        end <- quantiles[j+1]
        seq(start,end,(end-start)/n)[-n]
    }))
 }   

normalize.sample <- function(orig.signal, orig.quantiles, norm.quantiles, primary) {
    stopifnot(length(orig.signal) == length(primary))
    stopifnot(length(orig.quantiles) == length(norm.quantiles))
    msg()
    
    norm.target <- compute.quantiles.target(norm.quantiles)

    norm.signal <- orig.signal
    norm.signal[primary] <- preprocessCore::normalize.quantiles.use.target(matrix(orig.signal[primary]), norm.target)
    if (sum(!primary) > 0) {
        orig.target <- compute.quantiles.target(orig.quantiles)
        orig.intervals <- findInterval(orig.signal[!primary], orig.target)
        norm.signal[!primary] <- norm.target[orig.intervals]
    }
    norm.signal
}

        


#!/usr/bin/Rscript

library(lme4)
library(coefplot2)
library(glmmADMB)
library(Hmisc)
library(ggplot2)

load('flows-checkpoint3.RData')

## Refit with glmmadmb due to warnings about gradients above tolerance with lme4 fits

modNames <- c('glmeundirhmax', 'glmedirhmax', 'glmehmax')
fFin <- f[modNames]

tmpf <- function(x) {
    test <- !is.na(om$cases1WksAgo)
    data <- om[test, ]
    glmmadmb(x, data=data, family='nbinom')
}
mFin <- lapply(fFin, tmpf)

## Plot of predicted cases vs flow

fund <- fortify(m$glmeundirhmax, data=model.frame(m$glmeundirhmax))
theme_set(new=theme_classic())

g <- ggplot(data=fund, aes(x=exp(logUndirectedFlowScaled), y=exp(.fitted)))
g <- g + geom_smooth(method='loess', alpha=0, size=2, color='black')
g <- g + geom_point(aes(x=I(runif(nrow(fund), min=-.1,max=.1) + exp(logUndirectedFlowScaled)),
                        y=cases), col='black', alpha=0.5)
g <- g + labs(x='Flow (swine / pairs / year)', y='Cases')
g <- g + coord_trans(y="log1p") + ylim(0,100)
ggsave('flows-prediction.eps', width=4, height=4, pointsize=18, device=cairo_ps)
ggsave('flows-prediction.pdf', width=4, height=4, pointsize=18, device=cairo_pdf)

## Plots of fixed effects

ct <- lapply(mFin, function(x) coeftab(x)[, 1:2])

extractEsts <- function(pattern, type) {
  tmpf <- function(x) grep(pattern, rownames(x))
  inds <- lapply(ct, tmpf)
  res <- list()
  mapply(function(x, y) x[y, type], ct, inds)
}
  
patterns <- list(flow='Flow', dense='logCmedDenseScaled', week='weekCent', inf='Inf')
ests <- sapply(patterns, extractEsts, type='Estimate')
sds <- sapply(patterns, extractEsts, type='Std. Error')
weekIqr <- iqr(model.frame(m$glmedirhmax)$weekCent)
ests[, 'week'] <- ests[, 'week']*weekIqr
sds[, 'week'] <- sds[, 'week']*weekIqr

stopifnot(rownames(ests) == c('glmeundirhmax', 'glmedirhmax', 'glmehmax'))
ests <- cbind(ests, baseline=c(hund$maximum, hdir$maximum, hint$maximum))
sds <- cbind(sds, baseline=0)

tmpf <- function() {
    longnames <- c(flow='Scaled transport flow', inf='Cases last week', week='Scaled week', dense='Scaled farm density', baseline='Baseline risk') 
    pal <- c('black', 'orange', 'blue')
    pch <- 15:17
    for(i in seq_len(nrow(ests))){
        coefplot2(ests[i, ], sds[i, ], varnames=longnames[colnames(ests)],
                  offset=(i-1)/10, col=pal[i], add=i>1, pch=pch[i],
                  main="Regression estimates")
    }
    legend('topright', legend=c('undirected', 'directed', 'none'), col=pal, pch=pch, title='Interstate flow')
}

pdf('coefplot.pdf', width=5,height=4)
tmpf()
dev.off()
## This works better than making the ps with R for some reason
system('pdftops coefplot.pdf')

res <- 100
png('coefplot.png', width=5*res, height=4*res, res=res)
tmpf()
dev.off()


## Table of likelihoods, dispersion, parameters, random effects

getNBTheta <- function(x) {
    if(inherits(x, 'glmmadmb')) {
        summary(x)$alpha
    } else {
        as.numeric(strsplit(family(x)$family, split='\\(|\\)')[[1]][2])
    }
}
getLL <- function(x) as.numeric(logLik(x))
getSD <- function(x) as.numeric(sqrt(VarCorr(x)$stateF))
getdf <- function(x) attr(logLik(x), 'df')
getintercept <- function(x) fixef(x)['(Intercept)']

modList <- c(mFin, m[c('nbme', 'nbmeN')])
disp <- sapply(modList, getNBTheta)
llik <- sapply(modList, getLL)
resd <- sapply(modList, getSD)
df <- sapply(modList, getdf)
int <- sapply(modList, getintercept)

tab <- data.frame(baseline=I('no'), int=unname(int), disp, resd, df, llik)
rownames(tab) <- names(modList)
tab[c('glmeundirhmax', 'glmedirhmax', 'glmehmax'), 'baseline'] <- 'yes'
tab[, 'df'] <- tab[, 'df'] + ifelse(tab[, 'baseline'] == 'yes', 1, 0)
aic <- 2*-tab[, 'llik'] + 2*tab[, 'df']
tab <- cbind(tab, deltaAIC = aic - min(aic))
flowTerm <- c(glmeundirhmax='undirected', glmedirhmax='directed', glmehmax='internal',
              nbme='internal', nbmeN='none')
tab <- data.frame(flowTerm=flowTerm[rownames(tab)], tab)
tf <- format.df(tab)
align <- paste(attr(tf, "col.just"), collapse="|")
align <- paste('|', align, '|', sep='')
longnames <- c(flowTerm='\\bf Flow term', baseline='\\bf Fit $\\eta$',
               disp='\\bf Intercept', df='\\bf d.f.', llik='\\bf Log lik.',
               deltaAIC='\\bf $\\Delta$ AIC', resd='\\bf $\\hat{\\sigma}$',
               int='{\\bf Intercept}')
colnames(tab) <- longnames[colnames(tf)]
tab <- latexTabular(tab, helvetica=FALSE, align=align, translate=FALSE,
                 cdec=c(0,0,1,2,2,0,1,1))
tab <- gsub('\\\\multicolumn\\{1\\}\\{c\\}', '', tab)

tab <- gsub('(\\\\)\\s?(\n)', '\\1\\\\hline\\2', tab)
cat(tab, file='tab.tex')


scales <- c(week=iqr(om$weekCent),
            internal=iqr(log(om$internalFlow)),
            cmedDense=iqr(log(om$cmedDense*om$nFarms*om$nFarms)),
            undirected=iqr(log(om$undirectedFlow)),
            directeted=iqr(log(om$directedFlow)))
sink(file='scales.txt')
print(scales)
sink()

## Dotplot of AICs

flowTerm <- c(glmeundirhmax='Within-state + undirected between state',
              glmedirhmax='Within-state + directed between state',
              glmehmax='Within-state only',
              nbme='Within-state only, fixed other risks ',
              nbmeN='No flow, fixed other risks')

png('aic.png', width=7*res, height=4*res, res=res)
dotchart2(aic, labels=flowTerm[rownames(tab)], xlab='AIC (i.e., Estimated information loss)', dotsize=2)
dev.off()

save.image('flows-checkpoint4.RData')

                                             
## Selecting plot element for customizaiton
observe({
  v <- input$customizeItem
  isolate({
    if(!isEmpty(v)){
      currentSheet <- (projProperties[['activeSheet']])
      if(!isEmpty(currentSheet)) sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']] <<- v
    }
  })
})
observe({
  updateInput[['customizeItem']]
  currentSheet <- projProperties[['activeSheet']]
  s <- if(!isEmpty(currentSheet)){
    isolate(sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
  } else ''
  updateTabsetPanel(session, 'customizeItem', selected=null2String(s))
})

## modify plotTitle and other text fields
lapply(c('plotTitle', 'plotXlab', 'plotYlab'),
       function(inputId){
         assign(paste0('observer_', inputId, '_push'),
                observe({
                  v <- input[[inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)){
                      sheetList[[currentSheet]][['dynamicProperties']][[inputId]] <<- v
                    }
                  })

                }),
                sessionEnv)
         assign(paste0('observer_', inputId, '_pull'),
                observe({
                  updateInput[[inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- if(!isEmpty(currentSheet)){
                    isolate(sheetList[[currentSheet]][['dynamicProperties']][[inputId]])
                  } else ''
                  updateTextInput(session, inputId, value=null2String(s))
                }),
                sessionEnv)
       })


#
#
#
# ## modify xlab
# observe({
#   v <- input$plotXlab
#   isolate({
#     currentSheet <- (projProperties[['activeSheet']])
#     if(!isEmpty(currentSheet)){
#       sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']] <<- v
#     }
#   })
#
# })
# observe({
#   updateInput[['plotXlab']]
#   currentSheet <- projProperties[['activeSheet']]
#   s <- if(!isEmpty(currentSheet)){
#     isolate(sheetList[[currentSheet]][['dynamicProperties']][['plotXlab']])
#   } else ''
#   updateTextInput(session, 'plotXlab', value=null2String(s))
# })
#
# ## modify ylab
# observe({
#   v <- input$plotYlab
#   isolate({
#     currentSheet <- (projProperties[['activeSheet']])
#     if(!isEmpty(currentSheet)){
#       sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']] <<- v
#     }
#   })
#
# })
# observe({
#   updateInput[['plotYlab']]
#   currentSheet <- projProperties[['activeSheet']]
#   s <- if(!isEmpty(currentSheet)){
#     isolate(sheetList[[currentSheet]][['dynamicProperties']][['plotYlab']])
#   } else ''
#   updateTextInput(session, 'plotYlab', value=null2String(s))
# })


###########################
## Text Formatting
#
# ## Selecting font family
# observe({
#   v <- input$textFamily
#   isolate({
#     if(!isEmpty(v)){
#       currentSheet <- (projProperties[['activeSheet']])
#       if(!isEmpty(currentSheet)) {
#         customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
#         if(!isEmpty(customizeItem)){
#           if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
#             sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
#           }
#           sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][['textFamily']] <<- v
#         }
#       }
#     }
#   })
# })
# observe({
#   updateInput[['textFamily']]
#   currentSheet <- projProperties[['activeSheet']]
#   s <- ''
#   if(!isEmpty(currentSheet)){
#     customizeItem <- (sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
#     if(!isEmpty(customizeItem) && !is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
#       s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][['textFamily']])
#     }
#   }
#
#   updateSelectInput(session, 'textFamily', selected=null2String(s))
# })
#
# ## Selecting font face
# observe({
#   v <- input$textFace
#   isolate({
#     if(!isEmpty(v)){
#       currentSheet <- (projProperties[['activeSheet']])
#       if(!isEmpty(currentSheet)) {
#         customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
#         if(!isEmpty(customizeItem)){
#           if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
#             sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
#           }
#           sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][['textFace']] <<- v
#         }
#       }
#     }
#   })
# })
# observe({
#   updateInput[['textFace']]
#   currentSheet <- projProperties[['activeSheet']]
#   s <- ''
#   if(!isEmpty(currentSheet)){
#     customizeItem <- (sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
#     if(!isEmpty(customizeItem) && !is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
#       s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][['textFace']])
#     }
#   }
#
#   updateSelectInput(session, 'textFace', selected=null2String(s))
# })

# ## Selecting font color
# observe({
#   v <- input$textColor
#   isolate({
#     currentSheet <- (projProperties[['activeSheet']])
#     if(!isEmpty(currentSheet)) {
#       customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
#       if(!isEmpty(customizeItem)){
#         if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
#           sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
#         }
#         if(!isEmpty(v)) v <- paste0("#", v)
#         sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][['textColor']] <<- v
#       }
#     }
#   })
# })

## font size, etc.
lapply(list(list(inputId='textFamily', inputType='select'),
            list(inputId='textFace', inputType='select'),
            list(inputId='textColor', inputType='color'),
            list(inputId='textSize', inputType='numeric'),
            list(inputId='textHjust', inputType='numeric'),
            list(inputId='textVjust', inputType='numeric'),
            list(inputId='textAngle', inputType='numeric'),
            list(inputId='textLineheight', inputType='numeric')),
       function(x){
         assign(paste0('observer_', x$inputId, '_push'),
                observe({
                  v <- input[[x$inputId]]
                  isolate({
                    currentSheet <- (projProperties[['activeSheet']])
                    if(!isEmpty(currentSheet)) {
                      customizeItem <- sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']]
                      if(!isEmpty(customizeItem)){
                        if(is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]] <<- list()
                        }
                        if(x$inputId=='textColor' && !isEmpty(v)) v <- paste0("#", v)
                        if(are.vectors.different(v, sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]]))
                          sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]] <<- v
                      }
                    }
                  })
                }),
                sessionEnv)
         if(x$inputId=='textColor') return() ## no updateJsColorInput is available yet
         assign(paste0('observer_', x$inputId, '_pull'),
                observe({
                  updateInput[[x$inputId]]
                  currentSheet <- projProperties[['activeSheet']]
                  s <- ''
                  if(!isEmpty(currentSheet)){
                    customizeItem <- (sheetList[[currentSheet]][['dynamicProperties']][['customizeItem']])
                    if(!isEmpty(customizeItem) && !is.null(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]])){
                      s <- isolate(sheetList[[currentSheet]][['dynamicProperties']][[customizeItem]][[x$inputId]])
                    }
                  }

                  switch(x$inputType,
                         'numeric'=updateNumericInput(session, x$inputId, value=null2String(s)),
                         'select'=updateSelectInput(session, x$inputId, selected=null2String(s)))

                }),
                sessionEnv)
       })


## End of Text Formatting
###########################

# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to) %>%
        .b$omit$dups() %>%
        .b$omit$empty()
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap", "backtrack", "tswap", "r00"
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42, method="r0")
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="r0")
{
   method <- match.arg(method, c("r0", "r1", "r2", "r00", "c0", "swap", "tswap", "backtrack", "quasiswap"))
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      permuted_HP <- vegan::commsimulator(D$HP, method)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   D$method <- method
   return(D)
}
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
probe system/script/args
if args: any [system/script/args system/options/args][
	batch-mode: find args "--batch"
	fast-mode:  find args "--fast"
]
?? fast-mode
;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either fast-mode [
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
        
    ][
        do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
batch-mode: all [system/options/args find system/options/args "--batch"]
fast-mode: all [system/options/args find system/options/args "--fast"]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

do %source/units/run-all-init.r

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

do %source/units/run-all-extra-tests.r

===start-group=== "Main Red Tests"
    either fast-mode [
        --run-test-file-quiet %source/units/auto-tests/run-all-comp1.red
        --run-test-file-quiet %source/units/auto-tests/run-all-comp2.red
        --run-test-file-quiet %source/units/auto-tests/run-all-interp.red
        
    ][
        do %source/units/auto-tests/run-each-comp.r
        do %source/units/auto-tests/run-each-interp.r
    ]
===end-group===

***end-run-quiet***

--delete-temp-files

do %source/units/run-all-final.r
library(pcapack)

set.seed(1234)

m <- 10
n <- 50

x <- matrix(rnorm(m*n), m, n)


test <- function()
{
  mdl1 <- prcomp(x)
  mdl2 <- pca(x, method="svd")
#  mdl3 <- pca(x, method="svd", retx=FALSE)
  
#  all.equal(mdl1, mdl2)
  print(all.equal(mdl1$sdev, mdl2$sdev))
  print(all.equal(mdl1$rotation, mdl2$rotation))
  
  invisible()
}



test()

#Install dependencies
install.packages("reshape2")
install.package("ggplot2")

#Requires
require("reshape2")
require("ggplot2")

#Import the data
teams <- read.csv("./the-blue-alliance-data-master/the-blue-alliance-data-master/teams/teams.csv", header=FALSE)
names(teams) <- c("number", "name", "sponsors", "location", "website", "rookie_year")

#Let's parese the location further down into state
teams <- cbind(teams,colsplit(teams$location, pattern = ",", names = c("city","state","country")))

#Let's take a look ate how many teams join each year
png("new-teams-by-year.png")
hist(teams$rookie_year)
dev.off()

#Let's look at how many teams are in each sate
#TODO
png("team-count-by-state.png")
hist(sum(teams$location))
plot(table(teams$state))
dev.off()


library(pcapack)
library(rbenchmark)

m <- 1e4
n <- 250
x <- matrix(rnorm(m*n), m, n)

reps <- 5

benchmark(cov(x), pcapack_cov(x), replications=reps, columns=c("test", "elapsed", "relative"))

#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

library(data.table)

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)

  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       #input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       input=PCoA_in, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

library(data.table)

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       #input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       input=PCoA_in, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

library(data.table)

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
#my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



#my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
## con_2 <- file(PCoA_in)
## # read through the first time to get the number of samples
## open(con_1);
## num_values <- 0
## data_type = "NA"
## while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("PCO", my_line) ) == 1  ){
##     num_values <- num_values + 1
##   }
## }
## close(con_1)
## # create object for values
## eigen_values <- matrix("", num_values, 1)
## dimnames(eigen_values)[[1]] <- 1:num_values
## eigen_vectors <- matrix("", num_values, num_values)
## dimnames(eigen_vectors)[[1]] <- 1:num_values
## # read through a second time to populate the R objects
## value_index <- 1
## vector_index <- 1
## open(con_2)
## current.line <- 1
## data_type = "NA"
## while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
##   if ( length( grep("#", my_line) ) == 1  ){
##     if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
##         data_type="eigen_values"
##       } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
##         data_type="eigen_vectors"
##       }
##   }else{
##     split_line <- noquote(strsplit(my_line, split="\t"))
##     if ( identical(data_type, "eigen_values")==TRUE ){
##       dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
##       eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
##       value_index <- value_index + 1
##     }
##       if ( identical(data_type, "eigen_vectors")==TRUE ){
##         dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
##         for (i in 2:(num_values+1)){
##           eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
##         }
##         vector_index <- vector_index + 1
##       }
##   }
## }
## close(con_2)
## # finish labeling of data objects
## dimnames(eigen_values)[[2]] <- "EigenValues"
## dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
## class(eigen_values) <- "numeric"
## class(eigen_vectors) <- "numeric"
## # write imported data to global objects
## #eigen_values <<- eigen_values
## #eigen_vectors <<- eigen_vectors

## runtime <- Sys.time () - start
## print(paste("runtime:", round(runtime, digits=2), "seconds"))
## return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

load_pcoa_data.new <- function(PCoA_in){
  
  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  
  eigen_vectors.raw <- as.matrix(
                                 fread(
                                       input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                       skip="mgm", showProgress=TRUE, colClasses="character"
                                       )
                                 )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
  
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
con_2 <- file(PCoA_in)
# read through the first time to get the number of samples
open(con_1);
num_values <- 0
data_type = "NA"
while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
  if ( length( grep("PCO", my_line) ) == 1  ){
    num_values <- num_values + 1
  }
}
close(con_1)
# create object for values
eigen_values <- matrix("", num_values, 1)
dimnames(eigen_values)[[1]] <- 1:num_values
eigen_vectors <- matrix("", num_values, num_values)
dimnames(eigen_vectors)[[1]] <- 1:num_values
# read through a second time to populate the R objects
value_index <- 1
vector_index <- 1
open(con_2)
current.line <- 1
data_type = "NA"
while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
  if ( length( grep("#", my_line) ) == 1  ){
    if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
  }else{
    split_line <- noquote(strsplit(my_line, split="\t"))
    if ( identical(data_type, "eigen_values")==TRUE ){
      dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
      eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
      value_index <- value_index + 1
    }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
  }
}
close(con_2)
# finish labeling of data objects
dimnames(eigen_values)[[2]] <- "EigenValues"
dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
class(eigen_values) <- "numeric"
class(eigen_vectors) <- "numeric"
# write imported data to global objects
#eigen_values <<- eigen_values
#eigen_vectors <<- eigen_vectors

runtime <- Sys.time () - start
print(paste("runtime:", round(runtime, digits=2), "seconds"))
return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))




my_object <- load_pcoa_data.original("wgs_raw_ssL3.counts.10-15-14.txt.bray-curtis.PCoA")


load_pcoa_data.original <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)


  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}



my_object2 <- load_pcoa_data.new("fierer_data.raw.genus_counts.10-7-14.txt.DESeq_blind.PREPROCESSED.txt.bray-curtis.PCoA")

load_pcoa_data.new <- function(PCoA_in){

  start <- Sys.time ()
  print(paste("start:", start))

  con_1 <- file(PCoA_in)

  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values


  eigen_vectors.raw <- as.matrix(
                                   fread(
                                         input=metadata_file, sep="\t", stringsAsFactors=FALSE,
                                         skip="mgm", showProgress=TRUE, colClasses="character"
                                         )
                                   )
  
  eigen_vectors.raw.test <<- eigen_vectors.raw
  
  eigen_vectors <- eigen_vectors.raw[ , 2:ncol(eigen_vectors.raw)] # Load the metadata table (same if you use one or all columns)
  dimnames(eigen_vectors)[[1]] <- eigen_vectors.raw[,1]
    
  #test_table <- fread(PCoA_in, skip="PCO1", colClasses="character")

  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  #return(test_table)

  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))

}
  
  
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  
  runtime <- Sys.time () - start
  print(paste("runtime:", round(runtime, digits=2), "seconds"))
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}


import_package = function (package, attach) {
    stopifnot(inherits(package, 'character'))

    if (missing(attach)) {
        attach = if (interactive() && is.null(module_name()))
            getOption('import.attach', FALSE)
        else
            FALSE
    }

    stopifnot(class(attach) == 'logical' && length(attach) == 1 ||
              class(attach) == 'character')

    if (is.character(attach)) {
        export_list = attach
        attach = TRUE
    }
    else
        export_list = NULL

    module_parent = parent.frame()

    # TODO: Do we actually need this? Nothing is attached here, even if loading
    # the package via `library` would attach stuff.
    # Furthermore, S4 functions don’t work, and nor do S3, I’d wager.

    # Package which use `Depends` will pollute the global `search()` path.
    # We save the old `search()` path, and restore it afterwards. Furthermore,
    # We attach the list of attached packages to our local parent environment
    # chain instead.
    old_search = search()
    on.exit({
        if (! identical(module_parent, .GlobalEnv)) {
            newly_attached = setdiff(search(), old_search)
            for (pkg in newly_attached)
                detach(pkg)

            # Insert them into the current package’s parent chain.
            # We only need to insert the first one, since it already has the
            # others as its parents.
            # NOTE: This relies on the fact that `setdiff` doesn’t change the
            # order of the elements.

            parent.env(tail(newly_attached, 1)) = parent.env(module_parent)
            parent.env(module_parent) = newly_attached[1]
        }
    })

    pkg_ns = require_namespace(package)
    if (inherits(pkg_ns, 'error'))
        stop('Unable to load packge ', sQuote(package), '\n',
             'Failed with error: ', sQuote(conditionMessage(pkg_ns)))

    # TODO: Handle attaching

    pkg_ns
}

# Similar to `base::requireNamespace`, but returns the package namespace,
# doesn’t swallow the error message, and without NSE shenanigans.
require_namespace = function(package) {
    ns = .Internal(getRegisteredNamespace(package))
    if (is.null(ns))
        ns = tryCatch(loadNamespace(package), error = identity)

    ns
}
REBOL [
	Title:   "Builds and Runs All Red and Red/System Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.2.1
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; function to find and run-tests
run-all-script: func [
	dir [file!]
][
	qt/tests-dir: system/script/path/:dir
  	foreach line read/lines dir/run-all.r [
  		if any [
			find line "===start-group"
  	  		find line "--run-"
  		][
  			do line
  		]
  	]
]

batch-mode: false
binary?: false
if system/script/args  [
	;; should we run non-interactively?
	batch-mode: find system/script/args "--batch"

	;; should we use the binary compiler?
	args: parse system/script/args " "
	if find system/script/args "--binary" [
		binary?: true
		bin-compiler: select args "--binary"
		if bin-compiler = "--batch" [
			bin-compiler: none								;; use default
		]
		if bin-compiler [						
			if not attempt [exists? to file! bin-compiler] [
				either batch-mode [
					write %quick-test/quick-test.log "Invalid compiler path"
					quit/return 1
				][
					print "Invalid compiler path supplied"
					print args
					print ""
					halt
				]
			]
		]
	
	]
]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true
store-current-dir: what-dir

do %quick-test/quick-test.r
if binary? [
	qt/binary?: binary?
	if bin-compiler [qt/bin-compiler: bin-compiler]
]

;; run the tests
print rejoin ["Quick-Test v" qt/version]
print rejoin ["REBOL " system/version]

start-time: now/precise

***start-run-quiet*** "Complete Red Test Suite"
qt/tests-dir: clean-path %system/tests/
do %system/tests/source/units/make-red-system-auto-tests.r
qt/tests-dir: clean-path %tests/
do %tests/source/units/make-red-auto-tests.r
do %tests/source/units/make-interpreter-auto-tests.r
qt/script-header: "Red []"
run-all-script %tests/
qt/script-header: "Red/System []"
qt/tests-dir: clean-path %system/tests/
run-all-script %system/tests/

***end-run-quiet***

end-time: now/precise
print ["       in" difference end-time start-time newline]
system/options/quiet: store-quiet-mode
change-dir store-current-dir
either batch-mode [
	quit/return either qt/test-run/failures > 0 [1] [0]
][
	print ["The test output was logged to" qt/log-file]
	ask "hit enter to finish"
	print ""
	qt/test-run/failures
]
library(plyr)
library(ggplot2)

# read in house sales data
path = system.file(package='RIntroBayarea')
sales_file <- paste0(path, "/extdata/house-sales.csv")
sales <- read.csv(sales_file, stringsAsFactors=FALSE)

# read in geolocation data
ad_file <- paste0(path, '/extdata/addresses.csv')
ad <- read.csv(ad_file, stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))

# and prices into numeric values
sales$price <- as.numeric(sales$price)

# check if there are missing vaules in sales or date
any(is.na(sales$price))
any(is.na(sales$date))

# remove missing rows with missing dates
sales <- sales[!is.na(sales$date), ]

# combine sales data with geospatial information
names(sales)
names(ad)

# by common columns
intersect_cols <- intersect(names(sales), names(ad))
geo <- join(sales, ad, by = intersect_cols)

# choose only records with goog quality geocoding
precise_qual <- c(
  "QUALITY_ADDRESS_RANGE_INTERPOLATION", "QUALITY_EXACT_PARCEL_CENTROID",
  "gpsvisualizer")
precise <- subset(geo, quality %in% precise_qual)

# choose cities with at least 20 sales a week
# how many weeks does our dataset cover?
n_weeks <- as.integer((max(precise$date) - min(precise$date)) / 7)

# calculate sales per city
cities <- as.data.frame(table(precise$city))
names(cities) <- c('city', 'freq')

big_cities <- subset(cities, freq > n_weeks * 20)

# see what we actually pick up
ggplot(geo, aes(city)) +
  geom_histogram() +
  geom_hline(yintercept=n_weeks*20)

# add interesting citie
selected <- c(as.character(big_cities$city), 'Mountain View', 'Berkley')
bigc_geo <- subset(geo, city %in% selected)
REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	;--                 [objects images shapes sounds strings]
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   40]
		%PlanetaZluta      [600     1300   100    250   40]
		%PlanetaTermiti    [600     1300   100    290   40]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 300 40]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 0.5 * length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]#' Environment of loaded modules
#'
#' Each module is stored as an environment inside \code{.loaded_modules} with
#' the module’s code location path as its identifier. The path rather than the
#' module name is used because module names are not unique: two modules called
#' \code{a} can exist nested inside modules \code{b} and \code{c}, respectively.
#' Yet these may be loaded at the same time and need to be distinguished.
.loaded_modules = new.env()

is_module_loaded = function (module_path)
    exists(module_path, envir = .loaded_modules)

cache_module = function (module_ns)
    assign(module_path(module_ns), module_ns, envir = .loaded_modules)

get_loaded_module = function (module_path)
    get(module_path, envir = .loaded_modules)

#' Get a module’s path
#'
#' @param module a module environment or namespace
#' @return A character string containing the module’s full path.
module_path = function (module)
    attr(module, 'path')

#' Get a module’s base directory
#'
#' @param module a module environment or namespace
#' @return A character string containing the module’s base directory,
#'  or the current working directory if not invoked on a module.
module_base_path = function (module)
    UseMethod('module_base_path')

module_base_path.default = function (module) {
    if (identical(module, .GlobalEnv))
        script_path()
    else
        module_base_path(parent.env(module))
}

module_base_path.module = function (module)
    dirname(module_path(module))

module_base_path.namespace = function (module)
    dirname(module_path(module))

#' Return an R script’s path
script_path = function () {
    # Take a best guess at a script’s path. The following calling situations are
    # covered:
    #
    # 1. Rscript script.r
    # 2. R CMD BATCH script.r
    # 3. Script run interactively (give up, use `getwd()`)

    args = commandArgs()

    file_arg = grep('--file=', args)
    if (length(file_arg) != 0)
        return(dirname(sub('--file=', '', args[file_arg])))

    f_arg = grep('-f', args)
    if (length(f_arg) != 0)
        return(dirname(args[f_arg + 1]))

    getwd()
}

#' Get a module’s name
#'
#' @param module a module environment (default: current module)
#' @return A character string containing the name of the module or \code{NULL}
#'  if called from outside a module.
#' @note A module’s name is the name of a module that it was \code{import}ed
#' with. If the same module is subsequently imported using another qualifie
#' name (from within the same package, say, and hence truncated), the module
#' names of the two module instances may differ, even though the same copy of
#' the byte code is used.
#' This function approximates Python’s magic variable \code{__name__}, and can
#' be used similarly to test whether a module was loaded via \code{import} or
#' invoked directly.
#' @examples
#' \dontrun{
#' cat('This code is always executed.\n')
#'
#' if (is.null(module_name())) {
#'     cat('This code is only executed when the module is run
#'         as stand-alone code via Rscript or R CMD BATCH.\n')
#' }
#' }
#' @export
module_name = function (module = parent.frame())
    UseMethod('module_name', module)

#' @seealso \code{module_name}
#' @export
module_name.default = function (module = parent.frame()) {
    if (identical(module, .GlobalEnv))
        NULL
    else
        module_name(parent.env(module))
}

#' @seealso \code{module_name}
#' @export
module_name.module = function (module = parent.frame())
    strsplit(attr(module, 'name'), ':', fixed = TRUE)[[1]][2]

#' @seealso \code{module_name}
#' @export
module_name.namespace = function (module = parent.frame())
    strsplit(attr(module, 'name'), ':', fixed = TRUE)[[1]][2]
# read in house sales data

sales_file <- system.file('inst/extdata', 'house-sales.csv', package='RInroBayarea' )
sales <- read.csv(sales_file, stringsAsFactors=FALSE)

# read in geolocation data
ad_file <- system.file('inst', 'extdata', 'addresses.csv', package='RIntroBayarea' )
ad <- read.csv(ad_file, stringsAsFactors=FALSE)

# by default everything is read in as strings
# we need to convert date strings into date objects
sales$date <- as.POSIXct(strptime(sales$date, '%Y-%m-%d'))

# and prices into numeric values
sales$price <- as.numeric(sales$price)

# check if there are missing vaules in sales or date
any(is.na(sales$price))
any(is.na(sales$date))

# remove missing rows with missing dates
sales <- sales[!is.na(sales$date), ]

# combine sales data with geospatial information
names(sales)
names(ad)

geo <- join(sales, ad, by = c())install.packages("datasets", dependencies = TRUE)
install.packages("methods", dependencies = TRUE)
install.packages("ggplot2", dependencies = TRUE)
install.packages("knitr", dependencies = TRUE)
## No upload progress bar
fileInput1 <-
function (inputId, label, multiple = FALSE, accept = NULL)
{
  inputTag <- tags$input(id = inputId, name = inputId, type = "file")
  if (multiple)
    inputTag$attribs$multiple <- "multiple"
  if (length(accept) > 0)
    inputTag$attribs$accept <- paste(accept, collapse = ",")
  tagList(tags$label(label), inputTag)
}


shinyUI(navbarPage(
  id='mainNavBar',
  title="shinyData (Beta)",

  tabPanel(title='Project',

           div(selectInput('sampleProj',
                                list(actionButton('openSampleProj', 'Open', styleclass="primary", size="small"), 'Sample Project:'),
                                choices=list.files('samples')),
               class = "pull-right"),
           br(),

           downloadButton('downloadProject', 'Save Project to File'),

           tags$hr(),

           fileInput1('loadProject', 'Import Project from File', accept=c('.sData')),
           radioButtons('loadProjectAction', '',
                        choices=c('Replace existing work'='replace',
                                  'Merge with existing work'='merge'),
                        selected='replace', inline=FALSE),

           tags$hr(),
           includeMarkdown('md/about.md')
  ),



  tabPanel(title="Data",

           sidebarLayout(
             sidebarPanel(

               selectInput(inputId="datList", label="", choices=NULL),

               tags$hr(),

               fileInput1('file', 'Add Text File',
                         accept=c('text/csv',
                                  'text/comma-separated-values,text/plain',
                                  '.csv')),
               tags$hr(),

               conditionalPanel("output.uploadingTextFile==true",
                                checkboxInput('header', 'Header', TRUE),
                                radioButtons('sep', 'Separator',
                                             c(Comma=',',
                                               Semicolon=';',
                                               Tab='\t'),
                                             ','),
                                radioButtons('quote', 'Quote',
                                             c(None='',
                                               'Double Quote'='"',
                                               'Single Quote'="'"),
                                             '"')
                                )


             ),
             mainPanel(
               textInput('datName', 'Data Source Name'),

               tags$hr(),

               selectizeInput(inputId="measures", label="Measures",
                              choices=NULL, multiple=TRUE,
                              options=list(
                                placeholder = '',
                                plugins = I("['remove_button']"))),

               tags$hr(),

               selectizeInput(inputId="fieldsList", label="Fields Details",
                              choices=NULL),
               textInput('fieldName', 'Field Name'),

               tags$hr(),

               h4('Preview'),
               dataTableOutput('datPreview')



               )
             )
           ),

  tabPanel(title='Visualize',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(6, selectInput(inputId='sheetList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addSheet', label='Add Sheet', styleclass="primary", size="small"),
                   actionButton(inputId='deleteSheet', label='Delete Sheet', styleclass="danger", size="small")
                 ))
               ),
               fluidRow(
                 column(6, selectInput(inputId='layerList', label='', choices=NULL, selected='')),
                 column(6, fluidRow(
                   actionButton(inputId='addLayer', label='Add Overlay', styleclass="primary", size="small"),
                   actionButton(inputId='bringToTop', label='Bring to Top', styleclass="primary", size="small"),
                   conditionalPanel('input.layerList!="Plot"',
                                    actionButton(inputId='deleteLayer', label='Delete Overlay', styleclass="danger", size="small")
                                    )
                   ))
                 ),

               tabsetPanel(
                 tabPanel('Type',
                          fluidRow(
                            column(6,
                                   selectInput(inputId='markList', label='Mark Type',
                                               choices=GeomChoices, selected='bar'),
                                   selectInput(inputId='layerPositionType', label='Positioning',
                                               choices=c('Stack'='stack','Dodge'='dodge','Fill'='fill',
                                                         'Identity'='identity','Jitter'='jitter'),
                                               selected='stack'),
                                   fluidRow(
                                     column(6,
                                            textInput('layerPositionWidth', label='Width')
                                            ),
                                     column(6,
                                            textInput('layerPositionHeight', label='Height')
                                            )
                                     )
                            ),
                            column(6,
                                   selectInput(inputId='statTypeList', label='Stat',
                                               choices=StatChoices, selected='identity'),
                                   conditionalPanel('input.statTypeList=="summary"',
                                                    selectizeInput(inputId='yFunList', label='Summarize Y with',
                                                                   choices=YFunChoices,
                                                                   selected='sum', multiple=FALSE,
                                                                   options = list(create = TRUE)))
                            )
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          ),
                 tabPanel('Mapping',

                          fluidRow(
                            column(6,
                                   selectInput(inputId='aesList', label='',
                                               choices=NULL)
                                   ),
                            column(6,
                                   conditionalPanel('input.layerList != "Plot" ||
                                                    (input.aesList!="aesX" && input.aesList!="aesY")',
                                                    radioButtons('aesMapOrSet', '', choices=c('Map to variable'='map',
                                                                                              'Set to fixed value'='set'),
                                                                 selected='map')
                                                    )

                                   )
                            ),

                          uiOutput('mapOrSetUI'),
                          conditionalPanel('(input.aesList=="aesColor" || input.aesList=="aesBorderColor") &&
                                           input.aesMapOrSet=="set"',
                                           jscolorInput('aesValueColor')),

                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                        ),
                 tabPanel('Filters',
                          selectizeInput(inputId='filterField', label='Field',
                                         choices=NULL, multiple=FALSE),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                  ),

                 tabPanel('Customize',
                          navlistPanel(id='customizeItem',
                            'Labels',
                            tabPanel('Plot Title', value='title',
                                     textInput('plotTitle', '')
                                     ),
                            tabPanel('X Axis Title', value='xlab',
                                        textInput('plotXlab', '')
                            )
                            ),
                          conditionalPanel('true',
                                           h4('Format Text'),
                                           fluidRow(
                                             selectInput('textFamily','Font Family', choices=FontFamilyChoices),
                                             selectInput('textFace', 'Font Face', choices=FontFaceChoices),
                                             jscolorInput('textColor'),
                                             numericInput('textSize', 'Font Size (pts)', value=NULL, step=0.1)
                                             )
                                           ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
               )
               ),
             mainPanel(
               textInput('sheetName', label=''),
               tags$hr(),
               fluidRow(
                 column(4,
                        selectInput(inputId='outputTypeList', label='Output Type',
                                    choices=c('Table'='table','Plot'='plot'), selected='plot'),
                        radioButtons('autoRefresh', label='',
                                     choices=c('Auto Refresh'='refresh','Pause Refreshing'='pause'), selected='refresh')
                        ),
                 column(4,
                        selectInput(inputId='sheetDatList', label='Data', choices=NULL),
                        checkboxInput('combineMeasures', label='Combine Measures')
                        ),
                 column(4,
                        selectizeInput(inputId="columns", label="Facet Columns",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']"))),
                        selectizeInput(inputId="rows", label="Facet Rows",
                                       choices=NULL, multiple=TRUE,
                                       options=list(
                                         placeholder = '',
                                         plugins = I("['remove_button','drag_drop']")))
                        )
                 ),
               tags$hr(),
               uiOutput('sheetOutput')
               )
             )
           ),


  tabPanel(title='Presentation',

           sidebarLayout(
             sidebarPanel(
               fluidRow(
                 column(3, selectInput(inputId='docList', label='', choices=NULL, selected='')),
                 column(9, fluidRow(
                   actionButton(inputId='addDoc', label='Add Document', styleclass="primary", size="small"),
                   actionButton(inputId='deleteDoc', label='Delete Document', styleclass="danger", size="small")
                 ))
               ),

               tabsetPanel(
                 tabPanel('Instructions',

                          br(),
                          includeMarkdown('md/rmdInstructions.md'),

                          checkboxInput('withRChunk', label='Insert with R chunk enclosure', value=TRUE),
                          fluidRow(
                            column(6, selectInput(inputId='datNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertDatName', label='Insert Data', styleclass="primary", size="small")
                            ))
                          ),
                          fluidRow(
                            column(6, selectInput(inputId='sheetNameToInsert', label='', choices=NULL, selected='')),
                            column(6, fluidRow(
                              actionButton(inputId='insertSheetName', label='Insert Sheet', styleclass="primary", size="small")
                            ))
                          ),
                          br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br()
                          )
                 )
               ),
             mainPanel(
               textInput('docName', label=''),
               tags$hr(),
               div(downloadButton('downloadRmdOutput', 'Generate Output'), class = "pull-right"),
               selectInput('rmdOuputFormat','Output Format',
                           choices=c('HTML'='html_document', 'PDF'='pdf_document',
                                     'Word'='word_document', 'Markdown'='md_document',
                                     'ioslides'='ioslides_presentation',
                                     'Slidy'='slidy_presentation',
                                     'Beamer'='beamer_presentation'),
                           selected=''),

               tags$hr(),
               tabsetPanel(id='rmdTabs',
                 tabPanel('R_Markdown',
                          aceEditor('rmd', mode='markdown', value='', cursorId="rmdCursor",
                                    selectionId='rmdSelection', wordWrap=TRUE)
                          ),
                 tabPanel('Preview',
                          uiOutput('rmdOutput')
                          )
                 )
               )
             )
           ),



  tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"),
            tags$style(type='text/css', "button { margin-top: 20px; }"),
            tags$style(type='text/css', "#openSampleProj { margin-top: 0px; }")
            )


))

#' Contribution of individual links
#' @param D A list returned by proc_analysis
#' @param ... Additional arguments to be passed to PACo
#' @return A list with added object jacknife, containing the mean and upper CI values for each link
#' @export
paco_links <- function(D, ...)
{
   HP.ones <- which(D$HP > 0, arr.ind=TRUE)
   SQres.jackn <- matrix(rep(NA, sum(D$HP)^2), sum(D$HP))# empty matrix of jackknifed squared residuals
   colnames(SQres.jackn) <- paste(rownames(D$proc$X),rownames(D$proc$Yrot), sep="-") #colnames identify the H-P link
   t.critical = qt(0.975,sum(D$HP)-1) #Needed to compute 95% confidence intervals.
   for(i in c(1:sum(D$HP))) #PACo setting the ith link = 0
   {
      HP_ind <- D$HP
      HP_ind[HP.ones[i,1],HP.ones[i,2]]=0
      PACo.ind <- PACo(list(H=D$H, P=D$P, HP=HP_ind), method=D$method, ...)
      Proc.ind <- vegan::procrustes(X=PACo.ind$H_PCo, Y=PACo.ind$P_PCo) 
      res.Proc.ind <- c(residuals(Proc.ind))
      res.Proc.ind <- append(res.Proc.ind, NA, after= i-1)
      SQres.jackn[i, ] <- res.Proc.ind   #Append residuals to matrix of jackknifed squared residuals
   } 
   SQres.jackn <- SQres.jackn^2 #Jackknifed residuals are squared
   SQres <- (residuals(D$proc))^2 # Vector of original square residuals
   #jackknife calculations:
   SQres.jackn <- SQres.jackn*(-(sum(D$HP)-1))
   SQres <- SQres*sum(D$HP)
   SQres.jackn <- t(apply(SQres.jackn, 1, "+", SQres)) #apply jackknife function to matrix
   phi.mean <- apply(SQres.jackn, 2, mean, na.rm = TRUE) #mean jackknife estimate per link
   phi.UCI <- apply(SQres.jackn, 2, sd, na.rm = TRUE) #standard deviation of estimates
   phi.UCI <- phi.mean + t.critical * phi.UCI/sqrt(sum(D$HP))
   D$jackknife <- list(mean = phi.mean, upper = phi.UCI)
   return(D)
}
library = function (...) suppressMessages(base::library(...))
assign('library', library, globalenv())

library(knitr)
library(modules)

options(stringsAsFactors = FALSE,
        import.path = file.path(Sys.getenv('HOME'), 'Projects/R'))

#opts_chunk$set(cache = TRUE)

# Pretty-print tables

library(pander)

panderOptions('table.split.table', Inf)
panderOptions('table.alignment.default',
              function (df) ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.alignment.rownames', 'left')

# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
    if (is.data.frame(object) ||
        is.matrix(object) ||
        is.tbl_df(object))
        pander(object, style = 'rmarkdown')
    else if (isS4(object))
        show(object)
    else
        print(object)
})

# Helpers for dplyr tables

is.tbl_df = function (x)
    'tbl_df' %in% class(x)

pander.tbl_df = function (x, ...)
    pander(trunc_mat(x), ...)

# Copied from dplyr:::print.trunc_mat
pander.trunc_mat = function (x, ...) {
    if (! is.null(x$table))
        pander(x$table, ...)

    if (length(x$extra) > 0) {
        var_types = paste0(names(x$extra), ' (', x$extra, ')', collapse = ', ')
        pander(dplyr:::wrap('Variables not shown: ', var_types))
    }
}

# Disable code re-formatting.
opts_chunk$set(tidy = FALSE)

## conditional calculated field: mutate and ddply; see documentation for ddply
## groups: use selectInput with multiple=TRUE and selectize = FALSE
## http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information

## GitHub Hosting example: https://gist.github.com/mattbrehmer/5645155
## Alternative to ggplot2: https://github.com/ramnathv/rCharts

#options(error = browser)
# NULL, browser, etc.
options(shiny.error=NULL)
# options(shiny.error=function() {
#   ## skip validation errors
#   if(!inherits(eval.parent(expression(e)), "validation")) browser()
# })
options(shiny.trace = FALSE)  # change to TRUE for trace
#options(shiny.reactlog=TRUE)

require(shiny); require(reshape); require(ggplot2); require(Hmisc); require(uuid); #require(plotly);
require(tables); require(tools); require(png); require(data.table); require(shinysky); require(Cairo)
require(knitr); require(rmarkdown); require(shinyAce)

options(shiny.usecairo=TRUE)


MoltenMeasuresName <- 'value'
lengthUnique <<- function(x) { length(unique(x)) }
YFunChoices <- c('Sum'='sum','Mean'='mean','Median'='median','Min'='min','Max'='max',
                 'Standard Deviation'='sd','Variance'='var','Count'='length', 'Count (Distinct)'='lengthUnique')
AggFunChoicesDimension <- c('Min'='min','Max'='max',
                            'Count'='length', 'Count (Distinct)'='lengthUnique')
InternalY <- '..y..'


GeomChoices <- c('Text'='text', 'Bar'='bar','Line'='line',
                 'Area'='area',  'Point'='point',
                 'Path'='path','Polygon'='polygon',
                 'Boxplot'='boxplot')
StatChoices <- c('Identity'='identity','Count'='bin','Summary'='summary','Boxplot'='boxplot')


getAesChoices <- function(geom, stat='identity'){
  switch(geom,
         'text'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                           'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                'Color'=c('Alpha'='aesAlpha'),
                                'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                                'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                     'Color'=c('Alpha'='aesAlpha'),
                                     'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                     'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     )
        ),

        'bar'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType','Weight'='aesWeight'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType','Weight'='aesWeight'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'line'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType',
                                           'Grouping'='aesGroup'),
                                'Color'=c('Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType',
                                                'Grouping'='aesGroup'),
                                     'Color'=c('Alpha'='aesAlpha')
                     )
        ),

        'area'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'point'=switch(stat,
                      'bin'=list('Coordinates'=c('X'='aesX'),
                                 'Common'=c('Color'='aesColor','Size'='aesSize',
                                            'Shape'='aesShape'),
                                 'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      ),
                      'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                      'Common'=c('Color'='aesColor','Size'='aesSize',
                                                 'Shape'='aesShape'),
                                      'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      )
        ),

        'boxplot'=switch(stat,
                         'boxplot'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                        'Common'=c('Color'='aesColor','Size'='aesSize',
                                                   'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                        'Color'=c('Border Color'='aesBorderColor',
                                                  'Alpha'='aesAlpha')
                         ),
                         'identity'=list('Coordinates'=c('X'='aesX','Y Middle'='aesMiddle',
                                                         'Y Lower'='aesLower','Y Upper'='aesUpper',
                                                         'Y Min'='aesYmin','Y Max'='aesYmax'),
                                         'Common'=c('Color'='aesColor','Size'='aesSize',
                                                    'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                         'Color'=c('Border Color'='aesBorderColor',
                                                   'Alpha'='aesAlpha')
                         )
        )

  )
}

AesChoicesSimpleList <- unique(unlist(lapply(GeomChoices, getAesChoices), use.names=FALSE))

fonttable <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE,
                        text='
Short,Canonical
mono,Courier
sans,Helvetica
serif,Times
,AvantGarde
,Bookman
,Helvetica-Narrow
,NewCenturySchoolbook
,Palatino
,URWGothic
,URWBookman
,NimbusMon
URWHelvetica,NimbusSan
,NimbusSanCond
,CenturySch
,URWPalladio
URWTimes,NimbusRom
')
FontFamilyChoices <- as.vector(t(as.matrix(fonttable)))
FontFamilyChoices <- FontFamilyChoices[FontFamilyChoices!='']

FontFaceChoices <- c("plain","bold","italic","bold.italic")


#' Default http server configuration for libuv hook.
#' 
#' @param routes list. A named list of routes, with a handler
#'    function for each route. The first unnamed route will be used
#'    as the root. If none is provided, just a 404 status will be returned.
#' @examples
#' \dontrun{
#'   http_server(list('/ping' = function(params, query) 'Hello world!',
#'                    function(params, query) 'Invalid route.'))
#' }
http_server <- function(routes) {
  function(req) {
    params <- extract_params_from_request(req)
    query  <- extract_query_from_request(req)
    route  <- determine_route(routes, req$PATH_INFO)
    result <- route(params, query)
    if (is.microserver_response(result)) unclass(result)
    else unclass(microserver_response(result))
  }
}


#' Minimal function for opening a socket and accepting/responding to
#' requests.
#'
#' @param routes list. A named list of routes.
#' @param port integer. The default is 8103.
#' @importFrom httpuv startServer stopServer service
#' @export
run_server <- function(routes, port = 8103) {
  # A list of default HTTUPV callbacks
  httpuv_callbacks <- list(
    onHeaders = function(req) { NULL },
    call = http_server(routes),
    onWSOpen = function(ws) {
      # print('opening websocket')
    }
  )

  server_id <- httpuv::startServer("0.0.0.0", port, httpuv_callbacks)
  on.exit({ httpuv::stopServer(server_id) }, add = TRUE)

  repeat {
    httpuv::service(1)
    Sys.sleep(0.001)
  }
}

library(ggplot2)
load("city-summary.rdata")


ggplot(bigsum, aes(date, price / 1e6)) + 
  geom_line() + 
  facet_wrap(~ city)
ggsave("cities-price.png", width = 8, height = 6, dpi = 128)

# Smoothing ------------------------------------------------------------------

library(mgcv)
smooth <- function(y, x) {
  as.numeric(predict(gam(y ~ s(x), na.action = na.exclude)))
}

bigsum <- ddply(bigsum, .(city), transform,
  price_s = smooth(price, as.numeric(date)))

ggplot(bigsum, aes(date, price_s / 1e6)) + 
  geom_line() + 
  facet_wrap(~ city)
ggsave(file = "cities-smooth.png", width = 8, height = 6, dpi = 128)

index <- function(y, x) {
  y / y[order(x)[1]]
}
bigsum <- ddply(bigsum, .(city), transform,
  price_si = index(price_s, date))

ggplot(bigsum, aes(date, price_si)) + 
  geom_line() + 
  facet_wrap(~ city) 
ggsave(file = "cities-index.png", width = 8, height = 6, dpi = 128)

# Simplify  ---------------------------------------------------------

# Show location of peak and plummet
brentwood <- subset(bigsum, city == "Brentwood")
brentwood_sum <- subset(brentwood, as.character(date) %in% c("2006-02-05", "2008-11-09"))
ggplot(brentwood, aes(date, price_si)) +
  geom_line() + 
  geom_point(data = brentwood_sum, colour = "red", size = 5)
ggsave("brentwood.png", width = 8, height = 6, dpi = 128)

covar <- ddply(bigsum, "city", summarise,
  peak = price_si[date == "2006-02-05"],
  plummet = price_si[date == "2008-11-09"]
)

ggplot(covar, aes(peak, plummet)) + 
  geom_point()
ggsave(file = "cities-2d.png", width = 6, height = 6, dpi = 128)

ggplot(covar, aes(peak, plummet)) + 
  geom_point() +
  geom_text(aes(label = city), size = 4, hjust = -0.05)
ggsave(file = "cities-2d-labelled.png", width = 6, height = 6, dpi = 128)


# Try and explain with covariates from the census data ----------------------

covar$delta <- with(covar, plummet - peak)

census <- read.csv("census-city.csv")
covar <- join(covar, census, by = "city")

base <- ggplot(covar, aes(y = delta)) + geom_point()
base + aes(grads)
ggsave(file = "covar-grads.png", width = 6, height = 6, dpi = 128)
base + aes(income)
ggsave(file = "covar-income.png", width = 6, height = 6, dpi = 128)
base + aes(housesold_size)
ggsave(file = "covar-household.png", width = 6, height = 6, dpi = 128)
#' @title Pobieranie danych o szkołach.
#' @description
#' Funkcja pobiera z bazy dane o szkołach - o ich typie i specyfice, nazwie, adresowe i o lokalizacji.
#' @param lata wektor liczb całkowitych - lata, których mają dotyczyć dane (dla każdej szkoły zwrócone zostaną tylko najświeższe dane w ramach tego okresu)
#' @param typySzkol opcjonalny wektor tekstowy z typami szkół, które mają zostać zwrócone (lub NULL - zwraca informacje o wszystkich szkołach)
#' @param idOke wartość logiczna (domyślnie FALSE) - czy dołączać kody OKE szkół?
#' @param daneAdresowe wartość logiczna (domyślnie FALSE) - czy dołączać nazwę i dane adresowe?
#' @param dolaczPaou wartość logiczna (domyślnie FALSE) - czy dołączać szkoły z danych PAOU?
#' @param zrodloDanychODBC opcjonalnie nazwa źródła danych ODBC, dającego dostęp do bazy (domyślnie "EWD")
#' @return data frame
#' @import RODBCext
#' @export
pobierz_dane_szkol <- function(lata, typySzkol=NULL, idOke=FALSE, daneAdresowe=FALSE, dolaczPaou=FALSE, zrodloDanychODBC="EWD"){
  stopifnot(is.numeric(lata)         , length(lata) > 0,
            is.character(typySzkol) | is.null(typySzkol),
            is.logical(idOke)       , length(idOke) == 1,
            is.logical(daneAdresowe), length(daneAdresowe) == 1,
            is.logical(dolaczPaou)  , length(dolaczPaou) == 1,
            is.character(zrodloDanychODBC), length(zrodloDanychODBC) == 1
  )
  stopifnot(idOke %in% c(TRUE, FALSE), daneAdresowe %in% c(TRUE, FALSE), dolaczPaou %in% c(TRUE, FALSE))
  try(suppressWarnings(Sys.setlocale("LC_ALL", "pl_PL.UTF-8")))

  zapytanie = paste0( "SELECT id_szkoly, typ_szkoly, publiczna, dla_doroslych, specjalna, przyszpitalna,
                        d.rok, ",
                      ifelse(daneAdresowe, "d.nazwa, d.miejscowosc, d.adres, d.pna, d.poczta, ", ""),
                      ifelse(idOke       , "d.id_szkoly_oke, ", ""),
                      "d.wielkosc_miejscowosci, id_gminy + 100*id_powiatu + 10000*id_wojewodztwa AS teryt",
                      ifelse( is.null(typySzkol) | any(typySzkol %in% c("LO","LP","T")) ,", d.matura_miedzynarodowa",""),
                      " FROM szkoly AS sz JOIN szkoly_dane AS d USING (id_szkoly)
                      WHERE sz.id_szkoly > 0 AND d.rok IN (", paste0(rep("?", length(lata)), collapse=", "), ")
                        AND d.rok = (SELECT max(rok) FROM szkoly_dane WHERE id_szkoly = d.id_szkoly AND rok IN (", paste0(lata, collapse=", "), "))",
                      ifelse( is.null(typySzkol), "", paste0(" AND sz.typ_szkoly IN (", paste0(rep("?", length(typySzkol)), collapse=", "), ")") ),
                      ifelse( dolaczPaou, "", " AND sz.paou = FALSE"),
                      " ORDER BY id_szkoly")
  dane = if( is.null(typySzkol)){
    as.list(lata)
  } else{
    data.frame(as.list(lata), as.list(typySzkol), stringsAsFactors=FALSE)
  }

  tryCatch({
      P = odbcConnect(zrodloDanychODBC)
      ret = sqlExecute(P, zapytanie, fetch=TRUE, stringsAsFactors=FALSE, data=dane)
    },
    error = stop,
    finally = odbcClose(P)
  )

  ret$typ_szkoly[ret$typ_szkoly=="TRUE"] = "T"
  if (!("SP" %in% typySzkol)) ret = ret[, names(ret) != "id_szkoly_obut"]

  typyWWynikach = typySzkol %in% ret$typ_szkoly
  if (any(!typyWWynikach)) warning("Nie znaleziono żadnych szkół typu/ów: ", paste0(typySzkol[!typyWWynikach], collapse=", "), ".")

  attributes(ret)$lata = lata
  return( ret )
}
### PREPARE DATA

#' Get word assignments from LDA_GIBBS class (output of topmod.lda.fit). This is similar to the documentsums object that comes as the output of lda.collapsed.gibbs.sampler
#' 
#' Get word assignments from LDA_GIBBS class (output of topmod.lda.fit). This is similar to the documentsums object that comes as the output of lda.collapsed.gibbs.sampler
#' LDA assigns a topic to each unique word in a document. If you also want to take into account how often this word occured, the document term matrix (as used in the input for topmod.lda.fit) must be included in the weight.by.dtm argument.
#' 
#' @param m The output from one of the topicmodeling functions in the topicmodels package (e.g., LDA_GIBBS)
#' @param weight.by.dtm If you want to weight the topic assignment of a word to the number of times the word occured, give the document term matrix for this argument
#' @return A matrix where rows are topics and columns are documents. Values represent the number of times the topic is assigned to a word in this document (essentially this is the same as the documentsums object in the output of lda.collapsed.gibbs.samler)
#' @export
documentsums <- function(m, weight.by.dtm=NULL){
  assignments = data.frame(i=m@wordassignments$i, j=m@wordassignments$j, v=m@wordassignments$v)
  if(!is.null(weight.by.dtm)){
    dtm = weight.by.dtm[m@documents,m@terms]
    dtm = data.frame(i=dtm$i, j=dtm$j, count=dtm$v)
    assignments = merge(assignments, dtm, by=c('i','j'), all.x=T)
    docsums = acast(assignments, v ~ i, value.var='count', fun.aggregate=sum)
  } else docsums = acast(assignments, v ~ i, value.var='j', fun.aggregate=length) 
  docsums
}

#' Estimate a topic model using the lda package
#' 
#' Estimate an LDA topic model using the \code{\link{LDA}} function
#' The parameters other than dtm are simply passed to the sampler but provide a workable default.
#' See the description of that function for more information
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{amcat.dtm.create}})
#' @param K the number of clusters
#' @param num.iterations the number of iterations
#' @param alpha the alpha parameter
#' @param eta the eta parameter
#' @return A fitted LDA model (see \code{\link{LDA}})
#' @export
topmod.lda.fit <- function(dtm, method='Gibbs', K=50, num.iterations=500, alpha=50/K, eta=.01, burnin=250) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]
  m = LDA(dtm, k=K, method=method, control=list(iter=num.iterations, burnin=burnin, alpha=alpha, delta=eta))
  m
}

#' Get the topics per document, optionally merged with 
#' 
#' Return a data frame containing article metadata and topic occurence per document
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
topmod.topics.per.document <- function(topics) {
  ids = as.numeric(m@documents)
  cbind(id=ids, data.frame(posterior(m)$topics))
}

#' Add document meta to LDA output
#' 
#' Add a dataframe containing document meta to the output (a list) of \code{\link{lda.collapsed.gibbs.sampler}}. 
#' 
#' @param m The output of \code{\link{LDA}}   
#' @param meta A data.frame with document meta. Has to contain a vector to match the document.ids
#' @param match.by The name of the vector in meta that matches the document.ids 
#' @return The LDA output appended with document meta
#' @export
topmod.order.meta <- function(m, meta, match.by = 'id'){
  meta[match(m@documents, meta[,match.by]),]
}

### PLOT LDA TOPICS

#' Plot all topics
#' 
#' Write plots for all topics with \code{\link{topmod.plot.topic}} in designated folder
#' 
#' @param m The output of \code{\link{topmod.collapsed.gibbs.sampler}}   
#' @param time_var A vector with time stamps (either numeric or Date class) of the same length and order of the documents (rows) in m$document_sums
#' @param category_var A vector with id values of the same length and order of the documents (rows) in m$document_sums
#' @param path The path for a folder where output will be saved
#' @param date_interval The interval for plotting the values over time. Can be: 'day', 'week', 'month' or 'year'
#' @return Nothing
#' @export
topmod.plot.alltopics <- function(m, time_var, category_var, path, date_interval='day', value='total'){
  for(topic_nr in 1:m@k){
    print(paste('Plotting:',topic_nr))
    fn = paste(path, topic_nr, ".png", sep="")
    if (!is.null(fn)) png(fn, width=1280,height=800)
    topmod.plot.topic(m, topic_nr, time_var, category_var, date_interval, value=value)
    if (!is.null(fn)) dev.off()
  }
  par(mfrow=c(1,1), mar=c(3,3,3,3))
}

#' Plots topic wordcloud, and attention over time and per category
#' 
#' Plots \code{\link{topmod.plot.wordcloud}}, \code{\link{topmod.plot.time}} and \code{\link{topmod.plot.category}}
#' 
#' @param m The output of \code{\link{topmod.collapsed.gibbs.sampler}}
#' @param The index of the topic (1 to K)
#' @param time_var A vector with time stamps (either numeric or Date class) of the same length and order of the documents (rows) in m$document_sums
#' @param category_var A vector with id values of the same length and order of the documents (rows) in m$document_sums
#' @param date_interval The interval for plotting the values over time. Can be: 'day', 'week', 'month' or 'year'
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @return Nothing, just plots
#' @export
topmod.plot.topic <- function(m, topic_nr, time_var, category_var, date_interval='day', pct=F, value='total'){
  par(mar=c(4.5,3,2,1), cex.axis=1.7)
  layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE), widths=c(2.5,1.5), heights=c(1,2))
  topmod.plot.time(m, topic_nr, time_var, date_interval, pct=pct, value=value)
  topmod.plot.wordcloud(m, topic_nr)
  topmod.plot.category(m, topic_nr, category_var, pct=pct, value=value)
  par(mfrow=c(1,1), mar=c(3,3,3,3))
}

#' Change date object to date_interval
#' 
#' Change date object to date_interval
#' 
#' @param time_var A vector of Date values
#' @param date_interval The desired date_interval ('day','week','month', or 'year')
#' @return A vector of Date values
#' @export
topmod.prepare.time.var <- function(time_var, date_interval){
  if(class(time_var) == 'Date'){
    if(date_interval == 'day') time_var = as.Date(format(time_var, '%Y-%m-%d'))
    if(date_interval == 'month') time_var = as.Date(paste(format(time_var, '%Y-%m'),'-01',sep=''))
    if(date_interval == 'week') time_var = as.Date(paste(format(time_var, '%Y-%W'),1), '%Y-%W %u')
    if(date_interval == 'year') time_var = as.Date(paste(format(time_var, '%Y'),'-01-01',sep=''))
  } 
  time_var
}

#' Add empty values for pretty plotting
#' 
#' When plotting a timeline, gaps in date_intervals are ignored. For the attention for topics gaps should be considered as having value 0.   
#' 
#' @param d A data.frame with the columns 'time' (Date) and 'value' (numeric)  
#' @param date_interval The date_interval is required to know what the gaps are
#' @return A data.frame with the columns 'time' (Date) and 'value' (numeric)  
#' @export
topmod.fill.time.gaps <- function(d, date_interval){
  if(class(d$time) == 'numeric'){
    for(t in min(d$time):max(d$time)) 
      if(!t %in% d$time) d = rbind(d, data.frame(time=t, value=0))
  }
  if(class(d$time) == 'Date'){
    date_sequence = seq.Date(from=min(d$time), to=max(d$time), by=date_interval)
    for(i in 1:length(date_sequence)){
      t = date_sequence[i]
      if(!t %in% d$time) d = rbind(d, data.frame(time=t, value=0))
    }
  }
  d[order(d$time),]
}

#' Prepares the topic values per document for plotting 
#' 
#' Prepares the topic values per document for plotting
#' 
#' @param m The output of \code{\link{LDA}}
#' @param break_var A break vector to aggregate topic values per document
#' @param The index of the topic (1 to K)
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @return The aggregated/transformed topic values
#' @export
topmod.prepare.plot.values <- function(m, break_var, topic_nr, pct=F, value='total', filter=NULL){
  docsums = documentsums(m)
  hits = docsums[topic_nr,]
  d = aggregate(hits, by=list(break_var=break_var), FUN='sum') 
  if(value == 'relative'){
    total_hits = colSums(docsums)  
    totals = aggregate(total_hits, by=list(break_var=break_var), FUN='sum')
    d$x = d$x / totals$x
  }
  if(pct == T) d$x = d$x / sum(d$x)
  d
}


#' Plots topic values over time
#' 
#' Plots the attention for a topic over time
#' 
#' @param m The output of \code{\link{LDA}}
#' @param The index of the topic (1 to K)
#' @param time_var A vector with time stamps (either numeric or Date class) of the same length and order of the documents (rows) in m$document_sums
#' @param date_interval The interval for plotting the values over time. Can be: 'day', 'week', 'month' or 'year'
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @param return.values Logical. If true, data that is plotted is returned as a data.frame
#' @return data.frame for plotted values
#' @export
topmod.plot.time <- function(m, topic_nr, time_var, date_interval='day', pct=F, value='total', return.values=F){
  par(mar=c(3,3,3,1))
  time_var = topmod.prepare.time.var(time_var, date_interval)  
  d = topmod.prepare.plot.values(m, break_var=time_var, topic_nr=topic_nr, pct=pct, value=value)
  colnames(d) = c('time','value')
  d = topmod.fill.time.gaps(d, date_interval)
  plot(d$time, d$value, type='l', xlab='', main='', ylab='', xlim=c(min(d$time), max(d$time)), ylim=c(0, max(d$value)), bty='L', lwd=5, col='darkgrey')
  par(mar=c(3,3,3,3))
  if(return.values==T) d
}

#' Plots topic values per category
#' 
#' Plots the attention for a topic per category
#' 
#' @param m The output of \code{\link{LDA}}
#' @param The index of the topic (1 to K)
#' @param category_var A vector with id values of the same length and order of the documents (rows) in m$document_sums
#' @param pct Show topic values as percentages
#' @param value Show topic values as 'total', or as 'relative' to the attention for other topics
#' @param return.values Logical. If true, data that is plotted is returned as a data.frame
#' @return data.frame for plotted values
#' @export
topmod.plot.category <- function(m, topic_nr, category_var, pct=F, value='total', return.values=F){
  par(mar=c(15,3,1,2))
  d = topmod.prepare.plot.values(m, break_var=category_var, topic_nr=topic_nr, pct=pct, value=value)
  colnames(d) = c('category','value')
  barplot(as.matrix(t(d[,c('value')])), main='', beside=TRUE,horiz=FALSE,
          density=NA,
          col='darkgrey',
          xlab='',
          ylab="",
          axes=T, names.arg=d$category, cex.names=0.8, cex.axis=0.8, adj=1, las=2)
  par(mar=c(3,3,3,3))
  if(return.values==T) d
}

#' Plot wordcloud for LDA topic
#' 
#' Plots a wordcloud of the top words per topic
#' 
#' @param m The output of \code{\link{LDA}}
#' @param topic_nr The index of the topic (1 to K)
#' @return Nothing, just plots
#' @export
topmod.plot.wordcloud <- function(m, topic_nr){
  x = posterior(m)$terms[topic_nr,]
  x = sort(x, decreasing=T)[1:100]
  x = x[!is.na(x)]
  names = sub("/.*", "", names(x))
  freqs = x
  pal <- brewer.pal(6,"YlGnBu")
  wordcloud(names, freqs, scale=c(6,.5), min.freq=1, max.words=Inf, random.order=FALSE, rot.per=.15, colors=pal)
}


#' Cast data.frame to sparse matrix
#' 
#' Create a sparse matrix from matching vectors of row indices, column indices and values
#' 
#' @param rows a vector of row indices: [i,]
#' @param columns a vector of column indices: [,j]
#' @param values a vector of the values for each (non-zero) cell: [i,j] = value
#' @return a sparse matrix of the dgTMatrix class (\code{\link{Matrix}} package) 
#' @export
cast.sparse.matrix <- function(rows, columns, values=NULL) {
  if(is.null(values)) values = rep(1, length(rows))
  d = data.frame(rows=rows, columns=columns, values=values)
  if(nrow(d) > nrow(unique(d[,c('rows','columns')]))){
    message('(Duplicate row-column matches occured. Values of duplicates are added up)')
    d = aggregate(values ~ rows + columns, d, FUN='sum')
  }
  unit_index = unique(d$rows)
  char_index = unique(d$columns)
  sm = spMatrix(nrow=length(unit_index), ncol=length(char_index),
                match(d$rows, unit_index), match(d$columns, char_index), d$values)
  rownames(sm) = unit_index
  colnames(sm) = char_index
  sm
}

#' Create a document term matrix from a list of tokens
#' 
#' Create a \code{\link{DocumentTermMatrix}} from a list of document ids, terms, and frequencies. 
#' 
#' @param documents a vector of document names/ids
#' @param terms a vector of words of the same length as documents
#' @param freqs a vector of the frequency a a term in a document
#' @return a document-term matrix  \code{\link{DocumentTermMatrix}}
#' @export
dtm.create <- function(documents, terms, freqs=rep(1, length(documents))) {
  # remove NA terms
  d = data.frame(ids=documents, terms=terms, freqs=freqs)
  if (sum(is.na(d$terms)) > 0) {
    warning("Removing ", sum(is.na(d$terms)), "rows with missing term names")
    d = d[!is.na(d$terms), ]
  }
  sparsemat = cast.sparse.matrix(rows=d$ids, columns=d$terms, values=d$freqs)
  as.DocumentTermMatrix(sparsemat, weighting=weightTf)
}

#' Compute some useful corpus statistics for a dtm
#' 
#' Compute a number of useful statistics for filtering words: term frequency, idf, etc.
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
term.statistics <- function(dtm) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]    # get rid of empty rows/columns
  vocabulary = colnames(dtm)
  data.frame(term = vocabulary,
             characters = nchar(vocabulary),
             number = grepl("[0-9]", vocabulary),
             nonalpha = grepl("\\W", vocabulary),
             termfreq = col_sums(dtm),
             docfreq = col_sums(dtm > 0),
             reldocfreq = col_sums(dtm > 0) / nDocs(dtm),
             tfidf = tapply(dtm$v/row_sums(dtm)[dtm$i], dtm$j, mean) * log2(nDocs(dtm)/col_sums(dtm > 0)))
}

#' Compute the chi^2 statistic for a 2x2 crosstab containing the values
#' [[a, b], [c, d]]
chi2 <- function(a,b,c,d) {
  ooe <- function(o, e) {(o-e)*(o-e) / e}
  tot = 0.0 + a+b+c+d
  a = as.numeric(a)
  b = as.numeric(b)
  c = as.numeric(c)
  d = as.numeric(d)
  (ooe(a, (a+c)*(a+b)/tot)
   +  ooe(b, (b+d)*(a+b)/tot)
   +  ooe(c, (a+c)*(c+d)/tot)
   +  ooe(d, (d+b)*(c+d)/tot))
}

#' Compare two corpora
#' 
#' Compare the term use in corpus dtm with a refernece corpus dtm.ref, returning relative frequencies
#' and overrepresentation using various measures
#' 
#' @param dtm.x the main document-term matrix
#' @param dtm.y the 'reference' document-term matrix
#' @param smooth the smoothing parameter for computing overrepresentation
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
corpora.compare <- function(dtm.x, dtm.y, smooth=.001) {
  freqs = term.statistics(dtm.x)[, c("term", "termfreq")]
  freqs.rel = term.statistics(dtm.y)[, c("term", "termfreq")]
  f = merge(freqs, freqs.rel, all=T, by="term")    
  f[is.na(f)] = 0
  f$relfreq.x = f$termfreq.x / sum(freqs$termfreq)
  f$relfreq.y = f$termfreq.y / sum(freqs.rel$termfreq)
  f$over = (f$relfreq.x + smooth) / (f$relfreq.y + smooth)
  f$chi = chi2(f$termfreq.x, f$termfreq.y, sum(f$termfreq.x) - f$termfreq.x, sum(f$termfreq.y) - f$termfreq.y)
  f
}

#' Plot a word cloud from a dtm
#' 
#' Compute the term frequencies for the dtm and plot a word cloud with the top n topics
#' 
#' @param dtm the document-term matrix
#' @param nterms the amount of words to plot (default 100)
#' @param freq.fun if given, will be applied to the frequenies (e.g. sqrt)
#' @param scale the scale to plot (see wordcloud::wordcloud)
#' @param min.freq the minimum frquency to include (see wordcloud::wordcloud)
#' @param rot.per the percentage of vertical words (see wordcloud::wordcloud)
#' @param pal the colour model, see RColorBrewer
#' @export
dtm.wordcloud <- function(dtm, nterms=100, freq.fun=NULL, scale=c(6, .5), min.freq=1, rot.per=.15, pal=brewer.pal(6,"YlGnBu")) {
  terms = term.statistics(dtm)
  freqs = terms$termfreq[1:nterms]
  if (!is.null(freq.fun)) freqs = freq.fun(freqs)
  wordcloud(terms$term[1:nterms], freqs, 
          scale=scale, min.freq=min.freq, max.words=Inf, random.order=FALSE, 
          rot.per=rot.per, colors=pal)
}
#' Cast data.frame to sparse matrix
#' 
#' Create a sparse matrix from matching vectors of row indices, column indices and values
#' 
#' @param rows a vector of row indices: [i,]
#' @param columns a vector of column indices: [,j]
#' @param values a vector of the values for each (non-zero) cell: [i,j] = value
#' @return a sparse matrix of the dgTMatrix class (\code{\link{Matrix}} package) 
#' @export
cast.sparse.matrix <- function(rows, columns, values=NULL) {
  if(is.null(values)) values = rep(1, length(rows))
  d = data.frame(rows=rows, columns=columns, values=values)
  if(nrow(d) > nrow(unique(d[,c('rows','columns')]))){
    message('(Duplicate row-column matches occured. Values of duplicates are added up)')
    d = aggregate(values ~ rows + columns, d, FUN='sum')
  }
  unit_index = unique(d$rows)
  char_index = unique(d$columns)
  sm = spMatrix(nrow=length(unit_index), ncol=length(char_index),
                match(d$rows, unit_index), match(d$columns, char_index), d$values)
  rownames(sm) = unit_index
  colnames(sm) = char_index
  sm
}

#' Create a document term matrix from a list of tokens
#' 
#' Create a \code{\link{DocumentTermMatrix}} from a list of document ids, terms, and frequencies. 
#' 
#' @param documents a vector of document names/ids
#' @param terms a vector of words of the same length as documents
#' @param freqs a vector of the frequency a a term in a document
#' @return a document-term matrix  \code{\link{DocumentTermMatrix}}
#' @export
dtm.create <- function(documents, terms, freqs) {
  # remove NA terms
  d = data.frame(ids=documents, terms=terms, freqs=freqs)
  if (sum(is.na(d$terms)) > 0) {
    warning("Removing ", sum(is.na(d$terms)), "rows with missing term names")
    d = d[!is.na(d$terms), ]
  }
  sparsemat = cast.sparse.matrix(rows=d$ids, columns=d$terms, values=d$freqs)
  as.DocumentTermMatrix(sparsemat, weighting=weightTf)
}

#' Compute some useful corpus statistics for a dtm
#' 
#' Compute a number of useful statistics for filtering words: term frequency, idf, etc.
#' 
#' @param dtm a document term matrix (e.g. the output of \code{\link{dtm.create}})
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
term.statistics <- function(dtm) {
  dtm = dtm[row_sums(dtm) > 0,col_sums(dtm) > 0]    # get rid of empty rows/columns
  vocabulary = colnames(dtm)
  data.frame(term = vocabulary,
             characters = nchar(vocabulary),
             number = grepl("[0-9]", vocabulary),
             nonalpha = grepl("\\W", vocabulary),
             termfreq = col_sums(dtm),
             docfreq = col_sums(dtm > 0),
             reldocfreq = col_sums(dtm > 0) / nDocs(dtm),
             tfidf = tapply(dtm$v/row_sums(dtm)[dtm$i], dtm$j, mean) * log2(nDocs(dtm)/col_sums(dtm > 0)))
}

#' Compute the chi^2 statistic for a 2x2 crosstab containing the values
#' [[a, b], [c, d]]
chi2 <- function(a,b,c,d) {
  ooe <- function(o, e) {(o-e)*(o-e) / e}
  tot = 0.0 + a+b+c+d
  a = as.numeric(a)
  b = as.numeric(b)
  c = as.numeric(c)
  d = as.numeric(d)
  (ooe(a, (a+c)*(a+b)/tot)
   +  ooe(b, (b+d)*(a+b)/tot)
   +  ooe(c, (a+c)*(c+d)/tot)
   +  ooe(d, (d+b)*(c+d)/tot))
}

#' Compare two corpora
#' 
#' Compare the term use in corpus dtm with a refernece corpus dtm.ref, returning relative frequencies
#' and overrepresentation using various measures
#' 
#' @param dtm.x the main document-term matrix
#' @param dtm.y the 'reference' document-term matrix
#' @param smooth the smoothing parameter for computing overrepresentation
#' @return A data frame with rows corresponding to the terms in dtm and the statistics in the columns
#' @export
corpora.compare <- function(dtm.x, dtm.y, smooth=.001) {
  freqs = term.statistics(dtm.x)[, c("term", "termfreq")]
  freqs.rel = term.statistics(dtm.y)[, c("term", "termfreq")]
  f = merge(freqs, freqs.rel, all=T, by="term")    
  f[is.na(f)] = 0
  f$relfreq.x = f$termfreq.x / sum(freqs$termfreq)
  f$relfreq.y = f$termfreq.y / sum(freqs.rel$termfreq)
  f$over = (f$relfreq.x + smooth) / (f$relfreq.y + smooth)
  f$chi = chi2(f$termfreq.x, f$termfreq.y, sum(f$termfreq.x) - f$termfreq.x, sum(f$termfreq.y) - f$termfreq.y)
  f
}
REBOL [
	Title:	 "Red/System ELF format emitter"
	Author:  "Andreas Bolka, Nenad Rakocevic"
	File:	 %ELF.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Andreas Bolka, Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; NOTE: all "offsets" are offsets into the file (as stored on disk),
;; all "addresses" are virtual addresses (of the process in memory).

context [
	defs: compose [
		;; Required by the linker.
		extensions [
			exe %""
			obj %.o
			lib %.a
			dll %.so
		]

		;; Target-specific Defaults (job-overridable)

		base-address	(to-integer #{08048000})
		page-size		4096

		;; ELF Constants

		elfclass32		1			;; 32-bit object

		elfdata2lsb		1			;; 2's-complement, little endian

		ev-current		1			;; the "current" version we're adhering to

		et-exec			2			;; executable file
		et-dyn			3			;; shared object file

		em-386			3			;; intel 80386
		em-arm			40			;; ARM

		pt-load			1			;; loadable segment
		pt-dynamic		2			;; dynamic linking information
		pt-interp		3			;; dynamic linker ("interpreter") path name
		pt-phdr			6			;; program header table

		pf-x			1			;; executable segment
		pf-w			2			;; writable segment
		pf-r			4			;; readable wegment

		shn-undef		0			;; undefined section

		sht-null		0			;; inactive section header
		sht-progbits	1			;; program-specific data (w/ file extent)
		sht-symtab		2			;; symbol table (for link editing)
		sht-strtab		3			;; string table
		sht-hash		5			;; symbol hash table
		sht-dynamic		6			;; dynamic linking
		sht-nobits		8			;; program-specific data (w/o file extend)
		sht-rel			9			;; relocations (w/o addends)
		sht-dynsym		11			;; symbol table (dynamic linking)

		shf-write		1			;; dynamically writable section
		shf-alloc		2			;; dynamically allocated section
		shf-execinstr	4			;; dynamically executable section

		stn-undef		0			;; end of a hash chain (undef symtab nr)

		stb-global		1			;; global symbol

		stt-object		1			;; symbol is a data object
		stt-func		2			;; symbol is a code object

		stv-default		0			;; default symbol visibility

		dt-null			0			;; marks the end of the _DYNAMIC array
		dt-needed		1			;; strtable offset of the name of a library
		dt-hash			4			;; address of the symbol hash table
		dt-strtab		5			;; address of the string table
		dt-symtab		6			;; address of the symbol table
		dt-strsz		10			;; total size of the string table (in bytes)
		dt-syment		11			;; size of one symbol table entry (in bytes)
		dt-init			12			;; address of the initialization function
		dt-fini			13			;; address of the termination function
		dt-rel			17			;; address of the relocation table
		dt-relsz		18			;; total size of the relocation table
		dt-relent		19			;; size of one reloc table entry (in bytes)

		r-386-32		1			;; direct 32-bit relocation
		r-386-copy		5			;; copy symbol at runtime

		r-arm-abs32		2			;; direct 32-bit relocation

		stabs-n-undf	0			;; undefined stabs entry
		stabs-n-fun		36			;; function name
		stabs-n-so		100			;; source file name
	]

	;; ELF Structures

	elf-header: make-struct [		;; (Elf32_Ehdr)
		ident-mag0		[char!]		;; 0x7F (EI_MAG0)
		ident-mag1		[char!]		;; "E" (EI_MAG1)
		ident-mag2		[char!]		;; "L" (EI_MAG2)
		ident-mag3		[char!]		;; "F" (EI_MAG3)
		ident-class		[char!]		;; file class
		ident-data		[char!]		;; data encoding
		ident-version	[char!]		;; file version
		ident-osabi		[char!]
		ident-pad1		[integer!]
		ident-pad2		[integer!]
		type			[short]
		machine			[short]
		version			[integer!]
		entry			[integer!]	;; virtual address of program entry point
		phoff			[integer!]	;; file offset to phdr table
		shoff			[integer!]	;; file offset to shdr table
		flags			[integer!]
		ehsize			[short]		;; size-of elf-header
		phentsize		[short]		;; size-of program-header
		phnum			[short]		;; num of "segments" (entries in phdr tab)
		shentsize		[short]		;; size-of section-header
		shnum			[short]		;; num of "sections" (entries in shdr tab)
		shstrndx		[short]		;; shdr table index of .shstrtab section
	] none

	program-header: make-struct [	;; (Elf32_Phdr)
		type			[integer!]
		offset			[integer!]
		vaddr			[integer!]
		paddr			[integer!]
		filesz			[integer!]
		memsz			[integer!]
		flags			[integer!]
		align			[integer!]
	] none

	section-header: make-struct [	;; (Elf32_Shdr)
		name			[integer!]	;; index into .shstrtab
		type			[integer!]
		flags			[integer!]
		addr			[integer!]
		offset			[integer!]
		size			[integer!]
		link			[integer!]
		info			[integer!]
		addralign		[integer!]
		entsize			[integer!]
	] none

	elf-dynamic: make-struct [		;; (Elf32_Dyn)
		tag				[integer!]
		val				[integer!]
	] none

	elf-symbol: make-struct [		;; (Elf32_Sym)
		name			[integer!]	;; symbol strtab index (zero: unnamed sym)
		value			[integer!]	;; absolute value, address, ...
		size			[integer!]	;; associated symbol size (if any)
		info			[char!]		;; symbol type and binding attributes
		other			[char!]		;; symbol visibility
		shndx			[short]		;; section this symbol is associated with
	] none

	elf-relocation: make-struct [	;; (Elf32_Rel)
		offset			[integer!]
		info-sym		[char!]
		info-type		[char!]
		info-unused		[short]
	] none

	stab-entry: make-struct [
		strx			[integer!]
		type			[char!]
		other			[char!]
		desc			[short]
		value			[integer!]
	] none

	machine-word: make-struct [
		value			[integer!]
	] none

	;; ------------------------------------------------------------------------

	;; The macro structure of our generated ELF binaries.
	default-structure: [
		;; Standard metadata:		[type		flags				align]
		segment "rx"				[load		[r x]				page] [
			struct "ehdr"
			segment "phdr"			[phdr	  	[r]					byte]
			segment "interp"		[interp	  	[r]					byte] [
				section ".interp"	[progbits 	[alloc]				byte]
			]
			section ".hash"			[hash	  	[alloc]				word]
			section ".dynstr"		[strtab	  	[alloc]				byte]
			section ".dynsym"		[dynsym	  	[alloc]				word]
			section ".rel.text"		[rel	  	[alloc]				word]
			section ".text"			[progbits 	[alloc execinstr]	word]
		]

		segment "rw"				[load	  	[r w]				page] [
			section ".data"			[progbits 	[write alloc]		word]
			section ".data.rel.ro"	[progbits 	[write alloc]		word]
			segment "dynamic"		[dynamic  	[r w]				word] [
				section ".dynamic"	[dynamic  	[write alloc]		word]
			]
		]

		section ".stab"				[progbits	[]					word]
		section ".stabstr"			[strtab		[]					byte]

		section ".shstrtab"			[strtab	  	[]					byte]
		struct "shdr"
	]

	;; The main entry point called from the linker.
	build: func [
		job [object!]
		/local
			base-address dynamic-linker
			libraries imports exports natives
			structure segments sections commands layout
			data-size
			get-address get-offset get-size get-meta get-data set-data
			relro-offset
	] [
		base-address: case [
			job/type = 'dll [0]
			true			[any [job/base-address defs/base-address]]
		]
		dynamic-linker: any [job/dynamic-linker ""]

		set [libraries imports] collect-import-names job
		exports: collect-exports job
		natives: collect-natives job

		structure: copy default-structure

		if empty? dynamic-linker [
			remove-elements structure [".interp"]
		]

		if empty? imports [
			remove-elements structure [
				".interp"
			]
		]

		if all [empty? imports empty? exports] [
			remove-elements structure [
				".hash"
				".dynstr"
				".dynsym"
				".dynamic"
			]
		]

		unless job/debug? [
			remove-elements structure [".stab" ".stabstr"]
		]

		data-size: size-of job/sections/data/2
		if job/debug? [
			data-size: data-size + linker/get-debug-lines-size job
		]
		if zero? data-size [
			remove-elements structure [".data"]
		]
		
		dynamic-size: calc-dynamic-size job/type job/symbols

		segments: collect-structure-names structure 'segment
		sections: collect-structure-names structure 'section

		commands: compose/deep [
			"rx"			skip (base-address)
			"rw"			skip (defs/page-size)

			".hash"			meta [link ".dynsym"]
			".dynsym"		meta [link ".dynstr" info ".interp"]
			".rel.text"		meta [link ".dynsym" info ".text"]
			".dynamic"		meta [link ".dynstr"]
			".stab"			meta [link ".stabstr"]

			"ehdr"			size elf-header
			"phdr"			size [program-header	length? segments]
			".hash"			size [machine-word		2 + 2 + (length? imports) + ((length? exports) / 2)]
			".dynsym"		size [elf-symbol		1 + (length? imports) + ((length? exports) / 2)]
			".rel.text"		size [elf-relocation	length? imports]
			".data"			size (data-size)
			".data.rel.ro"	size [machine-word		length? imports]
			".dynamic"		size [elf-dynamic		dynamic-size + length? libraries]
			".stab"			size [stab-entry		2 + ((length? natives) / 2)]
			"shdr"			size [section-header	length? sections]

			".interp"		data (to-c-string dynamic-linker)
			".dynstr"		data (to-elf-strtab compose [(libraries) (imports) (extract exports 2)])
			".text"			data (job/sections/code/2)
			".stabstr"		data (to-elf-strtab join ["%_"] extract natives 2)
			".shstrtab"		data (to-elf-strtab sections)
		]

		layout: layout-binary structure commands

		;; In the following section, we try to minimize the global state passed
		;; around. Instead of just passing LAYOUT to all build-* functions, we
		;; try to pass the minimum amount of information necessary. This makes
		;; the dependencies between those builders more explicit.

		get-address: func [name] [layout/:name/address]
		get-offset: func [name] [layout/:name/offset]
		get-size: func [name] [layout/:name/size]
		get-meta: func [name] [layout/:name/meta]
		get-data: func [name] [layout/:name/data]

		has-element: func [name] [found? find/skip layout name 2]

		set-data: func [name builder] [
			if has-element name [
				layout/:name/data: do builder
			]
		]

		set-data "ehdr" [
			build-ehdr
				job/os
				job/target
				job/type
				get-offset "phdr"
				get-offset "shdr"
				get-address ".text"
				segments
				sections
		]

		set-data "phdr"
			[build-phdr map-each segment segments [layout/:segment]]

		set-data ".hash"
			[build-hash compose [(imports) (extract exports 2)]]

		set-data ".dynsym" [
			build-dynsym
				imports
				exports
				get-data ".dynstr"
				get-address ".text"
				section-index-of sections ".text"
				get-address ".data"
				section-index-of sections ".data"
		]

		set-data ".rel.text"
			[build-reltext job/target imports get-address ".data.rel.ro"]

		set-data ".data" [
			if job/debug? [
				linker/build-debug-lines
					job
					get-address ".text"
					machine-word
			]
			job/sections/data/2
		]

		set-data ".data.rel.ro"
			[build-relro imports]

		set-data ".dynamic" [
			build-dynamic
				job/type
				job/symbols
				get-address ".text"
				get-address ".hash"
				get-address ".dynstr" get-size ".dynstr"
				get-address ".dynsym"
				get-address ".rel.text" get-size ".rel.text"
				get-data ".dynstr"
				libraries
		]

		set-data ".stab" [
			build-stab
				get-address ".text"
				get-data ".stabstr"
				natives
		]

		set-data "shdr" [
			build-shdr
				flatten map-each name sections [reduce [name layout/:name]]
				commands
				get-data ".shstrtab"
		]

		;; Resolve data references.
		if has-element ".data" [
			linker/resolve-symbol-refs
				job
				get-data ".text"
				get-data ".data"
				get-address ".text"
				get-address ".data"
				machine-word
		]

		;; Resolve import (library function) references.
		if has-element ".data.rel.ro" [
			relro-offset: get-address ".data.rel.ro"
			if job/PIC? [relro-offset: relro-offset - get-address ".text"]
			resolve-import-refs
				job
				imports
				get-data ".text"
				relro-offset
		]

		;; Concatenate the layout data into the output binary.
		job/buffer: copy #{}
		foreach [name values] layout [
			append job/buffer serialize-data values/data			;; Data
			append job/buffer rejoin array/initial values/pad #{00} ;; Padding
		]
		job/buffer
	]

	;; -- ELF structure builders --

	build-ehdr: func [
		target-os [word!]
		target-arch [word!]
		target-type [word!]
		phdr-offset [integer!]
		shdr-offset [integer!]
		text-address [integer!]
		segment-names [block!]
		section-names [block!]
		/local eh
	] [
		eh: make-struct elf-header none
		eh/ident-mag0:		#"^(7F)"
		eh/ident-mag1:		#"E"
		eh/ident-mag2:		#"L"
		eh/ident-mag3:		#"F"
		eh/ident-class:		defs/elfclass32
		eh/ident-data:		defs/elfdata2lsb
		eh/ident-version:	defs/ev-current
		eh/version:			defs/ev-current
		eh/entry:			text-address
		eh/phoff:			phdr-offset
		eh/shoff:			shdr-offset
		eh/flags:			0
		eh/ehsize:			size-of elf-header
		eh/phentsize:		size-of program-header
		eh/phnum:			length? segment-names
		eh/shentsize:		size-of section-header
		eh/shnum:			1 + length? section-names
		eh/shstrndx:		index? find section-names ".shstrtab"

		;; Target-specific header fields.

		eh/ident-osabi: switch/default target-os [
			FreeBSD      [9]
			Linux        [3]
		]	             [0]

		eh/type: select reduce [
			'exe defs/et-exec
			'dll defs/et-dyn
		] target-type

		switch target-arch [
			ia-32	[
				eh/machine: defs/em-386
			]
			arm		[
				eh/machine: defs/em-arm
				eh/flags: to-integer #{04000000} ;; EABI v4
			]
		]

		eh
	]

	build-phdr: func [segments [block!] /local ph] [
		map-each segment segments [
			ph: make-struct program-header none
			ph/type:		lookup-def "pt-" segment/meta/type
			ph/offset:		segment/offset
			ph/vaddr:		segment/address
			ph/paddr:		segment/address
			ph/filesz:		segment/size
			ph/memsz:		segment/size
			ph/flags:		lookup-flags "pf-" segment/meta/flags
			ph/align:		lookup-align segment/meta/align
			ph
		]
	]

	build-hash: func [symbols [block!] /local nsymbols] [
		;; @@ Document lookup algorithm?
		nsymbols: length? symbols
		map-each value collect [
			;; nbucket
			keep 1
			;; nchain
			keep nsymbols + 1
			;; bucket[0] = 1 if nsymbols>0 else 0
			keep min nsymbols 1
			;; chain[0] = undef
			keep defs/stn-undef
			;; chain[i:1..nsymbols-1] = i+1
			for i 2 nsymbols 1 [
				keep i
			]
			;; chain[nsymbols] = undef if nsymbols>0 (else omit)
			if nsymbols > 0 [
				keep defs/stn-undef
			]
		] [
			make-struct machine-word reduce [value]
		]
	]

	build-dynsym: func [
		imports [block!]
		exports [block!]
		dynstr [binary!]
		text-address [integer!]
		text-index [integer!]
		data-address [integer!]
		data-index [integer!]
		/local result entry export-base export-type export-index
	] [
		result: copy []

		;; Symbol #0: undefined symbol
		append result make-struct elf-symbol none

		foreach symbol imports [
			entry: make-struct elf-symbol none
			entry/name: strtab-index-of dynstr symbol
			entry/value: 0 ;; Unknown, for imported symbols.
			entry/info: to-elf-symbol-info defs/stb-global defs/stt-func
			entry/other: defs/stv-default
			entry/shndx: defs/shn-undef
			append result entry
		]

		foreach [symbol meta] exports [
			set [export-base export-type export-index] case [
				meta/type = 'global [
					reduce [data-address defs/stt-object data-index]
				]
				true [
					reduce [text-address defs/stt-func text-index]
				]
			]
			entry: make-struct elf-symbol none
			entry/name: strtab-index-of dynstr symbol
			entry/value: export-base + meta/offset
			entry/info: to-elf-symbol-info defs/stb-global export-type
			entry/size: meta/size
			entry/other: defs/stv-default
			entry/shndx: export-index
			append result entry
		]

		result
	]

	build-reltext: func [
		target-arch [word!]
		symbols [block!]
		relro-address [integer!]
		/local rel-type result entry
	] [
		rel-type: select reduce [
			'ia-32 defs/r-386-32
			'arm defs/r-arm-abs32
		] target-arch
		result: copy []
		repeat i length? symbols [ ;; 1..n, 0 is undef
			entry: make-struct elf-relocation none
			entry/offset: rel-address-of/index relro-address (i - 1)
			entry/info-sym: rel-type
			entry/info-type: i
			append result entry
		]
		result
	]

	build-relro: func [symbols [block!]] [
		;; @@ Use NOBITS section (filesize 0, memsize n) instead?
		array/initial length? symbols make-struct machine-word none
	]

	build-dynamic: func [
		job-type [word!]
		symbols [hash!]
		text-address [integer!]
		hash-address [integer!]
		dynstr-address [integer!]
		dynstr-size [integer!]
		dynsym-address [integer!]
		reltext-address [integer!]
		reltext-size [integer!]
		dynstr [binary!]
		libraries [block!]
		/local entries spec
	] [
		entries: copy []

		;; One DT_NEEDED for each dynamic library:
		foreach library libraries [
			repend entries ['needed strtab-index-of dynstr library]
		]

		if job-type = 'dll [
			if spec: select symbols '***-dll-entry-point [
				repend entries ['init text-address + spec/2 - 1]
			]
			if spec: select symbols 'on-unload [
				repend entries ['fini text-address + spec/2 - 1]
			]
		]
				
		;; Static _DYNAMIC entries:
		append entries reduce [
			'hash	hash-address
			'strtab	dynstr-address
			'symtab	dynsym-address
			'strsz	dynstr-size
			'syment	size-of elf-symbol
			'rel	reltext-address
			'relsz	reltext-size
			'relent	size-of elf-relocation
			'null	0
		]

		map-each [tag value] entries [
			make-struct elf-dynamic reduce [lookup-def "dt-" tag value]
		]
	]

	build-stab: func [
		text-address [integer!] stabstr [binary!] natives [block!]
		/local r s
	] [
		collect [
			;; The first synthetic entry (required) holds the number of
			;; non-synthetic entries as well as the size of the string table.
			s: make-struct stab-entry none
			s/type: defs/stabs-n-undf
			s/desc: 1 + ((length? natives) / 2)
			s/value: size-of stabstr
			keep s

			;; One source file stab (N_SO) is required before any other stabs.
			s: make-struct stab-entry none
			s/type: defs/stabs-n-so
			s/value: text-address
			s/strx: 1 ;; @@ Use a real source name (instead of "%_")
			keep s

			foreach [name offset] natives [
				s: make-struct stab-entry none
				s/type: defs/stabs-n-fun
				s/value: text-address + offset
				s/strx: strtab-index-of stabstr name
				keep s
			]
		]
	]

	build-shdr: func [
		sections [block!] commands [block!] shstrtab [binary!]
		/local names sh name section
	] [
		names: extract sections 2
		join reduce [
			make-struct section-header none
		] map-each [name section] sections [
			sh: make-struct section-header none
			sh/name:		strtab-index-of shstrtab name
			sh/type:		lookup-def "sht-" section/meta/type
			sh/flags:		lookup-flags "shf-" section/meta/flags
			sh/addr:		section/address
			sh/offset:		section/offset
			sh/size:		section/size
			sh/link:		section-index-of names select section/meta 'link
			sh/info:		section-index-of names select section/meta 'info
			sh/addralign:	lookup-align section/meta/align
			sh/entsize:		find-entry-size commands name
			sh
		]
	]

	;; -- Job helpers --

	collect-import-names: func [job [object!] /local libraries symbols] [
		libraries: copy []
		symbols: copy []
		foreach [libname libuses] job/sections/import/3 [
			append libraries libname
			foreach [symbol callsites] libuses [
				append symbols symbol
			]
		]
		reduce [libraries symbols]
	]

	collect-exports: func [
		{Collect a list of exported objects: symbol, type, offset and size. As
		the object size is not yet stored in the symbol or exports table, we
		have to compute it here.}
		job [object!]
		/local current-tail code-tail data-tail symbol-offset symbol-size
	] [
		if  not find job/sections 'export [return make block! 0]

		code-tail: length? job/sections/code/2
		data-tail: length? job/sections/data/2
		collect [
			foreach [meta symbol] reverse copy job/symbols [
				catch [
					case [
						find [import native-ref] meta/1 [
							throw 'continue
						]
						'global = meta/1 [
							symbol-offset: meta/2
							symbol-size: data-tail - symbol-offset
							data-tail: symbol-offset
						]
						'native = meta/1 [
							;; Code symbols have 1-based offsets, data symbols
							;; have 0-based offsets in job/symbols ...
							symbol-offset: meta/2 - 1
							symbol-size: code-tail - symbol-offset
							code-tail: symbol-offset
						]
						true [
							make error! reform ["Unhandled symbol type:" meta/1]
						]
					]
					if find job/sections/export/3 symbol [
						keep compose/deep [
							(form symbol) [
								type (meta/1)
								offset (symbol-offset)
								size (symbol-size)
							]
						]
					]
				]
			]
		]
	]

	collect-natives: func [job [object!]] [
		collect [
			foreach [name meta] job/symbols [
				if meta/1 = 'native [
					keep reduce [(join name ":F") (meta/2 - 1)]
				]
			]
		]
	]

	resolve-import-refs: func [
		job [object!] symbols [block!] code [binary!] relro-offset [integer!]
		/local rel
	] [
		rel: make-struct machine-word none
		foreach [libname libimports] job/sections/import/3 [
			foreach [symbol callsites] libimports [
				rel/value: rel-address-of/symbol relro-offset symbols symbol
				foreach callsite callsites [
					change/part at code callsite serialize-data rel size-of rel
				]
			]
		]
	]

	;; -- File structure/file commands helpers --

	remove-elements: func [structure elements /local begin mark name children] [
		parse structure [
			any [
				begin: (children: none)
				word! ;; type
				set name string!
				opt [block!] ;; meta
				opt [set children block!]
				mark: (
					if children [remove-elements children elements]
					if any [find elements name  attempt [empty? children]] [
						mark: remove/part begin mark
					]
				) :mark
			]
		]
	]

	collect-structure-names: func [
		structure [block!] filter [word! block!] /local result type name
	] [
		result: copy []
		parse structure elements-rule: [
			any [
				set type word!
				set name string!
				opt [block!] ;; meta
				(if filter = type [append result name])
				opt [into [elements-rule]]
			]
		]
		result
	]

	find-skip: func [commands [block!] name [string!]] [
		any [select commands reduce [name 'skip] 0]
	]

	find-size: func [commands [block!] name [string!] /local data spec] [
		if data: select commands reduce [name 'data] [
			return size-of data
		]

		if spec: select commands reduce [name 'size] [
			;; size spec variant 1: `value`
			if integer? spec [return spec]

			;; size spec variant 2: `word` (bound)
			if word? spec [return size-of get spec]

			;; size spec variant 3: `[element num-elements]` (bound, unreduced)
			set [element num-elements] reduce spec
			return num-elements * size-of element
		]

		make error! reform ["Unknown node size:" name]
	]

	find-entry-size: func [commands [block!] name [string!] /local spec] [
		;; Items with a `[element num-elements]` size command have an entry
		;; size, everything else does not.
		either block? spec: select commands reduce [name 'size] [
			size-of first reduce spec
		] [
			0
		]
	]

	merge-meta: func [
		commands [block!] name [string!] meta [block!] /local result
	] [
		append
			reduce ['type meta/1 'flags meta/2 'align meta/3]
			any [select commands reduce [name 'meta] []]
	]

	calc-dynamic-size: func [job-type [word!] symbols [hash!] /local size] [
		size: 9
		if job-type = 'dll [
			if find symbols '***-dll-entry-point [
				size: size + 1
			]
			if find symbols 'on-unload [
				size: size + 1
			]
		]
		size
	]

	complete-sizes: func [
		structure [block!] commands [block!] /local total size name children
	] [
		;; This could be inlined into LAYOUT-BINARY, but having it explicit as
		;; a second pass makes makes things more clear.
		total: 0
		parse structure [
			any [
				word! ;; type
				set name string!
				opt [block!] ;; meta
				[
					set children block!
					(
						total: total + size: complete-sizes children commands
						repend commands [name 'size size]
					)
				|
					(
						size: find-size commands name
						;; Ensure all leaf nodes are padded to 32-bit multiples.
						if not zero? pad: (4 - (size // 4)) // 4 [ ;; @@ Make alignment target-specific.
							repend commands [name 'pad pad]
						]
						total: total + size + pad
					)
				]
			]
		]
		total
	]

	layout-binary: func [
		{Given a file structure and file layout commands, generate a full file
		"layout". A file layout collects the type, offset, address, size,
		metadata and data for each element in the file's structure.}
		structure [block!] commands [block!]
		/local layout emit offset address elements-rule name type meta size
	] [
		layout: copy []

		emit: func [n t o a s m d /local p] [
			p: any [select commands reduce [name 'pad] 0]
			repend layout [
				n reduce [
					'type t 'offset o 'address a 'size s 'pad p 'meta m 'data d
				]
			]
			p
		]

		offset: 0
		address: 0

		complete-sizes structure commands

		parse structure elements-rule: [
			any [
				(meta: copy [])
				set type word!
				set name string!
				opt [set meta block!]
				(
					address: address + find-skip commands name
					size: find-size commands name
					meta: merge-meta commands name meta
					data: select commands reduce [name 'data]
				)
				[
					into [
						(emit name type offset address size meta data)
						elements-rule
					]
				|
					(
						padding: emit name type offset address size meta data
						address: address + size + padding
						offset: offset + size + padding
					)
				]
			]
		]

		layout
	]

	;; -- Definitions lookup --

	lookup-def: func [prefix [string! word!] suffix [string! word!]] [
		defs/(to-word join prefix suffix)
	]

	lookup-flags: func [prefix [string! word!] flags [block!] /local value] [
		value: 0
		foreach flag flags [
			value: value or lookup-def prefix flag
		]
		value
	]

	lookup-align: func [align [word!]] [
		select reduce [
			'byte 1
			'word size-of machine-word
			'page defs/page-size
		] align
	]

	;; -- Helpers for creating/using ELF structures --

	strtab-index-of: func [strtab [binary!] string [string!]] [
		-1 + index? find strtab to-c-string string
	]

	section-index-of: func [
		sections [block!] section [string! none!] /local pos
	] [
		either pos: find sections section [index? pos] [0]
	]

	rel-address-of: func [
		base [integer!]
		/symbol syms [block!] sym [string!]
		/index ind [integer!]
	] [
		base + ((size-of machine-word) * any [ind (-1 + index? find syms sym)])
	]

	to-c-string: func [data [string! binary!]] [join as-binary data #{00}]

	to-elf-strtab: func [items [block!]] [
		join #{00} map-each item items [to-c-string form item]
	]

	to-elf-symbol-info: func [binding [integer!] type [integer!]] [
		(shift/left binding 4) + (type and 15)
	]

	;; -- Helpers for working with various binary data intermediaries --

	serialize-data: func [data [block! object! binary! none!]] [
		case [
			block? data		[rejoin map-each item data [serialize-data item]]
			struct? data	[form-struct data]
			binary? data	[data]
			none? data		[#{}]
		]
	]

	size-of: func [data [block! object! binary! none!]] [
		length? serialize-data data
	]

	;; -- Misc helpers --

	flatten: func [items] [collect [foreach item items [keep item]]]
]
#' Conduct an aggregate query on amcat
#'
#' This function is similar to using the 'show table' function in AmCAT. It allows you to specify a
#' number of queries and get the number of hits per search term, per period, etc.
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param axis1 The first grouping (break/group by) variable, e.g. year, month, week, day, or medium
#' @param axis2 The second grouping (break/group by) variable, e.g. medium. Do not use a date interval here.
#' @param ... additional arguments to pass to the AmCAT API. 
#' @return A data frame with hits per group
#' @export
amcat.aggregate <- function(conn, queries, labels=queries, sets, axis1=NULL, axis2=NULL, ...) {
  result = NULL
  queries = as.character(queries)
  for (i in 1:length(queries)) {
    if (!is.na(queries[i])) {
      
      r = tryCatch(amcat.getobjects(conn,"aggregate", filters=list(q=queries[i], sets=sets, axis1=axis1, axis2=axis2, ...)),
                   error=function(e) {warning("Error on querying '", labels[i], "': ", e$message); NULL})
      if (is.null(r)) next
      if (nrow(r) > 0) {
        if (names(r)[1] == "count") {
          r$query = labels[i]
          result = rbind(result, r)
        } else {
          warning(paste("Error on querying",labels[i]))
        }
      }
    }
  }  
  # convert axis1 to Date object if needed
  if (!is.null(axis1))
    if (axis1 %in% c("year", "quarter", "month", "week", "day")) result[, axis1] = as.Date(result[, axis1])
  return(result)
}

#' Conduct a query on amcat
#'
#' This function is similar to using the 'show article list' function in AmCAT. It allows you to specify a
#' number of queries and get document metadata and number of hits per document
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param ... additional arguments to pass to the AmCAT API, e.g. extra filters
#' @return A data frame with hits per article
#' @export
amcat.hits <- function(conn, queries, labels=queries, sets, minimal=T, ...) {
  result = NULL
  for (i in 1:length(queries)) {
    q = paste("count", queries[i], sep="#")
    r = amcat.getobjects(conn, "search",filters=list(q=q, col="hits", sets=sets, minimal=minimal, ...))
    if (nrow(r) > 0) {
      r$query = labels[i]
      result = rbind(result, r)
    } else {
      warning(paste("Query",labels[i]," produced no results"))
    }
  }
  return(result)
}
#' Default http server configuration for libuv hook.
#' 
#' @param routes list. A named list of routes, with a handler
#'    function for each route. The first unnamed route will be used
#'    as the root. If none is provided, just a 404 status will be returned.
#' @examples
#' \dontrun{
#'   http_server(list('/ping' = function(params, query) 'Hello world!',
#'                    function(params, query) 'Invalid route.'))
#' }
http_server <- function(routes) {
  function(req) {
    params <- extract_params_from_request(req)
    query <- extract_query_from_request(req)
    route <- determine_route(routes, req$PATH_INFO)
    body <- route(params, query)
    if (is.microserver_response(body)) unclass(body)
    else unclass(microserver_response(body))
  }
}


#' Minimal function for opening a socket and accepting/responding to
#' requests.
#'
#' @param routes list. A named list of routes.
#' @param port integer. The default is 8103.
#' @importFrom httpuv startServer stopServer service
#' @export
run_server <- function(routes, port = 8103) {
  # A list of default HTTUPV callbacks
  httpuv_callbacks <- list(
    onHeaders = function(req) { NULL },
    call = http_server(routes),
    onWSOpen = function(ws) {
      # print('opening websocket')
    }
  )

  server_id <- httpuv::startServer("0.0.0.0", port, httpuv_callbacks)
  on.exit({ httpuv::stopServer(server_id) }, add = TRUE)

  repeat {
    httpuv::service(1)
    Sys.sleep(0.001)
  }
}

#' gets the current screen width.
#'
#' It's highly OS specific, I do ignore if it works on OSX

getConsoleWidth <- function() {
  os <- .Platform$OS.type
  if ( os  %in% c("unix", "Darwin" )) {
    as.numeric(system('tput cols', intern=TRUE))
  } else {
    return(tryCatch({
      txt <- system('cmd /c "mode con /status | grep  \"Colonne:\"',
                    intern=TRUE)
      txt <- unlist(strsplit(txt, ":"))[2]
      as.numeric(txt)
    }, error = function (err) {
      ## please God forgive me
      80
    }))
  }
}

#' Classe S4 per ProgressBar
#'
#' @name ProgressBar
#' @rdname ProgressBar
#' @aliases ProgressBar-class
#' @title ProgressBar with labels
#' @slot value current value 
#' @slot min minimum value
#' @slot max maximum value
#' @slot char char to use as token for progress
#' @slot width current screen width, autoevaluated
#' @slot time time since the beginning of ProgressBar
#' @exportClass ProgressBar
#' @export ProgressBar
#' @import methods

ProgressBar <- setClass(
  "ProgressBar",
  representation(
    value= "numeric",
    min="numeric",                        
    max="numeric",
    char="character",
    width="numeric",
    time="POSIXct"))


setMethod(
  "initialize",
  signature("ProgressBar"),
  function(.Object, min=0, max=1, char="=") {
    .Object@min <- min
    .Object@max <- max
    .Object@char <- char
    .Object@width <- getConsoleWidth()
    .Object@time <- Sys.time()
    return(.Object)
  })

#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @docType methods
#' @rdname kill-methods



setGeneric(
  "kill",
  function(x){
    standardGeneric("kill")
  })
#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @aliases kill,ProgressBar-method

setMethod(
  "kill",
  signature("ProgressBar"),
  function(x) {
    cat("\n", file = stderr())
    flush.console()
  })

#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @docType methods
#' @rdname update-methods
#' @export

setGeneric(
  "update",
  function(x, value, label="") {
    standardGeneric("update")
  })
#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @export
#' @rdname update
#' @aliases update,ProgressBar,ANY-method

setMethod(
  "update",
  signature("ProgressBar", "ANY"),
  function(x, value, label="") {    
    x@value  <- value
    min <- x@min
    if(value == min) {
      x@time <- Sys.time()
    }    
    max <- x@max
    char <- x@char
    elapsed <- as.numeric(difftime(Sys.time(),  x@time, units="secs"))
    V <- value/elapsed
    eta <- (max - value) / V
    eta <- if(value == min) {
      "--:--"
    } else if(eta > 3600) {
      sprintf("%02i:%02i:%02i", as.integer(floor(eta/3600)),
              as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    } else {
      sprintf("%02i:%02i", as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    }
    
    if (!is.finite(value) || value < min || value > max)
      return()
    
    nw <- nchar(char,"w")
    pad <- 12 + nchar(eta)
    nlabel <- nchar(label)
    width <- trunc(x@width/nw) - pad - nlabel
    nb <- round(width * (value - min)/(max - min))
    pc <- round(100 * (value - min)/(max - min))
    if(nlabel > 0) {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% - %s %s", pc, label, eta)), collapse = ""),
          file = stderr())
    } else {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% %s", pc, eta)), collapse = ""),
          file = stderr())
      
    }
    flush.console()
    invisible(x)
  })
#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list()
IMMA.parameters  <- list()
IMMA.definitions <- list()

# Core section
IMMA.attachments[[100]] <- 'core'

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH')

# For each parameter, provide an array specifying:
#    Its length in characters, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)
#ICOADS attachment
IMMA.attachments[[1]] = 'icoads';
IMMA.parameters[[1]]  = c('BSI','B10','B1','DCK','SID','PT',
                          'DUPS','DUPC','TC','PB','WX','SX',
			  'C2','SQZ','SQA','AQZ','AQA','UQZ',
			  'UQA','VQZ','VQA','PQZ','PQA','DQZ',
			  'DQA','ND','SF','AF','UF','VF','PF',
			  'RF','ZNC','WNC','BNC','XNC','YNC',
			  'PNC','ANC','GNC','DNC','SNC','CNC',
			  'ENC','FNC','TNC','QCE','LZ','QCZ')
IMMA.definitions[[1]] = list(
    'BSI'  = list( 1, NULL,  NULL,  NULL, NULL, 1., 1 ),
    'B10'  = list( 3, 1.,    648.,  NULL, NULL, 1., 1 ),
    'B1'   = list( 2, 0.,    99.,   NULL, NULL, 1., 1 ),
    'DCK'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'SID'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'PT'   = list( 2, 0.,    15.,   NULL, NULL, 1., 1 ),
    'DUPS' = list( 2, 0.,    14.,   NULL, NULL, 1., 1 ),
    'DUPC' = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'TC'   = list( 1, 0.,    1.,    NULL, NULL, 1., 1 ),
    'PB'   = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'WX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'SX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'C2'   = list( 2, 0.,    40.,   NULL, NULL, 1., 1 ),
    'SQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'SQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'AQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'AQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'UQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'UQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'VQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'VQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'PQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'PQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'DQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'DQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'ND'   = list( 1, 1.,    2.,    NULL, NULL, 1., 1 ),
    'SF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'AF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'UF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'VF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'PF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'RF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'ZNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'WNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'BNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'XNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'YNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'PNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ANC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'GNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'DNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'SNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'CNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ENC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'FNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'TNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'QCE'  = list( 2, 0.,    63.,   NULL, NULL, 1., 1 ),
    'LZ'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'QCZ'  = list( 2, 0.,    31.,   NULL, NULL, 1., 1 )
)
# IMMT2 attachment
IMMA.attachments[[2]] = 'immt2'
IMMA.parameters[[2]]  = c('OS','OP','FM','IX','W2','SGN',
                          'SGT','SGH','WMI','SD2','SP2',
			  'SH2','IS','ES','RS','IC1','IC2',
			  'IC3','IC4','IC5','IR','RRR','TR',
			  'QCI','QI1','QI2','QI3','QI4',
			  'QI5','QI6','QI7','QI8','QI9',
			  'QI10','QI11','QI12','QI13','QI14',
			  'QI15','QI16','QI17','QI18','QI19',
			  'QI20','QI21','HDG','COG','SOG',
			  'SLL','SLHH','RWD','RWS')
IMMA.definitions[[2]] = list(
    'OS'   = list( 1, 0.,   6.,   NULL,  NULL,  1.,  1 ),
    'OP'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'FM'   = list( 2, 0.,   8.,   NULL,  NULL,  1.,  1 ),
    'IX'   = list( 1, 1.,   7.,   NULL,  NULL,  1.,  1 ),
    'W2'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGN'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGT'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'SGH'  = list( 2, 0.,   50.,  56.,   99.,   1.,  1 ),
    'WMI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SD2'  = list( 2, 0.,   38.,  NULL,  NULL,  1.,  1 ),
    'SP2'  = list( 2, 0.,   30.,  99.,   99.,   1.,  1 ),
    'SH2'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'IS'   = list( 1, 1.,   5.,   NULL,  NULL,  1.,  1 ),
    'ES'   = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'RS'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'IC1'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC2'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC3'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC4'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC5'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IR'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'RRR'  = list( 3, 0.,   999., NULL,  NULL,  1.,  1 ),
    'TR'   = list( 1, 1.,   9.,   NULL,  NULL,  1.,  1 ),
    'QCI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI1'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI2'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI3'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI4'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI5'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI6'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI7'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI8'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI9'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI10' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI11' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI12' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI13' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI14' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI15' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI16' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI17' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI18' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI19' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI20' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI21' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'HDG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'COG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'SOG'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLL'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLHH' = list( 3, -99., 99.,  NULL,  NULL,  1.,  1 ),
    'RWD'  = list( 3, 1.,   362., NULL,  NULL,  1.,  1 ),
    'RWS'  = list( 3, 0.0,  99.9, NULL,  NULL,  0.1, 1 )
)
# Model quality control attachment
IMMA.attachments[[3]] = 'mqc';
IMMA.parameters[[3]]  = c('CCCC','BUID','BMP','BSWU','SWU',
                          'BSWV','SWV','BSAT','BSRH','SRH',
			  'SIX','BSST','MST','MSH','BY',
			  'BM','BD','BH','BFL')
IMMA.definitions[[3]] = list(
    'CCCC' = list( 4, 65.,   90.,    NULL,  NULL,  NULL,  3 ),
    'BUID' = list( 6, 48.,   57.,    65.,   90.,   NULL,  3 ),
    'BMP'  = list( 5, 870.0, 1074.6, NULL,  NULL,  0.1,   1 ),
    'BSWU' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWU'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSWV' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWV'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSAT' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSRH' = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SRH'  = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SIX'  = list( 1, 2.,    3.,     NULL,  NULL,  1.,    1 ),
    'BSST' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'MST'  = list( 1, 0.,    9.,     NULL,  NULL,  1.,    1 ),
    'MSH'  = list( 3, 0.,    999.,   NULL,  NULL,  1.,    1 ),
    'BY'   = list( 4, 0.,    9999.,  NULL,  NULL,  1.,    1 ),
    'BM'   = list( 2, 1.,    12.,    NULL,  NULL,  1.,    1 ),
    'BD'   = list( 2, 1.,    31.,    NULL,  NULL,  1.,    1 ),
    'BH'   = list( 2, 0.,    23.,    NULL,  NULL,  1.,    1 ),
    'BFL'  = list( 2, 0.,    99.,    NULL,  NULL,  1.,    1 )
)
# Metadata attachment
IMMA.attachments[[4]] = 'metadata'
IMMA.parameters[[4]]  = c('C1M','OPM','KOV','COR','TOB','TOT',
                          'EOT','LOT','TOH','EOH','SIM','LOV',
			  'DOS','HOP','HOT','HOB','HOA','SMF',
			  'SME','SMV')
IMMA.definitions[[4]] = list(
    'C1M' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'OPM' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'KOV' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'COR' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'TOB' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOT' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOH' = list( 1, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOH' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'SIM' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOV' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'DOS' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'HOP' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOT' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOB' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOA' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'SMF' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SME' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SMV' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 )
)
# Historical attachment
IMMA.attachments[[5]] = 'historical'
IMMA.parameters[[5]]  = c('WFI','WF','XWI','XW','XDI','XD',
                       'SLPI','TAI','TA','XNI','XN')
IMMA.definitions[[5]] = list(
    'WFI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'WF'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XWI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XW'   = list( 3, NULL,  NULL,  NULL,  NULL,  0.1,   1 ),
    'XDI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XD'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SLPI' = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TAI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TA'   = list( 4, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XNI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XN'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 )
)
# Supplemental attachment
IMMA.attachments[[99]] = 'supplemental'
IMMA.parameters[[99]]  = c('ATTE','SUPD')
IMMA.definitions[[99]] = list(
    'ATTE' = list( 1,     NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SUPD' = list( NULL,  NULL,  NULL,  NULL,  NULL,  NULL,  3 )
)

#' Find out which attachment a parameter is in
#'
#' IMMA data are divided into core parameters and optional attachments
#' this function gives the attachment number of a parameter name.
#'
#' Attachment 100 is core. 
#'
#' @export
#' @param parameter - Name of parameter to be found
#' @return the number of the attachment containing that parameter.
IIMMA.whichAttachment <- function(parameter) {
    for(i in c(100,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

#' Check the value for a parameter is inside its acceptable range(s)
#'
#' Flags data which is physically impossibe and can't be written in IMMA.
#'
#' The IMMA format constrains the possible ranges of numeric parameters
#'  data outside those ranges can't be written in the format.This function
#'  tests all the data for a selected paramete is inside the acceptable range.
#'
#' @export
#' @param ob Observations data frame.
#' @param parameter - Name of parameter to be tested
#' @return for each observbation, TRUE if within range (or no range defined), FALSE if
#'  outside range.
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[7] == 3 ) {
        return(result); 
    }
  
    w<-which(!is.null(ob[[parameter]]) & !is.na(ob[[parameter]]) &
             ((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] ))
        |    ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= ob[[parameter]] )))
    if(length(w)<length(ob[[parameter]])) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        definitions<-IMMA.definitionsFor(parameter)

        # Treat differently according to type
        if(definitions[7]==3) { # Character, just print
          w<-which(!is.null(ob[[parameter]]))
          if(length(w)>0) {
              if(!is.null(definitions[1])) {
                 Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],ob[[parameter]][w])
              } else {  # Unspecified length, supplementary only - use length of data
                 Result[w]<-sprintf("%s%s",Result[w],ob[[parameter]][w])
              }
          }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
              if(!is.null(definitions[1])) {
                 Result[!w]<-sprintf(sprintf("%%s%%.%ss",definitions[1]),Result[!w],' ')
              } else {  # Unspecified length, supplementary only - use length of data
                 Result<-sprintf("%s%s",Result[!w],' ')
              }
          }
        }
        if(definitions[7]==1) { # Integer - check, scale, round and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             Result[w]<-sprintf(sprintf("%%s%%.%dd",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
        if(definitions[7]==2) { # Base36 - check, scale, convert and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             enc<-IMMA.encode_base36(round)
             Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
      }
    # Done all the parameters, add the ID and length to the start
    # (except for core)
    if ( attachment != 100 ) {
        if ( attachment == 99 ) {
            Result = sprintf(" 0%s",Result)
        } else {
            Result = sprintf("%2d%s",nchar(Result)+4,Result)
        }
        Result = sprintf("%2d%s",attachment,Result)
    }

    return(Result)
  }

# Make a string version of the whole record
IMMA.packString <- function(ob) {
    Result = rep('',length(ob$YR))
    for(attachment in c(100,1,2,3,4,5,99)) {
      w<-IMMA.hasAttachment(ob,attachment)
      if(length(w)>0) {
        Result[w]<-sprintf("%s%s",Result,IMMA.encodeAttachment(ob[w,],attachment))
      }
    }
    return(Result)
}

# Unpack the string version of an attachment into a data frame
IMMA.decodeAttachment <- function(ob.strings,attachment){
   Result<-data.frame()
   pstart<-1
   for ( parameter in IMMA.parameters[[attachment]]) {
      definitions<-IMMA.definitionsFor(parameter)
      pstring<-substr(ob.strings,pstart,pstart+definitions[1])
      pstart<-pstart+definitions[1]
      pstring<-sub("^\\s+", "", pstring) # strip leading blanks
      w<-which(nchar(pstring)==0)        # all blank - set to missing
      
      if(definitions[7]==3) { # Character,add directly
        if(length(w)>0) {
           is.na(pstring[w])<-TRUE
        }
        Result[[parameter]]<-pstring
      }
      if(definitions[7]==2) { # Base36 - convert, scale and add
        pint<-integer(length(pstring))
        if(length(w)>0) {
           is.na(pint[w])<-TRUE
        }
        if(length(w)<length(pint)) {
          pint[-w]<-IMMA.decode_base36(pstring[-w])
        }
        Result[[parameter]]<-pint*dimensions[6]
      }
      if(definitions[7]==1) { # numeric data - scale and add
        pint<-integer(length(pstring))
        if(length(w)>0) {
           is.na(pint[w])<-TRUE
        }
        Result[[parameter]]<-pint*dimensions[6]
      }
    }
   return(Result)
}

# Unpack from string format into a data frame
IMMA.unpack <- function(ob.strings) {

   # split the strings into a separate vector for each attachment
   atsplit<-list()
   # Core is always present and first
   atsplit[[100]]<-substr(ob.strings,1,108)
   ob.strings<-substring(ob.strings,109)
   w<-which(nchar(ob.strings)>4)
   while(length(w)>0) {
     att.no<-as.integer(substr(ob.strings[w],1,2))
     att.len<-as.integer(substr(ob.strings[w],3,4))
     for(attachment in c(1,2,3,4,5)) {
        w2<-which(att.no==attachment)
        if(length(w2)>0) {
          atsplit[[attachment]][w][w2]<-substr(ob.strings[w][w2],5,att.len)
          ob.strings[w][w2]<-substring(ob.strings[w][w2],att.len+1)
        }
      }
     attachment<-99 # No set length - use the rest of the string
     w2<-which(att.no==attachment)
     if(length(w2)>0) {
       atsplit[[attachment]][w][w2]<-substring(ob.strings[w][w2],5)
       ob.strings[w][w2]<-''
     }
     w<-which(nchar(ob.strings)>4)
   }
   return(atsplit)
}


#' Read in all the IMMA records from a connection
#'
#' Keeps the data internally in a data frame - size
#'  depends on which attachments are present in the source.
#'
#' Currently only supports IMMA0 format.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
#IMMA.read<-function(con,n=-1) {
library(zoo)
library(Matrix)
library(tm)

#' Call a frog (Dutch lemmatizer and dependency parser) instance running in daemon mode
#' 
#' See http://ilk.uvt.nl/frog/
#' To install frog and run as daemon (assuming debian/ubuntu), run:
#' $ sudo apt-get install frog frogdata ucto
#' $ frog -S 9772
#' 
#' A separate call to frog is made for each text in the text input vector.
#' 
#' Note that if something is wrong, it is quite possible that this function will totall hang
#' your R session as it is waiting for output on the socket, so use with caution!
#' 
#' @param text: The text(s) to parse
#' @param host: The hostname for the frog server
#' @param port: The port the frog server is listening on
#' @param verbose: If true, output a message for each document
#' @return a data frame of tokens with columns for lemma, pos, etc 
#' @export
call_frog <- function(text, host="localhost", port=9772, verbose=T) {
  # establish connection and add finalizing code
  socket <- make.socket(host, port)
  on.exit(close.socket(socket))
  # call frog, ending with EOT
  result <- NULL
  for (i in 1:length(text)) {
    t = text[i]
    if (verbose) message("Frogging document ",i,": ", nchar(t), " characters")
    tokens = do_call_frog(socket, t)
    tokens$docid = i
    result = rbind(result, tokens)
  }
  result[, c(ncol(result), ncol(result)-1, 1:(ncol(result)-2))]
}

#' Do the actual call to frog, returning the data frame
do_call_frog <- function(socket, text) {
  write.socket(socket, text)
  write.socket(socket, "\nEOT\n")
  # read until 'READY' is found
  output <- ""
  while (!grepl("\nREADY\n$", output)) {
    output = paste(output, read.socket(socket), sep="")  
  }
  output = gsub("READY\n$", "", output)
  # read output and label columns
  con <- textConnection(output)
  result = read.table(con, header=F, sep="\t")
  colnames(result) <- c("position", "word", "lemma", "morph", "pos", "prob",
                        "ner", "chunk", "parse1", "parse2")
  result$majorpos = gsub("\\(.*", "", result$pos)
  # assign sentence number by assigning number when position == 1 and filling down into NA cells using zoo::na.locf
  result$sent[result$position == 1] = 1:sum(result$position == 1)
  result$sent = na.locf(result$sent)
  result
}

#' Create a document term matrix from a token list
#' 
#' @param docs: a vector that identifies to which document a token belongs
#' @param terms: a vector of terms of length equal to docs
#' @param freqs: an optional vector giving the frequency of each term
#' @param weighting: the optional weighting for tm (default: term frequency)
#' @return an object of type DocumentTermMatrix (from the tm package)
#' @export
create_dtm <- function(docs, terms, freqs=rep(1, length(terms)), weighting=weightTf) {
  d = data.frame(doc=docs, term=terms, freq=freqs)
  d = aggregate(freq ~ doc + term, d, FUN='sum')
  docnames = unique(d$doc)
  termnames = unique(d$term)
  sm = spMatrix(nrow=length(docnames), ncol=length(termnames),
                match(d$doc, docnames), match(d$term, termnames), d$freq)
  rownames(sm) = docnames
  colnames(sm) = termnames
  as.DocumentTermMatrix(sm, weighting=weighting)
}

result = call_frog("Een zin is een test. Maar nog een zin?\nEven Apeldoorn bellen!")
docs = result$sent
terms = result$lemma
freqs=rep(1, length(terms))

m = create_dtm(result$sent, result$lemma)
as.matrix(m)

nouns = result[result$majorpos == "N", ]
m = create_dtm(nouns$sent, nouns$lemma)
as.matrix(m)
REBOL [
	Title:		"Red/System ARM code emitter"
	Author:		"Andreas Bolka, Nenad Rakocevic"
	File:		%ARM.r
	Tabs:	 4
	Rights:		"Copyright (C) 2011-2012 Andreas Bolka, Nenad Rakocevic. All rights reserved."
	License:	"BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

make-profilable make target-class [
	target:				'ARM
	little-endian?:		yes
	struct-align-size:	4
	ptr-size:			4
	default-align:		4
	stack-width:		4
	stack-slot-max:		8							;-- size of biggest datatype on stack (float64!)
	args-offset:		8							;-- stack frame offset to arguments (fp + lr)
	branch-offset-size:	4							;-- size of branch instruction
	insn-size:			4
	
	need-divide?: 		none						;-- if TRUE, include division routine in code
	div-sym:			'_div_
	
	conditions: make hash! [
	;-- name ----------- signed --- unsigned --
		overflow?		 #{60}		-
		not-overflow?	 #{70}		-	
		=				 #{00}		-
		<>				 #{10}		-
		signed?			 -			-
		unsigned?		 -			-
		even?			 -			-
		odd?			 -			-
		<				 #{b0}		#{30}
		>=				 #{a0}		#{20}
		<=				 #{d0}		#{90}
		>				 #{c0}		#{80}
	]
	
	byte-flag: 			#{00400000}					;-- trigger byte access in opcode
	
	pools: context [								;-- literals pools management
		active?:	  no							;-- yes => store in pools, no => store inlined
		values:		  make block! 2000				;-- [value instruction-pos sym-spec ...]
		entry-points: make block! 100				;-- insertion points candidates for pools between functions
		ins-points:	  make block! 100				;-- insertion points candidates for pools inlined in code
		pools:		  make block! 1					;-- [pool-pos [value-ref ...] inline? ...]
		limit:		  4088							;-- reachability max distance (insn<->pool, 4092 - insn - branching)
		verbose:	  0								;-- if > 0, output debug logs
		
		pools-stats: has [list][
			print "--- Pools:"
			list: pools
			forskip list 3 [
				print ["pos:" list/1 ", literals:" length? list/2]
			]
			print "---"
		]
		
		;-- Collect a literal value to be stored in a pool
		collect: func [value [integer!] /spec s [word! get-word! block!] /with opcode [binary!] /local pos][
			either active? [
				insert pos: tail values reduce [value emitter/tail-ptr s]
				emit-reloc-addr/only next pos
				emit-i32 any [opcode #{e59f0000}]
				pos
			][
				emit-i32 any [opcode #{e59f0000}]	;-- LDR r0, [pc, #0]	; offset 0 => value
				emit-i32 #{ea000000}				;-- B <after_value>
				if spec [
					spec: switch type?/word s [
						get-word! [emitter/get-symbol-ref to word! s]
						word!	  [emitter/symbols/:s]
						block!	  [s]
					]
					
					emit-reloc-addr spec/3
				]				
				emit to-bin32 value					;-- emit value
			]
		]
		
		;-- Collect a possible position in code for a literals pool
		mark-entry-point: func [name][
			if verbose > 0 [print ["new entry-point:" emitter/tail-ptr "(after" name #")"]]
			
			append entry-points emitter/tail-ptr
		]
		
		mark-ins-point: has [pos][
			pos: emitter/tail-ptr
			if pos <> pick tail ins-points -1 [append ins-points pos]
		]
		
		insert-jmp-point: func [idx [integer!] offset [integer!]][			
			update-values-index idx 4				;-- move values references by 4 bytes
			update-entry-points idx 4				;-- move entry-points by 4 bytes
		]
		
		get-pool: does [all [not empty? pools skip tail pools -3]]
		
		make-pool: func [/ins /local bound base list pool refs][
			if all [
				not ins
				(entry-points/1 - first any [get-pool [1]]) >= limit
			][
				ins: true
			]
			list: either ins [ins-points][entry-points]
			
			if all [
				not empty? pools
				empty? second pool: get-pool	;-- remove last pool if empty
			][
				clear pool
			]
			either ins [
				base: ins-points/1				;-- start search on first available insertion point
				while [list/1 - base < limit][	;-- search farthest reachable point (accounting for fake entry)
					list: next list
				]
				list: back list					;-- limit exceeded, back to last reachable
			][
				unless empty? pools [
					bound: second last second get-pool	;-- start search after last stored literal entry position in code
					while [list/1 < bound][
						list: next list
					]
					if tail? list [
						compiler/throw-error "[ARM emitter] suitable pool position not found!"
					]
				]
			]
				
			if verbose > 0 [print ["^/* making a new pool, at:" list/1 ", inlined?:" ins]]
			
			repend pools [list/1 refs: make block! 50 to logic! ins]	;-- create a new pool entry
			
			either ins [
				remove/part ins-points next list	;-- clear all ins-points before pool position
				repend/only refs [0 0 none]			;-- insert fake literal in pool (place-holder for B insn) 
			][
				entry-points: next list				;-- move to next possible position
			]
			get-pool								;-- return a reference on the last pool structure
		]
				
		update-values-index: func [idx [integer!] offset [integer!]][		
			forskip values 3 [			
				if values/2 >= idx [values/2: values/2 + offset]
			]			
		]
		
		;-- Update functions entry points after a pool insertion
		update-entry-points: func [pool-idx [integer!] offset [integer!] /strict /local refs comp ep][
			comp: get pick [greater? greater-or-equal?] to logic! strict
			
			ep: head entry-points
			forall ep [if comp ep/1 pool-idx [ep/1: ep/1 + offset]]
			
			forskip pools 3 [if comp pools/1 pool-idx [pools/1: pools/1 + offset]]

			foreach [name spec] emitter/symbols [	;-- move functions entry-points and references
				if find [native native-ref] spec/1 [
					if all [spec/2 spec/2 >= pool-idx][spec/2: spec/2 + offset]
					unless empty? refs: spec/3 [
						forall refs [if refs/1 >= pool-idx [refs/1: refs/1 + offset]]
					]
				]
			]
		]

		;-- Update functions entry points after a pool insertion
		update-refs-part: func [floor [integer!] ceil [integer!] offset [integer!] /local refs ep ip][
			forskip values 3 [
				if values/2 - 4 > ceil [break]
				if values/2 - 4 >= floor [values/2: values/2 + offset]
			]
			values: head values
			
			ep: head entry-points
			forall ep [
				if ep/1 - 4 > ceil [break]
				if ep/1 - 4 > floor [ep/1: ep/1 + offset]
			]

			ip: head ins-points
			forall ip [
				if ip/1 - 4 > ceil [break]
				if ip/1 - 4 > floor [ip/1: ip/1 + offset]
			]

			forskip pools 3 [
				if pools/1 - 4 > ceil [break]
				if pools/1 - 4 > floor [pools/1: pools/1 + offset]
			]
			pools: head pools

			foreach [name spec] emitter/symbols [	;-- move functions entry-points and references
				if find [native native-ref] spec/1 [
					if all [spec/2 spec/2 >= floor spec/2 - 4 < ceil][spec/2: spec/2 + offset]
					unless empty? refs: spec/3 [
						forall refs [
							if refs/1 - 4 > ceil [break]
							if refs/1 - 4 >= floor [refs/1: refs/1 + offset]
						]
					]
				]
			]
		]
		
		find-close-pool: func [pool-idx [integer!] ins-idx [integer!] /local pool][
			pool: find/skip pools pool-idx 3
			until [
				pool: skip pool 3
				if tail? pool [
					if limit > entry-points/1 [return make-pool]	;-- see if next entry-point is reachable
					return make-pool/ins							; @@ temp change
					;compiler/throw-error "[ARM emitter] unable to find a reachable pool!"
				]
				limit > (abs pool/1 + (4 * length? pool/2) - (ins-idx + 8))
			]
			pool
		]
		
		;-- Create literal pools lists and put literals pointers inside according to their distance
		populate-pools: has [index pos offset pool][
			if verbose > 0 [print "^/=== Populate stage ==="]
			
			forskip values 3 [
				index: values/2
				if empty? pools [make-pool]

				pool: get-pool
				pos: pool/1 + (4 * length? pool/2)	;-- pos: offset of value entry in the pool buffer

				offset: pos - index
				if verbose > 0 [prin [offset #" "]]

				either positive? offset [			;-- test if pool is before or after caller
					if limit <= offset [				;-- if pool is too far ahead
						pool: make-pool/ins			;-- make a new pool at next possible insertion position
					]
				][
					if limit <= abs offset [			;-- if pool too far behind,
						pool: make-pool				;-- make a new pool at next possible position @@ > 4088 case
						pos: pool/1
					]
				]
				append/only pool/2 values			;-- insert literal value in the pool
			]
			sort/skip pools 3
		]
		
		;-- Move literal values that became out-of-range to a closer pool
		adjust-pools: has [pool-size value ins-idx spec entry-pos offset][
			if verbose > 0 [print "^/=== Adjust stage ===" pools-stats]
			
			foreach [pool-idx value-refs inline?] pools [
				pool-size: 4 * length? value-refs
				update-values-index pool-idx pool-size
				update-entry-points/strict pool-idx pool-size
			]
		
			foreach [pool-idx value-refs inline?] pools [
				if verbose > 0 [print ["^/processing pool:" pool-idx]]
				if inline? [value-refs: next value-refs]	;-- skip first fake entry (for branch insn)
				
				forall value-refs [		
					set [value ins-idx spec] value-refs/1
					
					entry-pos: 4 * (-1 + index? value-refs)	;-- offset of value entry in the pool
					offset: pool-idx + entry-pos - (ins-idx + 8)	;-- relative jump offset to the entry				
					if verbose > 0 [prin [offset #" "]]
				
					offset:	abs offset

					if offset >= limit [
						pool: find-close-pool pool-idx ins-idx
						if verbose > 0 [print ["^/* out-of-range:" offset ", moving to pool:" pool/1]]
						append/only pool/2 value-refs/1
						remove value-refs
						value-refs: back value-refs

						update-refs-part pool-idx pool/1 -4

						;update-values-index pool-idx -4
						;update-entry-points/strict pool-idx -4
						;
						;update-values-index pool/1 4
						;update-entry-points/strict pool/1 4
					]
				]
			]
		]
		
		;-- Build pools buffers and insert them in native code buffer
		commit-pools: has [buffer value ins-idx spec entry-pos offset code back? buf-size][
			if verbose > 0 [print "^/=== Commit stage ===" pools-stats]
			buffer: make binary! 800						;-- reserve pool buffer for 200 values (average estimate)

			foreach [pool-idx value-refs inline?] pools [
				if verbose > 0 [print ["^/- pool:" pool-idx ", len:" length? value-refs]]
				clear buffer
				
				buf-size: 4 * length? value-refs
				if inline? [
					append buffer reverse rejoin [			;-- B <buf-size>	; branch over the pool buffer
						#{ea} to-bin24 shift buf-size - 8 2
					]
					value-refs: next value-refs				;-- skip place-holder value				
				]
				insert/dup at emitter/code-buf pool-idx null buf-size
				
				forall value-refs [		
					set [value ins-idx spec] value-refs/1
					
					append buffer reverse debase/base to-hex value 16
										
					entry-pos: 4 * (-1 + index? value-refs)	;-- offset of value entry in the pool
					offset: pool-idx + entry-pos - (ins-idx + 8)	;-- relative jump offset to the entry				
					back?: negative? offset 
					if verbose > 0 [prin [offset #" "]]
					
					offset:	abs offset

					if offset >= limit [
						compiler/throw-error "[ARM emitter] adjusting failed!"
					]
					offset: reverse to-12-bit offset
					
					code: at emitter/code-buf ins-idx
					change code offset or copy/part code 4	;-- add relative jump offset to instruction
					if back? [code/3: #"^(7F)" and code/3]	;-- encode a negative offset

					if spec [
						spec: switch type?/word spec [
							get-word! [emitter/get-func-ref to word! spec]
							word!	  [emitter/symbols/:spec]
							block!	  [spec]
						]
						append spec/3 pool-idx + entry-pos	;-- add symbol back-reference for linker
					]
				]
				change at emitter/code-buf pool-idx buffer	;-- insert pool in code buffer
			]
		]
		
		process: does [
			unless empty? values [
				populate-pools
				adjust-pools
				commit-pools
			]	
			clear entry-points: head entry-points
			clear ins-points
			clear values
			clear pools
		]
	]
	
	emit-reloc-addr: func [spec [block!] /only][
		unless only [append spec emitter/tail-ptr]	;-- save reloc position
		unless empty? emitter/chunks/queue [				
			append/only 							;-- record reloc reference
				second last emitter/chunks/queue
				either only [spec][back tail spec]
		]
	]
	
	emit-divide: has [base][
		;-- Unsigned division code is from http://www.virag.si/2010/02/simple-division-algorithm-for-arm-assembler/
		;-- Original routine extended to handle signed division using code from:
		;-- "ARM System Developer's Guide", p.238, ISBN: 1-55860-874-5
		;-- registers usage:
		;-- 	- on entering: r0: dividend, r1: divisor, r4: mode (0: division, 1: modulo, 2: remainder)
		;--		- on exit: r0: quotient, r1: remainder or r0: modulo/remainder
		;--		- registers modified: r0-r3, r5, ip
		
		if verbose >= 3 [print "^/>>>emitting DIVIDE intrinsic"]
		
		base: emitter/tail-ptr
		
		foreach opcode [	
							; .divide	
			#{e3510000}			; CMP r1, #0			; if divisor = 0
			#{092d4000}			; PUSHEQ {lr}			; push calling address for error location
			#{03a0000d}			; MOVEQ r0, #13			; integer divide by zero error code
			#{092d0001}			; PUSHEQ {r0}
			#{0a000000}			; BEQ ***-on-quit		; call runtime error handler
			#{e1500001}			; CMP r0, r1			; if dividend = divisor
			#{0a00000b}			; BEQ .equal
			#{e1a03000}			; MOV r3, r0			; r3: dividend
			#{e1a05001}			; MOV r5, r1			; r5: divisor
			#{e3500000}			; CMP r0, #0			; if dividend < 0
			#{42603000}			; RSBMI r3, r0, #0		;	r3: -dividend
			#{e3510000}			; CMP r1, #0			; if divisor < 0
			#{42615000}			; RSBMI r5, r1, #0		;	r5: -divisor
			#{e3500102}			; CMP r0, #1<<31		; if r3 = -2^31 (special case for -2^31)
			#{0a000006}			; BEQ .ispowerof2		; or
			#{e1530005}			; CMP r3, r5			; if r3 <= divisor
			#{8a000004}			; BHI .ispowerof2			
			#{e1a01000}			; MOV r1, r0			; remainder: dividend
			#{e3a00000}			; MOV r0, #0			; quotient: 0
							; .equal
			#{03a00001}			; MOVEQ r0, #1			; if dividend = divisor, quotient: 1
			#{03a01000}			; MOVEQ r1, #0			;	remainder: 0
			#{ea000024}			; B .divide_end			; jump to remainder epilog
							; .ispowerof2
			#{e2413001}			; SUB r3, r1, #1		; r3: divisor - 1
			#{e1130001}			; TST r3, r1			; if divisor is a power of 2 (divisor & (divisor - 1))
			#{1a00000c}			; BNE .notpowerof2
			#{e1a03000}			; MOV r3, r0			; save dividend
			#{e1a02001}			; MOV r2, r1			; save divisor
							; .powerof2
			#{31a000c0}			; MOVCC r0, r0, ASR#1	; divide by 2 (but not on first pass)
			#{e1b010a1}			; MOVS r1, r1, LSR#1	; until power of 2 reached (carry set)
			#{3afffffc}			; BCC .powerof2
			#{e2621000}			; RSB r1, r2, #0		; 2's complement of divisor
			#{e0031001}			; AND r1, r3, r1		; r1: dividend and -divisor
			#{e0431001}			; SUB r1, r3, r1		; compute remainder = (dividend - (dividend and -divisor))
			#{e3530102}			; CMP r3, #1<<31		; if r3 = -2^31 (special case for -2^31)
			#{0a000017}			; BEQ .divide_end		; 	jump to end
			#{e3530000}			; CMP r3, #0			; if dividend < 0
			#{40411002}			; SUBMI r1, r1, r2		;	adjust remainder (remainder = remainder - divisor)
			#{ea000014}			; B .divide_end
							; .notpowerof2
			#{e1b02001}			; MOVS r2, r1			; r2: divisor
			#{e212c102}			; ANDS ip, r2, #1<<31	; if r2 < 0, ip: #80000000
			#{42622000}			; RSBMI r2, r2, #0		; if r2 < 0, r2: -r2 (2's complement)
			#{e1b01000}			; MOVS r1, r0			; r1: dividend
			#{e03cc041}			; EORS ip, ip, r1 ASR#32 ; if r1 < 0, ip: ip xor r1>>32
			#{22611000}			; RSBCS r1, r1, #0		; if r1 < 0, r1: -r1 (2's complement)
			
			#{e3a00000}			; MOV r0, #0     		; clear R0 to accumulate result
			#{e3a03001}			; MOV r3, #1     		; set bit 0 in R3, which will be shifted left then right
							; .start
			#{e1520001}			; CMP r2, r1
			#{91a02082}			; MOVLS r2, r2, LSL#1	; shift R2 left until it is about to be bigger than R1
			#{91a03083}			; MOVLS r3, r3, LSL#1	; shift R3 left in parallel in order to flag how far we have to go
			#{9afffffb}			; BLS      start
							; .next
			#{e1510002}			; CMP r1, r2      		; carry set if R1>R2 (don't ask why)
			#{20411002}			; SUBCS r1, r1, r2      ; subtract R2 from R1 if this would
														; give a positive answer
			#{20800003}			; ADDCS r0, r0, r3   	; and add the current bit in R3 to
											  			; the accumulating answer in R0.
			#{e1b030a3}			; MOVS r3, r3, LSR#1	; Shift R3 right into carry flag
			#{31a020a2}			; MOVCC r2, r2, LSR#1	; and if bit 0 of R3 was zero, also
												   		; shift R2 right.
			#{3afffff9}			; BCC next				; If carry not clear, R3 has shifted
			
							; .epilog					; back to where it started, and we can end
			#{e1b0c08c}			; MOVS ip, ip, LSL#1	; C: bit 31, N: bit 30
			#{22600000}			; RSBCS	r0, r0, #0		; if C = 1, r0: -r0 (2's complement)
			#{42611000}			; RSBMI	r1, r1, #0		; if N = 1, r1: -r1 (2's complement)								
							; .divide_end				; r0: quotient, r1: remainder
			#{e3340000}			; TEQ r4, #0			; if not modulo/remainder op,
			#{01a0f00e}			; MOVEQ pc, lr			; 	return from sub-routine
			
			;-- Adjust modulo result to be mathematically correct:
			;-- 	if modulo < 0 [
			;--			if divisor < 0 [divisor: negate divisor]
			;--			modulo: modulo + divisor
			;--		]
			#{e1b00001}			; MOVS r0, r1			; r0: modulo or remainder
			#{e3340002}			; TEQ r4, #2			; if r1 <> rem,
			#{01a0f00e}			; MOVEQ pc, lr			; 	return from sub-routine
			#{e3500000}			; CMP r0, #0	 		; if r0 >= 0, (modulo)
			#{51a0f00e}			; MOVPL pc, lr			; 	return from sub-routine
			#{e3520000}			; CMP r2, #0	 		; if r2 < 0 (divisor)
			#{41e00000}			; RSBMI	r0, r0, #0		;	r0: -r0 (2's complement)
			#{e0800002}			; ADD r0, r0, r2		; r0: r0 + r2
			#{e1a0f00e}			; MOV pc, lr			; return from sub-routine
 		][
 			emit-i32 opcode
 		]
 		;-- link it with runtime error handler
 		append emitter/symbols/***-on-quit/3 base + (4 * insn-size)
	]
	
	;-- Check if div-sym is not user-defined, else provide a unique replacement symbol
	make-div-sym: has [retry][
		if select emitter/symbols div-sym [
			retry: 3								;-- try 3 times, then spit an error to user face ;)
			until [
				div-sym: to word! rejoin ["_div_" random "0123456798"]
				if zero? retry: retry - 1 [
					compiler/throw-error "Unable to create divide symbol!"
				]
				none? emitter/symbols/:div-sym
			]
		]
		div-sym
	]
	
	call-divide: func [mod? [word! none!] /local refs][
		refs: third either need-divide? [
			emitter/symbols/:div-sym
		][
			div-sym: make-div-sym
			need-divide?: yes
			emitter/add-native div-sym				;-- add an entry for the divide pseudo-function
		]
		
		emit-i32 join #{e3a040} switch/default mod? [ ;-- MOV r4, #0|1|2
			mod [#"^(01)"]							;-- modulo
			rem [#"^(02)"]							;-- remainder
		][null]										;-- division
		
		emit-reloc-addr refs
		emit-i32 #{eb000000}						;-- BL .divide
	]
	
	on-init: does [
		if PIC? [
			emit-i32 #{e1a0900f}					;-- MOV sb, pc
			emit-i32 #{e2499008}					;-- SUB sb, #8
		]
	]
	
	on-finalize: does [
		if need-divide? [
			emitter/symbols/:div-sym/2: emitter/tail-ptr
			emit-divide
		]
		if pools/active? [pools/process]			;-- trigger pools processing on end of code generation
	]
	
	on-global-prolog: func [runtime? [logic!]][
		pools/active?: compiler/job/literal-pool?
		if runtime? [need-divide?: no]
	]
	
	on-global-epilog: func [runtime? [logic!]][
		if all [
			not runtime?
			compiler/job/runtime?
			compiler/job/need-main?
		][
			emit-pop								;-- pop zero padding
			emit-pop								;-- pop CATCH_ALL barrier
			emit-i32 #{e8bd0800}					;-- POP {fp}
			emit-epilog '***_start [] 7 * 4 0		;-- restore all before returning in __libc_start_main()
		]
		unless runtime? [
			pools/mark-entry-point 'global			;-- add end of global code section as pool entry-point
		]
	]
	
	on-root-level-entry: does [
		pools/mark-ins-point
	]
	
	count-floats: func [spec [block!] /local cnt][
		cnt: 0
		parse spec [any [into ['float! | 'float64! | 'float32!] (cnt: cnt + 1) | skip]]		
		cnt
	]
	
	extract-arguments: func [spec [block!] /local cnt][
		spec: copy spec
		clear find spec first [return:]
		clear find spec /local
		if string? spec/1 [remove spec]
		if block?  spec/1 [remove spec]
		remove-each value spec [not block? value]
		head reverse spec
	]
	
	arguments-on-stack?: func [args [block!] /cdecl /local total][
		total: 0
		forall args [
			if args/1 <> #_ [						;-- bypass place-holder marker
				total: total + argument-size? args/1 to logic! cdecl
				if total > 16 [return args]
			]
		]
		none
	]
	
	to-bin24: func [v [integer! char!]][
		copy skip debase/base to-hex to integer! v 16 1
	]
	
	;-- Convert a 12-bit integer offset to a 32-bit hexa LE
	to-12-bit: func [offset [integer!]][
		#{00000FFF} and debase/base to-hex offset 16
	]
	
	to-shift-imm: func [value [integer!]][
		reverse to-bin32 shift/left value 7
	]

	instruction-buffer: make binary! 4
	
	f-inc: func [op [binary!] idx [integer!]][
		either zero? idx [op][op or debase/base to-hex shift/left idx 12 16]
	]
	
	;-- Overloaded emit to print reversed binary series for easier reading
	emit: func [bin [binary! char! block!]][
		if verbose >= 4 [print [">>>emitting code:" mold reverse copy bin]]
		append emitter/code-buf bin
	]

	emit-i32: func [bin [binary! char! block!]] [
		;; To allow more natural emission of 32-bit instructions, "emit-i32"
		;; collects data in big-endian and emits it as 32-bit chunks in the
		;; target's native endianness.
		insert tail instruction-buffer bin
		if 4 <= length? instruction-buffer [
			emit to-bin32 to integer! take/part instruction-buffer 4
		]
	]
	
	;-- Polymorphic code generation
	emit-poly: func [opcode [binary!] /with offset [integer!]][
		if with 	 [opcode: opcode or to-12-bit offset]
		if width = 1 [opcode: opcode or byte-flag]	;-- 16-bit access not supported
		emit-i32 opcode
	]
	
	rotate-left: func [value [integer!] bits [integer!]][
		either bits < 4 [
			switch bits [
				0 [value]
				1 [(shift/left value and 255 2) or shift/logical value 30]
				2 [(shift/left value and 16 4) or shift/logical value 28]
				3 [(shift/left value and 3 6) or shift/logical value 26]
			]
		][
			shift/logical value 32 - (bits * 2)		;-- * 2 => rotation on even positions
		]
	]
	
	ror-position?: func [value [integer!] /local c][
		;-- Test if an integer can be represented using the 8-bit + 4-bit-ROR format
		c: 0
		foreach mask [
			255  									;-- 2#{00000000000000000000000011111111}
			-1073741761								;-- 2#{11000000000000000000000000111111}
			-268435441								;-- 2#{11110000000000000000000000001111}
			-67108861								;-- 2#{11111100000000000000000000000011}
			-16777216								;-- 2#{11111111000000000000000000000000}
			1069547520								;-- 2#{00111111110000000000000000000000}
			267386880								;-- 2#{00001111111100000000000000000000}
			66846720								;-- 2#{00000011111111000000000000000000}
			16711680								;-- 2#{00000000111111110000000000000000}
			4177920									;-- 2#{00000000001111111100000000000000}
			1044480									;-- 2#{00000000000011111111000000000000}
			261120									;-- 2#{00000000000000111111110000000000}
			65280									;-- 2#{00000000000000001111111100000000}
			16320									;-- 2#{00000000000000000011111111000000}
			4080									;-- 2#{00000000000000000000111111110000}
			1020									;-- 2#{00000000000000000000001111111100}
		][
			if value and mask = value [return c]
			c: c + 1
		]
		none
	]

	emit-load-imm32: func [value [integer! char!] /reg n [integer!] /local neg? bits opcode][
		value: to integer! value
		if neg?: negative? value [value: complement value]

		either bits: ror-position? value [	
			opcode: rejoin [						;-- MOVS r0|rN, #imm8, bits	; v = imm8 (ROR bits)x2
				#{e3} 
				pick [#{f0} #{b0}] neg?				;-- emit MVNS instead, if required
				to char! bits
				to char! rotate-left value bits
			]
			if reg [opcode: opcode or debase/base to-hex shift/left n 12 16]
			emit-i32 opcode
		][
			opcode: #{e59f0000}						;-- LDR r0|rN, [pc, #offset]
			if reg [opcode: opcode or debase/base to-hex shift/left n 12 16]
			
			pools/collect/with either neg? [complement value][value] opcode
		]
	]
	
	emit-op-imm32: func [opcode [binary!] value [integer! char!] /local bits][
		opcode: copy opcode
		either bits: ror-position? value: to integer! value [
			opcode/3: (to char! opcode/3) or to char! bits
			opcode/4: to char! rotate-left value bits
		][
			pools/collect/with value #{e59f3000}	;-- LDR r3, [pc, #offset]
			opcode/1: #"^(FD)" and to char! opcode/1
			opcode/4: #"^(03)"
		]
		emit-i32 opcode
	]
	
	emit-float: func [d-code [binary!] s-code [binary!]][
		emit-i32 either width = 8 [d-code][s-code]
	]
	
	emit-load-local: func [opcode [binary!] offset [integer!] /float][
		if negative? offset [
			opcode: copy opcode
			opcode/2: #"^(7F)" and opcode/2			;-- clear bit 23 (U)
		]
		if float [offset: offset / 4]
		offset: to-12-bit abs offset
		;if alt [opcode: opcode or #{00001000}]		;-- use r1 instead of r0 
		emit-i32 opcode or offset
	]
	
	emit-float-variable: func [
		name [word! object!] gcode [binary!] lcode [binary!]
		/local offset
	][
		if object? name [name: compiler/unbox name]

		either offset: select emitter/stack name [	;-- local variable case
			emit-load-local/float lcode offset
		][											;-- global variable case
			pools/collect/spec/with 0 name #{e59f3000}	;-- LDR r3, [pc, #offset]
			if PIC? [emit-i32 #{e0833009}]				;-- ADD r3, sb
			emit-i32 gcode
		]
	]

	emit-variable: func [
		name  [word! object!]
		gcode [binary! block! none!]
		pcode [binary! block! none!]
		lcode [binary! block!]
		/alt										;-- use alternative register (r1)
		/local offset opcode Rn
	][
		if object? name [name: compiler/unbox name]

		either offset: select emitter/stack name [	;-- local variable case
			emit-load-local lcode offset
		][											;-- global variable case
			opcode: #{e59f0000}
			
			either alt [
				opcode: opcode or #{00001000}		;-- use r1 instead of r0
			][
				if all [gcode not zero? Rn: gcode/3 and #"^(F0)"][
					opcode: copy opcode
					opcode/3: to char! Rn			;-- use same Rn
				]
			]
			pools/collect/spec/with 0 name opcode	;-- LDR r0|r1|Rn, [pc, #offset]
			opcode: get pick [pcode gcode] PIC?
			if opcode [emit-i32 opcode]
		]
	]
	
	emit-variable-64: func [
		name [word!] gcode [binary!] l-low [binary!] l-high [binary!]
	][
		if object? name [name: compiler/unbox name]
		
		either offset: select emitter/stack name [	;-- local variable case
			emit-load-local l-low offset
			emit-load-local l-high offset + 4
		][
			pools/collect/spec/with 0 name #{e59f2000}	;-- LDR r2, [pc, #offset]
			if PIC? [emit-i32 #{e0822009}]				;-- ADD r2, sb
			emit-i32 gcode
		]
	]
	
	emit-variable-poly: func [						;-- polymorphic variable access generation
		name [word! object!]
		g-code [binary!]							;-- opcodes for global variables
		p-code [binary! none!]						;-- opcodes for global variables
		l-code [binary! block!]						;-- opcodes for local variables
		/alt
	][
		with-width-of name [
			if width = 1 [
				g-code: g-code or byte-flag
				if p-code [p-code: p-code or byte-flag]
				l-code: l-code or byte-flag
			]
			either alt [
				emit-variable/alt name g-code p-code l-code
			][
				emit-variable name g-code p-code l-code
			]
			if all [
				PIC?
				none? p-code
				none? select emitter/stack name
			][										;-- no specific PIC opcode case (LDM/STM)
				emit-i32 pick [
					#{e0811009}						;-- ADD r1, sb
					#{e0800009}						;-- ADD r0, sb
				] to logic! alt
				emit-i32 g-code
			]
		]
	]
	
	emit-load-symbol: func [name [word!]][
		emit-variable name
			#{e5900000}								;-- LDR r0, [r0]		; global
			#{e7900009}								;-- LDR r0, [r0, sb]	; PIC
			#{e59b0000}								;-- LDR r0, [fp, #[-]n]	; local
	]
	
	emit-move-alt: does [emit-i32 #{e1a01000}]		;-- MOV r1, r0

	emit-swap-regs: func [/alt][
		either alt [
			emit-i32 #{e1a0c002}					;-- MOV r12, r2
			emit-i32 #{e1a02000}					;-- MOV r2, r0
			emit-i32 #{e1a0000c}					;-- MOV r0, r12	
		][
			emit-i32 #{e1a0c001}					;-- MOV r12, r1
			emit-move-alt
			emit-i32 #{e1a0000c}					;-- MOV r0, r12
		]
	]
	
	emit-move-path-alt: does [
		emit-i32 #{e1a02000}						;-- MOV r2, r0
	]
	
	emit-save-last: does [
		last-saved?: yes
		either find [float! float64!] compiler/last-type/1 [
			emit-i32 #{e92d0003}					;-- PUSH {r0,r1}
		][
			emit-i32 #{e92d0001}					;-- PUSH {r0}
		]
	]

	emit-restore-last: does [
		unless find [float! float64! float32!] compiler/last-type/1 [
			emit-i32 #{e8bd0002}		   			;-- POP {r1}
		]
	]

	emit-casting: func [value [object!] alt? [logic!] /local old type][
		type: compiler/get-type value/data	
		case [
			value/type/1 = 'logic! [
				if verbose >= 3 [print [">>>converting from" mold/flat type/1 "to logic!"]]
				old: width
				set-width/type type/1
				either alt? [
					if width = 1 [										; 16-bit not supported
						emit-i32 #{e20110ff}		;-- AND r1, r1, #ff
					]
					emit-i32 #{e3510000}			;-- CMP r1, 0
					emit-i32 #{13a01001}			;-- MOVNE r1, #1
				][
					if width = 1 [										; 16-bit not supported
						emit-i32 #{e20000ff}		;-- AND r0, r0, #FF
					]
					emit-i32 #{e3500000}			;-- CMP r0, 0
					emit-i32 #{13a00001}			;-- MOVNE r0, #1
				]
				width: old
			]
			all [value/type/1 = 'integer! type/1 = 'byte!][
				if verbose >= 3 [print ">>>converting from byte! to integer! "]
				emit-i32 pick [
					#{e20110ff}						;-- AND r1, r1, #ff				
					#{e20000ff}						;-- AND r0, r0, #ff
				] alt?
			]
			all [find [float! float64!] value/type/1 find [float32! integer!] type/1][
				if verbose >= 3 [print [">>>converting from" mold/flat type/1 "to float!"]]
				either alt? [
					emit-i32 #{ee001a10}			;-- FMSR s0, r1
				][
					emit-i32 #{ee000a10}			;-- FMSR s0, r0
				]
				emit-i32 #{eeb70ac0}				;-- FCVTDS d0, s0
				emit-i32 #{ec510b10}				;-- FMRRD r0, r1, d0
			]
			all [value/type/1 = 'float32! find [float! float64!] type/1][
				if verbose >= 3 [print [">>>converting from float! to float32!"]]
				; @@ handle alt case?
				emit-i32 #{ec410b10}				;-- FMDRR d0, r1, r0
				emit-i32 #{eeb70bc0}				;-- FCVTSD s0, d0
				emit-i32 #{ee100a10}				;-- FMRS r0, s0
			]
		]
	]
	
	emit-load-literal: func [type [block! none!] value][
		unless type [type: compiler/get-type value]
		emit-load-literal-ptr second emitter/store-value none value type
	]
	
	emit-load-literal-ptr: func [spec [block!]][
		pools/collect/spec 0 spec					;-- r0: value
		if PIC? [emit-i32 #{e0800009}]				;-- ADD r0, sb
	]
	
	emit-access-register: func [reg [word!] set? [logic!] value /local opcode][
		if verbose >= 3 [print [">>>emitting ACCESS-REGISTER" mold value]]
		if all [set? not tag? value][emit-load value]

		unless reg = 'r0 [
			opcode: copy #{e1a00000}
			reg: to integer! next form reg
			either set? [
				opcode/3: to char! shift/left reg 4
			][
				opcode/4: to char! reg
			]
			emit-i32 opcode							;-- MOV <reg>, r0	; set
		]											;-- MOV r0, <reg>	; get
	]
	
	emit-fpu-get: func [
		/type
		/options option [word!]
		/masks mask [word!]
		/cword
		/local value bit 
	][
		unless type [
			emit-i32 #{eef10a10}					;-- FMRX r0, FPSCR
		]
		case [
			type [
				; hardcoded value for now (FPU_VFP)
				emit-load-imm32 3					;-- MOV r0, <FPU_TYPE_VFP>
			]
			options [
				set [value bit] switch/default option [
					rounding  		[[#{00C00000} 22]]
					flush-to-zero	[[#{01000000} 24]]
					NaN-mode		[[#{02000000} 25]]
				][
					compiler/throw-error ["invalid FPU option name:" option]
				]
				emit-op-imm32 #{e2000000} to integer! value  ;-- AND r0, r0, #mask
			]
			masks [
				bit: switch/default mask [
					precision	[12]
					underflow	[11]
					overflow	[10]
					zero-divide [9]
					denormal	[15]
					invalid-op  [8]
				][
					compiler/throw-error ["invalid FPU mask name:" mask]
				]
				emit-op-imm32 #{e2000000} shift/left 1 bit  ;-- AND r0, r0, #mask
			]
			;cword []									;-- control word is already in eax
		]
		unless any [type cword][						;-- align result on right side
			emit-i32 #{e1a00020} or to-shift-imm bit	;-- LSR r0, r0, #bit
			if masks [emit-i32 #{e2200001}]				;-- EOR r0, #1		; invert 0<=>1
		]
	]

	emit-fpu-set: func [
		value
		/options option [word!]
		/masks mask [word!]
		/cword
		/local bit
	][
		value: to integer! value
		unless cword [emit-i32 #{eef10a10}]			;-- FMRX r0, FPSCR
		
		case [
			options [
				set [mask bit] switch/default option [
					rounding  		[[#{00C00000} 22]]
					flush-to-zero	[[#{01000000} 24]]
					NaN-mode		[[#{02000000} 25]]
				][
					compiler/throw-error ["invalid FPU option name:" option]
				]
				emit-op-imm32 #{e2000000} complement to integer! mask  ;-- AND r0, r0, #mask
				emit-op-imm32 #{e3800000} shift/left to integer! value bit	;-- OR r0, r0, LSL #value, #bit
			]
			masks [
				bit: switch/default mask [
					precision	[12]
					underflow	[11]
					overflow	[10]
					zero-divide [9]
					denormal	[15]
					invalid-op  [8]
				][
					compiler/throw-error ["invalid FPU mask name:" mask]
				]
				emit-op-imm32 #{e3800000} shift/left 1 bit  ;-- OR r0, r0, #mask
			]
		]
		emit-i32 #{eee10a10}						;-- FMXR FPSCR, r0
	]
	
	emit-fpu-update: emit-fpu-init: none			;-- not used for now
	
	emit-get-pc: does [
		emit-i32 #{e1a0000f}						;-- MOV r0, pc
	]

	emit-set-stack: func [value /frame][
		if verbose >= 3 [print [">>>emitting SET-STACK" mold value]]
		unless tag? value [emit-load value]
		either frame [
			emit-i32 #{e1a0b000}					;-- MOV fp, r0
		][
			emit-i32 #{e1a0d000}					;-- MOV sp, r0
		]
	]

	emit-get-stack: func [/frame][
		if verbose >= 3 [print ">>>emitting GET-STACK"]
		either frame [
			emit-i32 #{e1a0000b}					;-- MOV r0, fp
		][
			emit-i32 #{e1a0000d}					;-- MOV r0, sp
		]
	]

	emit-pop: does [
		if verbose >= 3 [print ">>>emitting POP"]
		emit-i32 #{e8bd0001}						;-- POP {r0}
	]
	
	emit-pop-float: func [idx [integer!] /with type [block!]][
		if with [width: select emitter/datatypes type/1]
		emit-float
			f-inc #{ed9d0b00} idx	;-- FLDD d<idx>, [sp]		; double precision float
			f-inc #{ed9d0a00} idx	;-- FLDS s<idx>, [sp]		; single precision float
			
		emit-i32 join #{e28dd0}		;-- ADD sp, sp, width		; adjust stack pointer
			to char! width
	]
	
	emit-push-float: func [idx [integer!] type [block!]][
		width: select emitter/datatypes type/1
		emit-float
			f-inc #{ed8d0b00} idx	;-- FSTD [sp], d<idx>		; double precision float
			f-inc #{ed8d0a00} idx	;-- FSTS [sp], s<idx>		; single precision float

		emit-i32 join #{e24dd0}		;-- SUB sp, sp, width		; adjust stack pointer
			to char! width
	]
	
	emit-not: func [value [word! char! tag! integer! logic! path! string! object!] /local opcodes type boxed][
		if verbose >= 3 [print [">>>emitting NOT" mold value]]

		if object? value [boxed: value]
		value: compiler/unbox value
		if block? value [value: <last>]

		opcodes: [
			logic!	 [emit-i32 #{e2200001}]			;-- EOR r0, #1		; invert 0<=>1
			byte!	 [emit-i32 #{e1e00000}]			;-- MVN r0, r0
			integer! [emit-i32 #{e1e00000}]			;-- MVN r0, r0
		]
		switch type?/word value [
			logic! [
				emit-load not value
			]
			char! [
				emit-load value
				do opcodes/byte!
			]
			integer! [
				emit-load value
				do opcodes/integer!
			]
			word! [
				emit-load value
				type: either boxed [
					emit-casting boxed no
					boxed/type/1
				][
					first compiler/resolve-aliased compiler/get-variable-spec value
				]
				if find [pointer! c-string! struct!] type [ ;-- type casting trap
					type: 'logic!
				]
				switch type opcodes
			]
			tag! [
				if boxed [
					emit-casting boxed no
					compiler/last-type: boxed/type
				]
				switch compiler/last-type/1 opcodes
			]
			string! [								;-- type casting trap
				emit-load value
				if boxed [emit-casting boxed no]
				do opcodes/logic!
			]
			path! [
				emitter/access-path value none
				either boxed [
					emit-casting boxed no
					switch boxed/type/1 opcodes 
				][
					type: compiler/resolve-path-type value
					compiler/last-type: type
					switch type/1 opcodes
				]
			]
		]
	]
	
	emit-boolean-switch: does [
		emit-i32 #{e3a00000}						;--		  MOV r0, #0	; (FALSE)
		emit-i32 #{ea000000}						;--		  B _exit
		emit-i32 #{e3a00001}						;--		  MOV r0, #1	; (TRUE)
													;-- _exit:
		reduce [4 12]								;-- [offset-TRUE offset-FALSE]
	]

	emit-load: func [
		value [char! logic! integer! word! string! path! paren! get-word! object! decimal!]
		/alt
		/with cast [object!]
		/local type offset spec
	][
		if verbose >= 3 [print [">>>loading" mold value]]

		switch type?/word value [
			char! [
				emit-load-imm32 to integer! value
			]
			logic! [
				emit-load-imm32 to integer! value
			]
			integer! [
				emit-load-imm32 value
			]
			decimal! [
				either all [cast cast/type/1 = 'float32!][
					emit-load-imm32 to integer! IEEE-754/to-binary32 value
				][
					spec: emitter/store-value none value [float!]
					pools/collect/spec/with 0 spec/2 #{e59f3000}	;-- LDR r3, [pc, #offset]
					if PIC? [emit-i32 #{e0833009}]					;-- ADD r3, sb
					emit-i32 #{e8930003} 							;-- LDM r3, {r0,r1}
				]
			]
			word! [
				type: compiler/get-variable-spec value
				either find [float! float64!] type/1 [
					emit-variable-poly value
						#{e8900003} 				;-- LDM r0, {r0,r1}		; global
						none
						#{e59b0000}					;-- LDR r0, [fp, #[-]n]	; local, low bits @@ test!!
					
					if offset: select emitter/stack value [
						emit-load-local #{e59b1000} offset + 4	;-- LDR r1, [fp, #[-]n+4]	; local, high bits
					]
				][
					either alt [
						emit-variable-poly/alt value
							#{e5911000}				;-- LDR r1, [r1]		; global
							#{e7911009}				;-- LDR r1, [r1, sb]	; PIC
							#{e59b1000}				;-- LDR r1, [fp, #[-]n]	; local
					][
						emit-variable-poly value
							#{e5900000} 			;-- LDR r0, [r0]		; global
							#{e7900009}				;-- LDR r0, [r0, sb]	; PIC
							#{e59b0000}				;-- LDR r0, [fp, #[-]n]	; local
					]
				]
			]
			get-word! [
				either offset: select emitter/stack to word! value [
					emit-i32 either negative? offset [
						#{e24b00}					;-- SUB r0, fp, n
					][
						#{e28b00}					;-- ADD r0, fp, n
					]
					emit-i32 to-bin8 abs offset
				][
					pools/collect/spec 0 value
					if PIC? [emit-i32 #{e0800009}]	;-- ADD r0, sb
				]
			]
			string! [
				emit-load-literal [c-string!] value
			]
			path! [
				emitter/access-path value none
			]
			paren! [
				emit-load-literal none value
			]
			object! [
				unless any [block? value/data value/data = <last>][
					either alt [
						emit-load/alt/with value/data value
					][
						emit-load/with value/data value
					]
					set-width value
				]
			]
		]
	]
	
	emit-store: func [
		name [word!] value [char! logic! integer! word! string! paren! tag! get-word! decimal!]
		spec [block! none!]
		/local store-qword store-word store-byte type
	][
		if verbose >= 3 [print [">>>storing" mold name mold value]]
		if value = <last> [value: 'last]			;-- force word! code path in switch block
		if logic? value [value: to integer! value]	;-- TRUE -> 1, FALSE -> 0

		store-qword: [
			emit-variable-64 name
				#{e8820003}							;-- STM r2, {r0,r1}			; global, low + high
				#{e58b0000}							;-- STR r0, [fp, #[-]n]		; local, low bits
				#{e58b1000}							;-- STR r1, [fp, #[-]n]		; local, high bits
		]
		store-word: [
			emit-variable/alt name
				#{e5010000}							;-- STR r0, [r1]			; global
				#{e7810009}							;-- STR r0, [r1, sb]		; PIC
				#{e58b0000}							;-- STR r0, [fp, #[-]n]		; local
		]
		store-byte: [
			emit-variable/alt name
				#{e5410000}							;-- STRB r0, [r1]			; global
				#{e7c10009}							;-- STRB r0, [r1, sb]		; PIC
				#{e5cb0000}							;-- STRB r0, [fp, #[-]n]	; local
		]

		switch type?/word value [
			char! [
				do store-byte
			]
			integer! [
				do store-word
			]
			decimal! [
				type: compiler/get-variable-spec name
				either type/1 = 'float32! [
					do store-word
				][
					do store-qword
				]
			]
			word! [
				set-width name
				switch width [
					1 [do store-byte]
					4 [do store-word]
					8 [do store-qword]
				]
			]
			get-word! [
				unless find emitter/stack to word! value [
					pools/collect/spec 0 value
					if PIC? [emit-i32 #{e0800009}]	;-- ADD r0, sb
				]
				do store-word
			]
			string! paren! [
				do store-word
			]
		]
	]
	
	emit-init-path: func [name [word!]][
		emit-load-symbol name
	]

	emit-access-path: func [
		path [path! set-path!] spec [block! none!] /short /local offset type saved
	][
		if verbose >= 3 [print [">>>accessing path:" mold path]]

		unless spec [
			spec: second compiler/resolve-type path/1
			emit-load path/1
		]
		if short [return spec]

		saved: width
		type: first compiler/resolve-type/with path/2 spec
		set-width/type type							;-- adjust operations width to member value size

		offset: emitter/member-offset? spec path/2
		if width = 8 [								;-- 64-bit value case
			emit-poly/with #{e5901000} offset + 4	;-- LDR r1, [r0, offset+4]	; high bits
		]
		emit-poly/with #{e5900000} offset			;-- LDR[B] r0, [r0, offset]
		width: saved
	]
	
	emit-load-index: func [idx [word!]][
		unless compiler/local-variable? idx [idx: compiler/resolve-ns idx]
		emit-variable idx
			#{e5933000}								;-- LDR r3, [r3]		; global
			#{e7933009}								;-- LDR r3, [r3, sb]	; PIC
			#{e59b3000}								;-- LDR r3, [fp, #[-]n]	; local
		emit-i32 #{e2433001}						;-- SUB r3, r3, #1		; one-based index
	]

	emit-c-string-path: func [path [path! set-path!] parent [block! none!] /local opcodes idx][
		unless parent [emit-init-path path/1]
		opcodes: pick [[							;-- store path opcodes --
			#{e5402000}								;-- STRB r2, [r0]		; first
			#{e7c02003}								;-- STRB r2, [r0, r3] 	; nth | variable index
		][											;-- load path opcodes --
			#{e5500000}								;-- LDRB r0, [r0]		; first
			#{e7d00003}								;-- LDRB r0, [r0, r3]	; nth | variable index
		]] set-path? path

		either integer? idx: path/2 [
			either zero? idx: idx - 1 [				;-- indexes are one-based
				emit-i32 opcodes/1
			][
				emit-load-imm32/reg idx 3			;-- LDR r3, #idx
				emit-i32 opcodes/2
			]
		][
			emit-load-index idx
			emit-i32 opcodes/2
		]
	]
	
	emit-pointer-path: func [
		path [path! set-path!] parent [block! none!] /local opcodes idx type scale
	][
		opcodes: pick [[							;-- store path opcodes --
			#{e5002000}								;-- STR[B] r2, [r0]
			#{e7802003}								;-- STR[B] r2, [r0, r3]
			#{e0822003}								;-- ADD r2, r2, r3
			#{e8820003}								;-- STM r2, {r0,r1}
		][											;-- load path opcodes --
			#{e5900000}								;-- LDR[B] r0, [r0]
			#{e7900003}								;-- LDR[B] r0, [r0, r3]
			#{e0800003}								;-- ADD r0, r0, r3
			#{e8900003} 							;-- LDM r0, {r0,r1}
		]] set-path? path

		type: either parent [
			compiler/resolve-type/with path/1 parent
		][
			emit-init-path path/1
			compiler/resolve-type path/1
		]
		set-width/type type/2/1						;-- adjust operations width to pointed value size
		idx: either path/2 = 'value [1][path/2]
		scale: emitter/size-of? type/2/1

		if all [set-path? path not parent width = 8][
			emit-swap-regs/alt
		]

		either integer? idx [
			either zero? idx: idx - 1 [				;-- indexes are one-based
				either width = 8 [
					emit-i32 opcodes/4
				][
					emit-poly opcodes/1
				]
			][
				emit-load-imm32/reg idx * scale 3	;-- LDR r3, #idx
				either width = 8 [
					emit-i32 opcodes/3
					emit-i32 opcodes/4
				][
					emit-poly opcodes/2
				]
			]
		][
			emit-load-index idx
			if scale > 1 [
				emit-i32 #{e1a03003}				;-- LSL r3, r3, #log2(scale)
					or debase/base to-hex shift/left power-of-2? scale 7 16
			]
			either width = 8 [
				emit-i32 opcodes/3
				emit-i32 opcodes/4
			][
				emit-poly opcodes/2
			]
		]
	]
	
	emit-load-path: func [path [path!] type [word!] parent [block! none!] /local idx][
		if verbose >= 3 [print [">>>loading path:" mold path]]

		switch type [
			c-string! [emit-c-string-path path parent]
			pointer!  [emit-pointer-path  path parent]
			struct!   [emit-access-path   path parent]
		]
	]
	
	emit-store-path: func [path [set-path!] type [word!] value parent [block! none!] /local idx offset size][
		if verbose >= 3 [print [">>>storing path:" mold path mold value]]
		
		size: emitter/size-of? compiler/get-type value
													;-- @@ separate 64/32-bit conventions, too messy...
		unless value = <last> [
			if parent [emit-i32 #{e1a02000}]		;-- MOV r2, r0		; save value/address
			emit-load value							; @@ generates duplicate value loading sometimes
			if all [not parent size = 8][
				emit-i32 #{e1a02000}				;-- MOV r2, r0		; save value/address
			]
			if size <> 8 [emit-swap-regs/alt]			;-- save value/restore address
		]

		switch type [
			c-string! [emit-c-string-path path parent]
			pointer!  [emit-pointer-path  path parent]
			struct!   [
				unless parent [
					parent: emit-access-path/short path parent
					if size = 8 [emit-swap-regs/alt] ;-- save value/restore address
				]
				type: first compiler/resolve-type/with path/2 parent
				set-width/type type					;-- adjust operations width to member value size

				either zero? offset: emitter/member-offset? parent path/2 [
					either width = 8 [
						emit-i32 #{e8820003}		;-- STM r2, {r0,r1}		; r2 = address
					][
						emit-poly #{e5002000}		;-- STR r2, [r0]		; r2 = value
					]
				][
					emit-load-imm32/reg offset 3
					either width = 8 [
						emit-i32 #{e0822003}		;-- ADD r2, r2, r3
						emit-i32 #{e8820003}		;-- STM r2, {r0,r1}		; r2 = address
					][
						emit-poly #{e7802003}		;-- STR r2, [r0, r3]	; r2 = value
					]
				]
			]
		]
	]
	
	patch-exit-call: func [code-buf [binary!] ptr [integer!] exit-point [integer!]][
		change 
			at code-buf ptr
			reverse to-bin24 shift exit-point - ptr - (2 * branch-offset-size) 2
	]
	
	emit-exit: does [
		if verbose >= 3 [print ">>>exiting function"]
		emit-reloc-addr emitter/exits
		emit-i32 #{ea000000}						;-- B <disp>
	]
	
	emit-branch: func [
		code 	[binary!]
		op 		[word! block! logic! none!]
		offset  [integer! none!]
		/back?
		/local distance opcode jmp
	][
		distance: (length? code) - (any [offset 0]) - 4	;-- offset from the code's head
		if back? [distance: negate distance + 12]	;-- 8 (PC offset) + one instruction
		
		op: either not none? op [					;-- explicitly test for none
			op: case [
				block? op [							;-- [cc] => keep
					op: op/1
					either logic? op [pick [= <>] op][op]	;-- [logic!] or [cc]
				]
				logic? op [pick [= <>] op]			;-- test for TRUE/FALSE
				'else 	  [opposite? op]			;-- 'cc => invert condition
			]
			either '- = third op: find conditions op [	;-- lookup the code for the condition
				op/2								;-- condition defined only for signed
			][
				pick op pick [2 3] signed?			;-- choose code between signed and unsigned
			]
		][
			#{e0}									;-- unconditional jump
		]
		unless back? [
			if same? head code emitter/code-buf [
				pools/insert-jmp-point emitter/tail-ptr distance	;-- update code indexes affected by the insertion
			]
		]
		opcode: reverse rejoin [
			op or #{0a} to-bin24 shift distance 2
		]		
		insert any [all [back? tail code] code] opcode
		4											;-- opcode length
	]

	emit-push: func [
		value [char! logic! integer! word! block! string! tag! path! get-word! object! decimal!]
		/with cast [object!]
		/cdecl
		/local push-last push-last64 spec type
	][
		if verbose >= 3 [print [">>>pushing" mold value]]
		if block? value [value: <last>]
		
		push-last:  [emit-i32 #{e92d0001}]			;-- PUSH {r0}
		push-last64: [emit-i32 #{e92d0003}]			;-- PUSH {r0,r1}

		switch type?/word value [
			tag! [									;-- == <last>
				type: either cast [cast/type][compiler/last-type]
				do either find [float! float64!] type/1 [
					push-last64
				][
					push-last
				]
			]
			logic! [
				emit-load-imm32 to integer! value	;-- MOV r0, #0|#1
				do push-last
			]
			char! [
				emit-load-imm32 to integer! value	;-- MOV r0, #imm8
				do push-last
			]
			integer! [
				emit-load-imm32/reg value 3
				emit-i32 #{e92d0008}				;-- PUSH {r3}
			]
			decimal! [
				either all [cast cast/type/1 = 'float32! not cdecl][
					emit-load-imm32 to integer! IEEE-754/to-binary32 value
					do push-last
				][
					spec: emitter/store-value none value [float!]
					pools/collect/spec/with 0 spec/2 #{e59f2000}	;-- LDR r2, [pc, #offset]
					if PIC? [emit-i32 #{e0822009}]	;-- ADD r2, sb
					emit-i32 #{e8920003} 			;-- LDM r2, {r0,r1}
					emit-i32 #{e92d0003}			;-- PUSH {r0,r1}
				]
			]
			word! [
				type: compiler/get-variable-spec value
				either any [
					find [float! float64!] type/1 
					all [cast find [float! float64!] cast/type/1]
				][
					emit-load value
					do push-last64
				][
					emit-load-symbol value
					do push-last
				]
			]
			get-word! [
				emit-load value
				do push-last						;-- PUSH &value
			]
			string! [
				emit-load-literal [c-string!] value
				do push-last						;-- PUSH value
			]
			path! [
				emitter/access-path value none
				compiler/last-type: either cast [
					emit-casting cast no
					cast/type
				][
					compiler/resolve-path-type value
				]
				emit-push <last>
			]
			object! [
				unless path? value/data [
					emit-casting value no
				]
				either cdecl [
					emit-push/with/cdecl value/data value
				][
					emit-push/with value/data value
				]
			]
		]
	]
	
	emit-bitshift-op: func [name [word!] a [word!] b [word!] args [block!] /local c value][
		switch b [
			ref [
				emit-variable args/2
					#{e5d03000}						;-- LDRB r3, [r0]			; global
					#{e7d03009}						;-- LDRB r3, [r0, sb]		; PIC
					#{e5db3000}						;-- LDRB r3, [fp, #[-]n]	; local
			]
			reg [emit-i32 #{e1a03001}]				;-- MOV r3, r1
		]
		opcode: select [
			<<  [
				#{e1a00000}							;-- LSL r0, r0, #b
				#{e1a00310}							;-- LSL r0, r0, r3
			]
			>>  [
				#{e1a00040}							;-- ASR r0, r0, #b
				#{e1a00350}							;-- ASR r0, r0, r3
			]
			-** [
				#{e1a00020}							;-- LSR r0, r0, #b
				#{e1a00330}							;-- LSR r0, r0, r3
			]
		] name
	
		emit-i32 either b = 'imm [
			opcode/1 or to-shift-imm args/2
		][
			opcode/2
		]
		
		if b = 'imm [
			c: select [1 7 2 15 4 31] width
			value: compiler/unbox args/2		
			unless all [0 <= value value <= c][		
				compiler/backtrack name
				compiler/throw-error rejoin [
					"a value in 0-" c " range is required for this shift operation"
				]
			]
		]
	]
	
	emit-bitwise-op: func [name [word!] a [word!] b [word!] args [block!] /local code][		
		code: select [
			and [#{e0000001}]						;-- AND r0, r0, r1	; commutable op
			or  [#{e1800001}]						;-- OR  r0, r0, r1	; commutable op
			xor [#{e0200001}]						;-- EOR r0, r0, r1	; commutable op
		] name

		switch b [
			imm [
				emit-load-imm32/reg compiler/unbox args/2 1	;-- MOV r1, #value
				emit-i32 code						;-- <OP> r0, r0, r1
			]
			ref [
				emit-load/alt args/2
				if object? args/2 [emit-casting args/2 yes]
				emit-i32 code
			]
			reg [emit-i32 code]						;-- <OP> r0, r0, r1		; commutable op
		]
	]
	
	emit-comparison-op: func [name [word!] a [word!] b [word!] args [block!] /local op-poly arg2][
		op-poly: [
			switch width [
				1 [
					emit-i32 #{e1a03c00}			;-- MOV r3, r0, LSL #24
					emit-i32 #{e1533c01}			;-- CMP r3, r1, LSL #24
				]
				;2 []								;-- 16-bit not supported
				4 [emit-i32 #{e1500001}]			;-- CMP r0, r1		; not commutable op
			]
		]		
		arg2: either object? args/2 [compiler/cast args/2][args/2]
		
		switch b [
			imm [
				switch width [
					1 [
						emit-i32 join #{e35000}		;-- CMP r0, #imm8
							to char! arg2
					]
					;2 []							;-- 16-bit not supported
					4 [
						emit-load-imm32/reg arg2 1	;-- r1: arg2	
						emit-i32 #{e1500001}		;-- CMP r0, r1		; not commutable op
					]
				]
			]
			ref [
				emit-load/alt args/2
				if object? args/2 [emit-casting args/2 yes]
				do op-poly
			]
			reg [
				do op-poly
			]
		]
	]
	
	emit-math-op: func [
		name [word!] a [word!] b [word!] args [block!]
		/local mod? scale c type arg2 op-poly
	][
		;-- r0 = a, r1 = b
		if find mod-rem-op name [					;-- work around unaccepted '// and '%
			mod?: select mod-rem-func name			;-- convert operators to words (easier to handle)
			name: first [/]							;-- work around unaccepted '/ 
		]
		arg2: compiler/unbox args/2

		if all [
			find [+ -] name							;-- pointer arithmetic only allowed for + & -
			type: compiler/resolve-aliased compiler/resolve-expr-type args/1
			not compiler/any-pointer? compiler/resolve-expr-type args/2	;-- no scaling if both operands are pointers		
			scale: switch type/1 [
				pointer! [emitter/size-of? type/2/1]		  ;-- scale factor: size of pointed value
				struct!  [emitter/member-offset? type/2 none] ;-- scale factor: total size of the struct
			]
			scale > 1
		][
			either compiler/literal? arg2 [
				arg2: arg2 * scale					;-- 'b is a literal, so scale it directly
			][
				either b = 'reg [
					emit-swap-regs					;-- swap r0, r1		; put operands in right order
					emit-i32 #{e92d0002}			;-- PUSH {r1}		; save r1 (a) from corruption
				][									;-- 'b will now be stored in reg, so save 'a
					emit-i32 #{e92d0001}			;-- PUSH {r0}		; save r0 (a) from corruption
					emit-move-alt					;-- MOV r1, r0
					emit-load args/2
				]
				emit-math-op '* 'reg 'imm reduce [arg2 scale]	;@@ refactor that using barrel shifter
				emit-i32 #{e8bd0002}				;-- POP {r1}		; restore pointer in r1
				if name = '- [emit-swap-regs]		;-- swap r0, r1		; put operands in right order
				b: 'reg
			]
		]
		;-- r0 = a, r1 = b
		switch name [
			+ [
				op-poly: [emit-i32 #{e0800001}]		;-- ADD r0, r0, r1	; commutable op
				switch b [
					imm [
						emit-op-imm32 #{e2800000} arg2 ;-- ADD r0, r0, #value
					]
					ref [
						emit-load/alt arg2
						do op-poly
					]
					reg [do op-poly]
				]
			]
			- [
				op-poly: [emit-i32 #{e0400001}] 	;-- SUB r0, r0, r1	; not commutable op
				switch b [
					imm [
						emit-op-imm32 #{e2400000} arg2 ;-- SUB r0, r0, #value
					]
					ref [
						emit-load/alt arg2
						do op-poly
					]
					reg [do op-poly]
				]
			]
			* [
				op-poly: [emit-i32 #{e0000091}]		;-- MUL r0, r0, r1 	; commutable op
				switch b [
					imm [
						either all [
							not zero? arg2
							c: power-of-2? arg2		;-- trivial optimization for b=2^n
						][
							emit-i32 #{e1a00000}	;-- LSL r0, r0, #log2(b)
								or to-shift-imm c
						][
							emit-load-imm32/reg args/2 1	;-- MOV r1, #value
							do op-poly
						]
					]
					ref [
						emit-i32 #{e92d0002}		;-- PUSH {r1}	; save r1 from corruption
						emit-load/alt args/2
						do op-poly
						emit-i32 #{e8bd0002}		;-- POP {r1}
					]
					reg [do op-poly]
				]
			]
			/ [
				switch b [
					imm [
						emit-i32 #{e92d0002}		;-- PUSH {r1}	; save r1 from corruption
						emit-load-imm32/reg args/2 1 ;-- MOV r1, #value
					]
					ref [
						emit-i32 #{e92d0002}		;-- PUSH {r1}	; save r1 from corruption
						emit-load/alt args/2
					]
				]
				call-divide mod?
				
				if any [							;-- in case r1 was saved on stack
					all [b = 'imm any [mod? not c]]
					b = 'ref
				][
					emit-i32 #{e8bd0002}			;-- POP {r1}
				]
			]
		]
		;TBD: test overflow and raise exception ? (or store overflow flag in a variable??)
		; JNO? (Jump if No Overflow)
	]
	
	emit-integer-operation: func [name [word!] args [block!] /local a b sorted? left right][
		if verbose >= 3 [print [">>>inlining op:" mold name mold args]]

		set-width args/1							;-- set reg/mem access width
		set [a b] get-arguments-class args
		last-saved?: no								;-- reset flag

		;-- First operand processing
		left:  compiler/unbox args/1
		right: compiler/unbox args/2

		switch to path! reduce [a b] [
			imm/imm	[emit-load-imm32 left]			;-- MOV r0, a
			imm/ref [emit-load args/1]				;-- r0 = a
			imm/reg [								;-- r0 = b
				if path? right [
					emit-load args/2				;-- late path loading
				]
				emit-move-alt						;-- MOV r1, r0
				emit-load-imm32 left				;-- MOV r0, a		; r0 = a, r1 = b
			]
			ref/imm [emit-load args/1]
			ref/ref [emit-load args/1]
			ref/reg [								;-- r0 = b
				if path? right [
					emit-load args/2				;-- late path loading
				]
				emit-move-alt						;-- MOV r1, r0
				emit-load args/1					;-- r0 = a, r1 = b
			]
			reg/imm [								;-- r0 = a (or r1 = a if last-saved)
				if path? left [
					emit-load args/1				;-- late path loading
				]
				if last-saved? [emit-swap-regs]		;-- swap r0, r1	; r0 = a
			]
			reg/ref [								;-- r0 = a (or r1 = a if last-saved)
				if path? left [
					emit-load args/1				;-- late path loading
				]
				if last-saved? [emit-swap-regs]		;-- swap r0, r1	; r0 = a
			]
			reg/reg [								;-- r0 = b, r1 = a
				if path? left [
					if any [
						args/2 = <last>				;-- inlined statement
						block? right				;-- function call
					][				 				;-- r1 = b
						emit-swap-regs				;-- swap r0, r1
						sorted?: yes				;-- r0 = a, r1 = b
					]
					emit-load args/1				;-- late path loading
				]
				if path? right [
					emit-swap-regs					;-- swap r0, r1	; r0 = b, r1 = a
					emit-load args/2
				]
				unless sorted? [emit-swap-regs]		;-- swap r0, r1	; r0 = a, r1 = b
			]
		]
		if object? args/1 [emit-casting args/1 no]	;-- do runtime conversion if required

		;-- Operator and second operand processing
		either all [object? args/2 find [imm reg] b][
			emit-casting args/2 yes					;-- do runtime conversion if required
		][
			implicit-cast right
		]
		case [
			find comparison-op name [emit-comparison-op name a b args]
			find math-op	   name	[emit-math-op		name a b args]
			find bitwise-op	   name	[emit-bitwise-op	name a b args]
			find bitshift-op   name [emit-bitshift-op   name a b args]
		]
	]
	
	emit-vfp-casting: func [value [object!] /right [logic!] /local type][
		type: compiler/get-type value/data	
		case [
			all [find [float! float64!] value/type/1 find [float32! integer!] type/1][
				either right [
					emit-i32 #{eeb71ac1}			;-- FCVTDS d1, s2
				][
					emit-i32 #{eeb70ac0}			;-- FCVTDS d0, s0
				]
			]
			all [value/type/1 = 'float32! find [float! float64!] type/1][
				either right [
					emit-i32 #{eeb71bc1}			;-- FCVTSD s2, d1
				][
					emit-i32 #{eeb70bc0}			;-- FCVTSD s0, d0
				]
			]
		]
	]

	emit-float-operation: func [name [word!] args [block!] /local a b left right spec size saved][
		if verbose >= 3 [print [">>>inlining float op:" mold name mold args]]
		
		set [a b] get-arguments-class args

		;-- First operand processing
		left:  compiler/unbox args/1
		right: compiler/unbox args/2
		set-width args/1
		saved: width

		switch a [									;-- load left operand in d0 or s0
			imm [
				either width = 4 [
					emit-load-imm32/reg to integer! IEEE-754/to-binary32 left 3
					emit-i32 #{ee003a10}			;-- FMSR s0, r3
				][
					spec: emitter/store-value none args/1 compiler/get-type args/1
					pools/collect/spec/with 0 spec/2 #{e59f3000}	;-- LDR r3, [pc, #offset]
					if PIC? [emit-i32 #{e0833009}]	;-- ADD r3, sb
					emit-i32 #{ed930b00}			;-- FLDD d0, [r3]
				]
			]
			ref [
				set-width left
				either width = 8 [
					emit-float-variable args/1
						#{ed930b00} 				;-- FLDD d0, [r3]			; global
						#{ed9b0b00}					;-- FLDD d0, [fp, #[-]n]	; local
				][
					emit-float-variable args/1
						#{ed930a00} 				;-- FLDS s0, [r3]			; global
						#{ed9b0a00}					;-- FLDS s0, [fp, #[-]n]	; local
				]
				if object? args/1 [emit-vfp-casting args/1]
			]
			reg [
				if block? left [
					either b = 'reg [
						emit-pop-float 0
					][
					 	emit-float 
					 		#{ec410b10}				;-- FMDRR d0, r1, r0
					 		#{ee000a10}				;-- FMSR s0, r0
					]
				]
				if path? left [
					if all [b = 'reg not path? right][
						emit-push <last>			;-- push right result on stack
					]
					emit-load args/1				;-- late path loading
					emit-float 
						#{ec410b10}					;-- FMDRR d0, r1, r0
						#{ee000a10}					;-- FMSR s0, r0
				]
				if object? args/1 [emit-vfp-casting args/1]
			]
		]
	
		switch b [									;-- load right operand in d1 or s2
			imm [
				set-width args/2
				either width = 4 [
					emit-load-imm32/reg to integer! IEEE-754/to-binary32 right 3
					emit-i32 #{ee013a10}			;-- FMSR s2, r3
				][
					spec: emitter/store-value none args/2 compiler/get-type args/2
					pools/collect/spec/with 0 spec/2 #{e59f3000}	;-- LDR r3, [pc, #offset]
					if PIC? [emit-i32 #{e0833009}]	;-- ADD r3, sb
					emit-i32 #{ed931b00}			;-- FLDD d1, [r3]
				]
			]
			ref [
				set-width right
				either width = 8 [
					emit-float-variable args/2
						#{ed931b00} 				;-- FLDD d1, [r3]			; global
						#{ed9b1b00}					;-- FLDD d1, [fp, #[-]n]	; local
				][
					emit-float-variable args/2
						#{ed931a00} 				;-- FLDS s2, [r3]			; global
						#{ed9b1a00}					;-- FLDS s2, [fp, #[-]n]	; local
				]
				if object? args/2 [emit-vfp-casting/right args/2]
			]
			reg [
				set-width right
				if path? right [
					emit-load args/2
					emit-float 
						#{ec410b11}					;-- FMDRR d1, r1, r0
						#{ee010a10}					;-- FMSR s2, r0
				]
				if block? right [
					if path? left [emit-pop-float 0]
					emit-float 
						#{ec410b11}					;-- FMDRR d1, r1, r0
						#{ee010a10}					;-- FMSR s2, r0
				]
				if object? args/2 [emit-vfp-casting/right args/2]
			]
		]
		width: saved
		
		case [
			find comparison-op name [
				emit-float 							;-- load immediate from data segment
					#{eeb40b41}						;-- FCMPD d0, d1
					#{eeb40a41}						;-- FCMPS s0, s2
				emit-i32 #{eef1fa10}				;-- FMSTAT				; transfer flags to CPU
			]
			find math-op name [
				either width = 8 [
					either find mod-rem-op name [
						emit-i32 #{ee802b01}		;-- FDIVD  d2, d0, d1
						emit-i32 #{eebd4bc2}		;-- FTOSID s8, d2		; round towards 0
						emit-i32 #{eeb02b40}		;-- FCPYD  d2, d0		; d2 = dividend
						emit-i32 #{eeb80bc4}		;-- FSITOD d0, s8		; d0 = INT(q)
						emit-i32 #{ee002b41}		;-- FNMACD d2, d0, d1	; d2 = d2 - d0 * d1
					][
						emit-i32 switch name [		;-- double precision math
							+ [#{ee302b01}]			;-- FADDD d2, d0, d1
							- [#{ee302b41}]			;-- FSUBD d2, d0, d1
							* [#{ee202b01}]			;-- FMULD d2, d0, d1
							/ [#{ee802b01}]			;-- FDIVD d2, d0, d1
						]
					]
					emit-i32 #{ec510b12}			;-- FMRRD r0, r1, d2	; move result to CPU
				][
					either find mod-rem-op name [
						emit-i32 #{ee802a01}		;-- FDIVS  s4, s0, s2
						emit-i32 #{eebd4ac2}		;-- FTOSIS s8, s4		; round towards 0
						emit-i32 #{eeb02a40}		;-- FCPYS  s4, s0		; s4 = dividend
						emit-i32 #{eeb80ac4}		;-- FSITOS s0, s8		; s0 = INT(q)
						emit-i32 #{ee002a41}		;-- FNMACS s4, s0, s2	; s4 = s4 - s0 * s2
					][
						emit-i32 switch name [		;-- single precision math
							+ [#{ee302a01}]			;-- FADDS s4, s0, s2
							- [#{ee302a41}]			;-- FSUBS s4, s0, s2
							* [#{ee202a01}]			;-- FMULS s4, s0, s2
							/ [#{ee802a01}]			;-- FDIVS s4, s0, s2
						]
					]
					emit-i32 #{ee120a10}			;-- FMRS r0, s4			; move result to CPU
				]
			]
			true [
				compiler/throw-error "unsupported operation on floats"
			]
		]
	]
	
	emit-APCS-header: func [
		args [block!] cconv [word!] attribs [block! none!]
		/local reg bits offset type size stk freg
	][
		either args/1 = #custom [
			repeat reg min args/2/1 4 [
				emit-i32 #{e8bd00} 					;-- POP {rn[,rn+1]}
				emit-i32 to char! shift/left 1 reg - 1
			]
			stack-width * max 0 args/2/1 - 4		;-- return extra args on stack count
		][
			if issue? args/1 [args: args/2]
			reg: freg: stk: 0
		
			foreach arg reverse args [				;-- arguments are on stack in reverse order	
				if arg <> #_ [						;-- bypass place-holder marker
					type: compiler/get-type arg
					
					either all [
						compiler/job/ABI = 'hard-float
						find [float! float64! float32!] type/1
						any [none? attribs not find attribs 'variadic]	;-- 'typed is not using hf ABI
					][
						emit-pop-float/with freg type
					 	freg: freg + 1
					][
						size: either all [
							cconv = 'cdecl
							type/1 = 'float32!
						][
							8						;-- promote to C double
						][
							emitter/size-of? type
						]
						if reg >= 4 [stk: stk + any [size 4]] ;-- account for extra args on stack
															  ;-- ANY: workaround special variables from start.reds
						set [bits offset] either 8 = size [
							either reg <= 2 [
								if odd? reg [
									emit-load-imm32/reg 0 1
									reg: reg + 1	;-- start 64-bit value on even register
								]
								[3 2]				;-- use 2 regs
							][
								[0 2]				;-- no space in regs to store a 64-bit value
							]
						][
							[1 1]					;-- use 1 reg
						]

						if all [reg < 4 not zero? bits][
							emit-i32 #{e8bd00} 		;-- POP {rn[,rn+1]}
							emit-i32 to char! shift/left bits reg
						]

						reg: reg + offset
					]
				]
			]
			stk										;-- return extra args on stack count
		]
	]
	
	emit-hf-return: func [spec [block!] /local type][
		if all [
			compiler/job/ABI = 'hard-float
			find [float! float64! float32!] type: select spec first [return:]
		][
			width: select emitter/datatypes type/1
			emit-float
				#{ec510b10}							;-- FMRRD r0, r1, d0
				#{ee100a10}							;-- FMRS r0, s0
		]
	]

	emit-call-syscall: func [args [block!] fspec [block!] attribs [block! none!] /local extra][	; @@ check if it needs stack alignment too
		extra: emit-APCS-header args fspec/3 attribs
		emit-i32 #{e3a070}							;-- MOV r7, <syscall>
		emit-i32 to-bin8 last fspec
		emit-i32 #{ef000000}						;-- SVC 0		; @@ EABI syscall
		unless zero? extra [
			emit-op-imm32 #{e28dd000} extra			;-- ADD sp, sp, extra	; skip extra stack arguments
		]
		emit-hf-return fspec/4
	]
	
	emit-call-import: func [args [block!] fspec [block!] spec [block!] attribs [block! none!] /local extra type][
		extra: emit-APCS-header args fspec/3 attribs
		pools/collect/spec/with 0 spec #{e59fc000}	;-- MOV ip, #(.data.rel.ro + symbol_offset)
		if PIC? [emit-i32 #{e08cc009}]				;-- ADD ip, sb
		emit-i32 #{e59cc000}						;-- LDR ip, [ip]
		emit-i32 #{e12fff3c}						;-- BLX ip
		unless zero? extra [						;-- _next:
			emit-op-imm32 #{e28dd000} extra			;-- ADD sp, sp, extra	; skip extra stack arguments
		]
		emit-hf-return fspec/4
	]
	
	emit-call-native: func [
		args [block!] fspec [block!] spec [block!] attribs [block! none!] /routine name [word!]
		/local extra cb?
	][
		either routine [							;-- test for function! pointer case
			if cb?: any [
				fspec/5 = 'callback
				all [attribs any [find attribs 'cdecl find attribs 'stdcall]]
			][
				extra: emit-APCS-header args fspec/3 attribs
			]
			name: pick tail fspec -2
			
			emit-i32 #{e1a0c000}					;-- MOV r12, r0
			either all [
				'local = last fspec
				find form name slash 
			][
				emitter/access-path load form name none
			][
				emit-load-symbol name
			]
			emit-i32 #{e1a0a000}					;-- MOV r10, r0
			emit-i32 #{e1a0000c}					;-- MOV r0, r12
			emit-i32 #{e120003a}					;-- BLX r10
			if all [extra positive? extra][
				emit-op-imm32 #{e28dd000} extra		;-- ADD sp, sp, extra	; skip extra stack arguments
			]
			if cb? [emit-hf-return fspec/4]
		][
			if issue? args/1 [							;-- variadic call
				emit-push call-arguments-size? args/2	;-- push arguments total size in bytes 
														;-- (required to clear stack on stdcall return)
				emit-i32 #{e28dc004}					;-- ADD ip, sp, #4	; skip last pushed value
				emit-i32 #{e92d1000}					;-- PUSH {ip}		; push arguments list pointer
				total: length? args/2
				if args/1 = #typed [total: total / 3]	;-- typed args have 3 components
				emit-push total							;-- push arguments count
			]
			emit-reloc-addr spec/3
			emit-i32 #{eb000000}					;-- BL <disp>
		]
	]

	patch-call: func [code-buf rel-ptr dst-ptr] [
		;; @@ to-bin24
		change
			at code-buf rel-ptr
			copy/part to-bin32 shift (dst-ptr - rel-ptr - (2 * ptr-size)) 2 3
	]
	
	emit-argument: func [arg fspec [block!]][
		if arg = #_ [exit]							;-- place-holder, no code to emit
		
		either all [
			object? arg
			any [arg/type = 'logic! 'byte! = first compiler/get-type arg/data]
			not path? arg/data
		][
			unless block? arg [emit-load arg]		;-- block! means last value is already in r0 (func call)
			emit-casting arg no
			compiler/last-type: arg/type			;-- for inline unary functions
			emit-push <last>
		][
			if block? arg [arg: <last>]
			either all [
				fspec/3 = 'cdecl 
				compiler/find-attribute fspec/4 'variadic	;-- only for vararg C functions
			][
				emit-push/cdecl arg					;-- promote float32! to float!
			][
				emit-push arg
			]
		]
	]
	
	emit-stack-align: does [
		emit-i32 #{e1a0c00d}						;-- MOV ip, sp
		emit-i32 #{e3cdd007}						;-- BIC sp, sp, #7		; align sp to 8 bytes
		emit-i32 #{e1a0000c}						;-- MOV r0, ip
	]
	
	emit-stack-align-prolog: func [args [block!] /local size tag][
		;-- EABI stack 8 bytes alignment: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0046b/IHI0046B_ABI_Advisory_1.pdf
		; @@ to be optimized: infer stack alignment if possible, to avoid this overhead.
		
		emit-i32 #{e1a0c00d}                        ;-- MOV ip, sp
		emit-i32 #{e3cdd007}						;-- BIC sp, sp, #7		; align sp to 8 bytes
		size: 0
		if issue? tag: args/1 [
			args: args/2
			unless tag = #variadic [size: size + 4]
		]
		if args: arguments-on-stack?/cdecl args [	;-- skip arguments passed in r0-r3
			size: size + call-arguments-size?/cdecl args
		]
		unless zero? size // 8 [
			emit-i32 #{e24dd004}					;-- SUB sp, sp, #4		; ensure call will be 8-bytes aligned
		]
		emit-i32 #{e92d5000}						;-- PUSH {ip,lr}		; save previous sp and lr value
	]

	emit-stack-align-epilog: func [args [block!]][
		emit-i32 #{e8bd5000}						;-- POP {ip,lr}			; use ip as replacement to sp
		emit-i32 #{e1a0d00c}                        ;-- MOV sp, ip			; to workaround SIGILLs on ARMv7
	]
	
	emit-throw: func [value [integer! word!]][
		emit-load value

		emit-i32 #{e1a0d00b}						;-- 		MOV sp, fp		; unwind 1st frame
		emit-i32 #{e8bd4800}						;-- 		POP {fp,lr}
		emit-i32 #{e24bd004}						;-- _loop:	SUB sp, fp, #4
		emit-i32 #{e8bd0004}						;-- 		POP {r2} 		; get flag
		emit-i32 #{e1520000}						;-- 		CMP r2, r0
		emit-i32 #{38bd4800}						;-- 		POPLO {fp,lr} 	; unwind frame if r2 < r0
		emit-i32 #{3afffffa}						;-- 		BLO _loop		; next frame
													;-- _exit:  
		emitter/access-path to set-path! 'system/thrown <last>
		emit-i32 #{e1a0f00e}						;--			MOV pc, lr
	]

	emit-prolog: func [
		name locals [block!] locals-size [integer!]
		/local args-nb attribs args reg freg fargs-nb
	][
		if verbose >= 3 [print [">>>building:" uppercase mold to-word name "prolog"]]
		
		fspec: select compiler/functions name
		attribs: compiler/get-attributes fspec/4
		
		if any [
			fspec/5 = 'callback
			all [attribs any [find attribs 'cdecl find attribs 'stdcall]]
		][
			;; we use a simple prolog, which maintains ABI compliance: args 0-3 are
			;; passed via regs r0-r3, further args are passed on the stack (pushed
			;; right-to-left; i.e. the leftmost argument is at top-of-stack).
			;;
			;; our prolog pushes the first <=4 args right-to-left to the stack
			;;
			;; AAPCS (for external calls & callbacks only)
			;;
			;;	15 = pc
			;;	14 = lr
			;;	13 = sp									(callee saved: fun must preserve)
			;;	12 = "ip" (scratch)
			;;	4-11 = variable register 1-8			(callee saved: fun must preserve)
			;;	11 = "fp"
			;;	2-3 = argument 3-4
			;;  0-1	= argument 1-2 / result
			;;
			;;	stack (sp) at function call must be 8-byte (dword) aligned!
			;;
			;;	c widths: char = i8, short = i16, int & long = i32, long long = i64
			;;	alignment: == size (so char==1, short==2, int/long==4, ptr==4)
			;;	structs aligned at max aligned, padded to multiple of alignment
			
			args-nb: fspec/1
			
			if all [4 < args-nb name <> '***_start][
				compiler/throw-error "[ARM emitter] more than 4 arguments in callbacks, not yet supported"
			]
			emit-i32 #{e92d4ff0}					;-- STMFD sp!, {r4-r11, lr}
			emit-i32 #{ed2d8b10}					;-- FSTMD sp!, {d8-d15}

			args: fspec/4
			either all [compiler/job/ABI = 'hard-float not empty? args][
				reg: freg: 1
				args: extract-arguments args		;-- cleanup and reverse arguments order
				fargs-nb: count-floats args
				
				foreach arg args [					;-- process in reverse order
					either find [float! float64! float32!] arg/1 [
						emit-push-float fargs-nb - freg arg 		 ;-- push in reverse order
						freg: freg + 1
					][
						emit-i32 #{e92d00}		;-- PUSH {r<n>}
						emit-i32 to char! shift/left 1 args-nb - reg ;-- push in reverse order
						reg: reg + 1
					]
				]
			][
				repeat i args-nb [
					emit-i32 #{e92d00}				;-- PUSH {r<n>}
					emit-i32 to char! shift/left 1 args-nb - i	;-- push in reverse order
				]
			]
			if PIC? [
				emit-i32 #{e1a0900f}				;-- MOV sb, pc
				pools/collect emitter/tail-ptr + 1 + 2 ;-- +1 adjustment for CALL first opcode
				emit-i32 #{e0499000}				;-- SUB sb, r0
			]
		]
			
		;-- Red/System standard function prolog --	
		
		emit-i32 #{e92d4800}						;-- PUSH {fp,lr}
		emit-i32 #{e1a0b00d}						;-- MOV fp, sp
		
		emit-push pick [-2 0] to logic! all [attribs find attribs 'catch]	;-- push catch flag
		emit-push 0									;-- keep stack aligned on 64-bit
		
		unless zero? locals-size [
			locals-size: round/to/ceiling locals-size 4
			either locals-size > 255 [
				emit-load-imm32/reg locals-size 4
				emit-i32 #{e04dd004}				;-- SUB sp, sp, r4
			][
				emit-i32 join #{e24dd0}	to char! locals-size ;-- SUB sp, sp, locals-size
			]
		]
	]

	emit-epilog: func [
		name [word! path!] locals [block!] args-size [integer!] locals-size [integer!]
		/local fspec attribs
	][
		if verbose >= 3 [print [">>>building:" uppercase mold to-word name "epilog"]]
		
		emit-i32 #{e1a0d00b}						;-- MOV sp, fp		; catch flag is skipped
		emit-i32 #{e8bd4800}						;-- POP {fp,lr}

		either compiler/check-variable-arity? locals [
			emit-i32 #{e8bd0004}					;-- POP {r2}		; skip arguments count
			emit-i32 #{e8bd0004}					;-- POP {r2}		; skip arguments pointer
			emit-i32 #{e8bd0004}					;-- POP {r2}		; get stack offset
			emit-i32 #{e08dd002}					;-- ADD sp, sp, r2	; skip arguments list (clears stack)
		][
			unless zero? args-size [
				emit-op-imm32
					#{e28dd000}						;-- ADD sp, sp, args-size
					round/to/ceiling args-size 4
			]
		]
		
		fspec: select/only compiler/functions name
		
		either any [
			fspec/5 = 'callback
			all [
				attribs: compiler/get-attributes fspec/4
				any [find attribs 'cdecl find attribs 'stdcall]
			]
		][
			emit-hf-return fspec/4
			emit-i32 #{ecbd8b10}					;-- FLDMIAD sp!, {d8-d15}
			emit-i32 #{e8bd4ff0}					;-- LDMFD sp!, {r4-r11, lr}
			emit-i32 #{e12fff1e}					;-- BX lr
		][
			emit-i32 #{e1a0f00e}					;-- MOV pc, lr
		]

		pools/mark-entry-point name
	]
]
#' Contribution of individual links
#' @param D A list returned by proc_analysis
#' @param ... Additional arguments to be passed to PACo
#' @return A list with added object jacknife, containing the mean and upper CI values for each link
#' @export
paco_links <- function(D, ...)
{
   HP.ones <- which(D$HP > 0, arr.ind=TRUE)
   SQres.jackn <- matrix(rep(NA, sum(D$HP)^2), sum(D$HP))# empty matrix of jackknifed squared residuals
   colnames(SQres.jackn) <- paste(rownames(D$proc$X),rownames(D$proc$Yrot), sep="-") #colnames identify the H-P link
   t.critical = qt(0.975,sum(D$HP)-1) #Needed to compute 95% confidence intervals.
   for(i in c(1:sum(D$HP))) #PACo setting the ith link = 0
   {
      HP_ind <- D$HP
      HP_ind[HP.ones[i,1],HP.ones[i,2]]=0
      PACo.ind <- PACo(list(H=D$H, P=D$P, HP=HP_ind), ...)
      Proc.ind <- vegan::procrustes(X=PACo.ind$H_PCo, Y=PACo.ind$P_PCo) 
      res.Proc.ind <- c(residuals(Proc.ind))
      res.Proc.ind <- append(res.Proc.ind, NA, after= i-1)
      SQres.jackn[i, ] <- res.Proc.ind   #Append residuals to matrix of jackknifed squared residuals
   } 
   SQres.jackn <- SQres.jackn^2 #Jackknifed residuals are squared
   SQres <- (residuals(D$proc))^2 # Vector of original square residuals
   #jackknife calculations:
   SQres.jackn <- SQres.jackn*(-(sum(D$HP)-1))
   SQres <- SQres*sum(D$HP)
   SQres.jackn <- t(apply(SQres.jackn, 1, "+", SQres)) #apply jackknife function to matrix
   phi.mean <- apply(SQres.jackn, 2, mean, na.rm = TRUE) #mean jackknife estimate per link
   phi.UCI <- apply(SQres.jackn, 2, sd, na.rm = TRUE) #standard deviation of estimates
   phi.UCI <- phi.mean + t.critical * phi.UCI/sqrt(sum(D$HP))
   D$jackknife <- list(mean = phi.mean, upper = phi.UCI)
   return(D)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap", "backtrack", "tswap", "r00"
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42, method="r0")
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="r0")
{
   method <- match.arg(method, c("r0", "r1", "r2", "r00", "c0", "swap", "tswap", "backtrack", "quasiswap"))
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      permuted_HP <- vegan::commsimulator(D$HP, method)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param method The method to permute matrices with: "r0", "r1", "r2", "c0", "swap", "quasiswap"
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42)
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, method="NA")
{
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      permuted_HP <- commsimulator(D$HP, method)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}
#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)

add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- coordpcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- coordpcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}

coordpcoa <-function (D, correction = "none", rn = NULL) 
{
    centre <- function(D, n) {
        One <- matrix(1, n, n)
        mat <- diag(n) - One/n
        mat.cen <- mat %*% D %*% mat
    }
    bstick.def <- function(n, tot.var = 1, ...) {
        res <- rev(cumsum(tot.var/n:1)/n)
        names(res) <- paste("Stick", seq(len = n), sep = "")
        return(res)
    }
    D <- as.matrix(D)
    n <- nrow(D)
    epsilon <- sqrt(.Machine$double.eps)
    if (length(rn) != 0) {
        names <- rn
    }
    else {
        names <- rownames(D)
    }
    CORRECTIONS <- c("none", "lingoes", "cailliez")
    correct <- pmatch(correction, CORRECTIONS)
    if (is.na(correct)) 
        stop("Invalid correction method")
    delta1 <- centre((-0.5 * D^2), n)
    trace <- sum(diag(delta1))
    D.eig <- eigen(delta1)
    min.eig <- min(D.eig$values)
    zero.eig <- which(abs(D.eig$values)- epsilon < epsilon)
    D.eig$values[zero.eig] <- 0
    if (min.eig > -epsilon) {
        correct <- 1
        eig <- D.eig$values
        k <- length(which(eig > epsilon))
        rel.eig <- eig[1:k]/trace
        cum.eig <- cumsum(rel.eig)
        vectors <- sweep(D.eig$vectors[, 1:k], 2, sqrt(eig[1:k]), 
            FUN = "*")
        bs <- bstick.def(k)
        cum.bs <- cumsum(bs)
        res <- data.frame(eig[1:k], rel.eig, bs, cum.eig, cum.bs)
        colnames(res) <- c("Eigenvalues", "Relative_eig", "Broken_stick", 
            "Cumul_eig", "Cumul_br_stick")
        rownames(res) <- 1:nrow(res)
        rownames(vectors) <- names
        colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
            prefix = "Axis.")
        note <- paste("There were no negative eigenvalues. No correction was applied")
        out <- (list(correction = c(correction, correct), note = note, 
            values = res, vectors = vectors, trace = trace))
    }
    else {
        k <- n
        eig <- D.eig$values
        rel.eig <- eig/trace
        rel.eig.cor <- (eig - min.eig)/(trace - (n - 1) * min.eig)
        rel.eig.cor = c(rel.eig.cor[1:(zero.eig[1] - 1)], rel.eig.cor[(zero.eig[1] + 
            1):n], 0)
        cum.eig.cor <- cumsum(rel.eig.cor)
        k2 <- length(which(eig > epsilon))
        k3 <- length(which(rel.eig.cor > epsilon))
        vectors <- sweep(D.eig$vectors[, 1:k2], 2, sqrt(eig[1:k2]), 
            FUN = "*")
        if ((correct == 2) | (correct == 3)) {
            if (correct == 2) {
                c1 <- -min.eig
                note <- paste("Lingoes correction applied to negative eigenvalues: D' = -0.5*D^2 -", 
                  c1, ", except diagonal elements")
                D <- -0.5 * (D^2 + 2 * c1)
            }
            else if (correct == 3) {
                delta2 <- centre((-0.5 * D), n)
                upper <- cbind(matrix(0, n, n), 2 * delta1)
                lower <- cbind(-diag(n), -4 * delta2)
                sp.matrix <- rbind(upper, lower)
                c2 <- max(Re(eigen(sp.matrix, symmetric = FALSE, 
                  only.values = TRUE)$values))
                note <- paste("Cailliez correction applied to negative eigenvalues: D' = -0.5*(D +", 
                  c2, ")^2, except diagonal elements")
                D <- -0.5 * (D + c2)^2
            }
            diag(D) <- 0
            mat.cor <- centre(D, n)
            toto.cor <- eigen(mat.cor)
            trace.cor <- sum(diag(mat.cor))
            min.eig.cor <- min(toto.cor$values)
            zero.eig.cor <- which((toto.cor$values < epsilon) & 
                (toto.cor$values > -epsilon))
            toto.cor$values[zero.eig.cor] <- 0
            if (min.eig.cor > -epsilon) {
                eig.cor <- toto.cor$values
                rel.eig.cor <- eig.cor[1:k]/trace.cor
                cum.eig.cor <- cumsum(rel.eig.cor)
                k2 <- length(which(eig.cor > epsilon))
                vectors.cor <- sweep(toto.cor$vectors[, 1:k2], 
                  2, sqrt(eig.cor[1:k2]), FUN = "*")
                bs <- bstick.def(k2)
                bs <- c(bs, rep(0, (k - k2)))
                cum.bs <- cumsum(bs)
            }
            else {
                if (correct == 2) 
                  cat("Problem! Negative eigenvalues are still present after Lingoes", 
                    "\n")
                if (correct == 3) 
                  cat("Problem! Negative eigenvalues are still present after Cailliez", 
                    "\n")
                rel.eig.cor <- cum.eig.cor <- bs <- cum.bs <- rep(NA, 
                  n)
                vectors.cor <- matrix(NA, n, 2)
            }
            res <- data.frame(eig[1:k], eig.cor[1:k], rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Corr_eig", "Rel_corr_eig", 
                "Broken_stick", "Cum_corr_eig", "Cum_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace, vectors.cor = vectors.cor, trace.cor = trace.cor))
        }
        else {
            note <- "No correction was applied to the negative eigenvalues"
            bs <- bstick.def(k3)
            bs <- c(bs, rep(0, (k - k3)))
            cum.bs <- cumsum(bs)
            res <- data.frame(eig[1:k], rel.eig, rel.eig.cor, 
                bs, cum.eig.cor, cum.bs)
            colnames(res) <- c("Eigenvalues", "Relative_eig", 
                "Rel_corr_eig", "Broken_stick", "Cum_corr_eig", 
                "Cumul_br_stick")
            rownames(res) <- 1:nrow(res)
            rownames(vectors) <- names
            colnames(vectors) <- colnames(vectors, do.NULL = FALSE, 
                prefix = "Axis.")
            out <- (list(correction = c(correction, correct), 
                note = note, values = res, vectors = vectors, 
                trace = trace))
        }
    }
    class(out) <- "pcoa"
    out
}#' paco
#' @param D A list with objects H, P, and HP, returned by prepare_paco_data
#' @return The input list with added objects for the principal coordinates of the objects
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
add_pcoord <- function(D)
{ 
   HP_bin <- which(D$HP > 0, arr.ind=TRUE)
   H_PCo <- ape::pcoa(D$H, correction="cailliez")$vectors #Performs PCo of Host distances 
   P_PCo <- ape::pcoa(D$P, correction="cailliez")$vectors #Performs PCo of Parasite distances
   D$H_PCo <- H_PCo[HP_bin[,1],] #Adjust Host PCo vectors 
   D$P_PCo <- P_PCo[HP_bin[,2],]  #Adjust Parasite PCo vectors
   return(D)
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param margin The margin to sample (1 to sample rows, 2 to sample columns)
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42)
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, margin=1)
{
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      el <- subset(reshape2::melt(D$HP), value>0)
      try_again = TRUE
      while(try_again)
      {
        el[,margin] <- sample(el[,margin])
        try_again <- (length(unique(paste(el$Var1, el$Var2))) != Nlinks)
      }
      permuted_HP <- reshape2::acast(rbind(subset(reshape2::melt(D$HP), value==0),el), Var1~Var2, length)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}

## conditional calculated field: mutate and ddply; see documentation for ddply
## groups: use selectInput with multiple=TRUE and selectize = FALSE
## http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information

## GitHub Hosting example: https://gist.github.com/mattbrehmer/5645155
## Alternative to ggplot2: https://github.com/ramnathv/rCharts

#options(error = browser)
options(shiny.error=NULL) # NULL
options(shiny.trace = FALSE)  # change to TRUE for trace
#options(shiny.reactlog=TRUE)

require(shiny); require(reshape); require(ggplot2); require(Hmisc); require(uuid); #require(plotly);
require(tables); require(tools); require(png); require(plyr); require(shinysky); require(Cairo)
require(knitr); require(rmarkdown); require(shinyAce)

options(shiny.usecairo=TRUE)



InitialTextValue <- 'Xabcde-f9'

MoltenMeasuresName <- 'value'
YFunChoices <- c('Sum'='sum','Mean'='mean','Median'='median','Min'='min','Max'='max',
                 'Standard Deviation'='sd','Variance'='var')
InternalY <- '..y..'


GeomChoices <- c('Text'='text', 'Bar'='bar','Line'='line',
                 'Area'='area',  'Point'='point',
                 'Path'='path','Polygon'='polygon',
                 'Boxplot'='boxplot')
StatChoices <- c('Identity'='identity','Count'='bin','Summary'='summary','Boxplot'='boxplot')


getAesChoices <- function(geom, stat='identity'){
  switch(geom,
         'text'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                           'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                'Color'=c('Alpha'='aesAlpha'),
                                'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                                'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                     'Color'=c('Alpha'='aesAlpha'),
                                     'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                     'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     )
        ),

        'bar'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType','Weight'='aesWeight'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType','Weight'='aesWeight'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'line'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType',
                                           'Grouping'='aesGroup'),
                                'Color'=c('Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType',
                                                'Grouping'='aesGroup'),
                                     'Color'=c('Alpha'='aesAlpha')
                     )
        ),

        'area'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'point'=switch(stat,
                      'bin'=list('Coordinates'=c('X'='aesX'),
                                 'Common'=c('Color'='aesColor','Size'='aesSize',
                                            'Shape'='aesShape'),
                                 'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      ),
                      'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                      'Common'=c('Color'='aesColor','Size'='aesSize',
                                                 'Shape'='aesShape'),
                                      'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      )
        ),

        'boxplot'=switch(stat,
                         'boxplot'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                        'Common'=c('Color'='aesColor','Size'='aesSize',
                                                   'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                        'Color'=c('Border Color'='aesBorderColor',
                                                  'Alpha'='aesAlpha')
                         ),
                         'identity'=list('Coordinates'=c('X'='aesX','Y Middle'='aesMiddle',
                                                         'Y Lower'='aesLower','Y Upper'='aesUpper',
                                                         'Y Min'='aesYmin','Y Max'='aesYmax'),
                                         'Common'=c('Color'='aesColor','Size'='aesSize',
                                                    'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                         'Color'=c('Border Color'='aesBorderColor',
                                                   'Alpha'='aesAlpha')
                         )
        )

  )
}

AesChoicesSimpleList <- unique(unlist(lapply(GeomChoices, getAesChoices), use.names=FALSE))

fonttable <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE,
                        text='
Short,Canonical
mono,Courier
sans,Helvetica
serif,Times
,AvantGarde
,Bookman
,Helvetica-Narrow
,NewCenturySchoolbook
,Palatino
,URWGothic
,URWBookman
,NimbusMon
URWHelvetica,NimbusSan
,NimbusSanCond
,CenturySch
,URWPalladio
URWTimes,NimbusRom
')
FontFamilyChoices <- as.vector(t(as.matrix(fonttable)))
FontFamilyChoices <- FontFamilyChoices[FontFamilyChoices!='']

FontFaceChoices <- c("plain","bold","italic","bold.italic")


#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list()
IMMA.parameters  <- list()
IMMA.definitions <- list()

# Core section
IMMA.attachments[[100]] <- 'core'

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH')

# For each parameter, provide an array specifying:
#    Its length in characters, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)
#ICOADS attachment
IMMA.attachments[[1]] = 'icoads';
IMMA.parameters[[1]]  = c('BSI','B10','B1','DCK','SID','PT',
                          'DUPS','DUPC','TC','PB','WX','SX',
			  'C2','SQZ','SQA','AQZ','AQA','UQZ',
			  'UQA','VQZ','VQA','PQZ','PQA','DQZ',
			  'DQA','ND','SF','AF','UF','VF','PF',
			  'RF','ZNC','WNC','BNC','XNC','YNC',
			  'PNC','ANC','GNC','DNC','SNC','CNC',
			  'ENC','FNC','TNC','QCE','LZ','QCZ')
IMMA.definitions[[1]] = list(
    'BSI'  = list( 1, NULL,  NULL,  NULL, NULL, 1., 1 ),
    'B10'  = list( 3, 1.,    648.,  NULL, NULL, 1., 1 ),
    'B1'   = list( 2, 0.,    99.,   NULL, NULL, 1., 1 ),
    'DCK'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'SID'  = list( 3, 0.,    999.,  NULL, NULL, 1., 1 ),
    'PT'   = list( 2, 0.,    15.,   NULL, NULL, 1., 1 ),
    'DUPS' = list( 2, 0.,    14.,   NULL, NULL, 1., 1 ),
    'DUPC' = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'TC'   = list( 1, 0.,    1.,    NULL, NULL, 1., 1 ),
    'PB'   = list( 1, 0.,    2.,    NULL, NULL, 1., 1 ),
    'WX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'SX'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'C2'   = list( 2, 0.,    40.,   NULL, NULL, 1., 1 ),
    'SQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'SQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'AQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'AQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'UQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'UQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'VQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'VQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'PQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'PQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'DQZ'  = list( 1, 1.,    35.,   NULL, NULL, 1., 2 ),
    'DQA'  = list( 1, 1.,    21.,   NULL, NULL, 1., 2 ),
    'ND'   = list( 1, 1.,    2.,    NULL, NULL, 1., 1 ),
    'SF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'AF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'UF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'VF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'PF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'RF'   = list( 1, 1.,    15.,   NULL, NULL, 1., 2 ),
    'ZNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'WNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'BNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'XNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'YNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'PNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ANC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'GNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'DNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'SNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'CNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'ENC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'FNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'TNC'  = list( 1, 1.,    10.,   NULL, NULL, 1., 2 ),
    'QCE'  = list( 2, 0.,    63.,   NULL, NULL, 1., 1 ),
    'LZ'   = list( 1, 1.,    1.,    NULL, NULL, 1., 1 ),
    'QCZ'  = list( 2, 0.,    31.,   NULL, NULL, 1., 1 )
)
# IMMT2 attachment
IMMA.attachments[[2]] = 'immt2'
IMMA.parameters[[2]]  = c('OS','OP','FM','IX','W2','SGN',
                          'SGT','SGH','WMI','SD2','SP2',
			  'SH2','IS','ES','RS','IC1','IC2',
			  'IC3','IC4','IC5','IR','RRR','TR',
			  'QCI','QI1','QI2','QI3','QI4',
			  'QI5','QI6','QI7','QI8','QI9',
			  'QI10','QI11','QI12','QI13','QI14',
			  'QI15','QI16','QI17','QI18','QI19',
			  'QI20','QI21','HDG','COG','SOG',
			  'SLL','SLHH','RWD','RWS')
IMMA.definitions[[2]] = list(
    'OS'   = list( 1, 0.,   6.,   NULL,  NULL,  1.,  1 ),
    'OP'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'FM'   = list( 2, 0.,   8.,   NULL,  NULL,  1.,  1 ),
    'IX'   = list( 1, 1.,   7.,   NULL,  NULL,  1.,  1 ),
    'W2'   = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGN'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SGT'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'SGH'  = list( 2, 0.,   50.,  56.,   99.,   1.,  1 ),
    'WMI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'SD2'  = list( 2, 0.,   38.,  NULL,  NULL,  1.,  1 ),
    'SP2'  = list( 2, 0.,   30.,  99.,   99.,   1.,  1 ),
    'SH2'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'IS'   = list( 1, 1.,   5.,   NULL,  NULL,  1.,  1 ),
    'ES'   = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'RS'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'IC1'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC2'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC3'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC4'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IC5'  = list( 1, 0.,   10.,  NULL,  NULL,  1.,  2 ),
    'IR'   = list( 1, 0.,   4.,   NULL,  NULL,  1.,  1 ),
    'RRR'  = list( 3, 0.,   999., NULL,  NULL,  1.,  1 ),
    'TR'   = list( 1, 1.,   9.,   NULL,  NULL,  1.,  1 ),
    'QCI'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI1'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI2'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI3'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI4'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI5'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI6'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI7'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI8'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI9'  = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI10' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI11' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI12' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI13' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI14' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI15' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI16' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI17' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI18' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI19' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI20' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'QI21' = list( 1, 0.,   9.,   NULL,  NULL,  1.,  1 ),
    'HDG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'COG'  = list( 3, 0.,   360., NULL,  NULL,  1.,  1 ),
    'SOG'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLL'  = list( 2, 0.,   99.,  NULL,  NULL,  1.,  1 ),
    'SLHH' = list( 3, -99., 99.,  NULL,  NULL,  1.,  1 ),
    'RWD'  = list( 3, 1.,   362., NULL,  NULL,  1.,  1 ),
    'RWS'  = list( 3, 0.0,  99.9, NULL,  NULL,  0.1, 1 )
)
# Model quality control attachment
IMMA.attachments[[3]] = 'mqc';
IMMA.parameters[[3]]  = c('CCCC','BUID','BMP','BSWU','SWU',
                          'BSWV','SWV','BSAT','BSRH','SRH',
			  'SIX','BSST','MST','MSH','BY',
			  'BM','BD','BH','BFL')
IMMA.definitions[[3]] = list(
    'CCCC' = list( 4, 65.,   90.,    NULL,  NULL,  NULL,  3 ),
    'BUID' = list( 6, 48.,   57.,    65.,   90.,   NULL,  3 ),
    'BMP'  = list( 5, 870.0, 1074.6, NULL,  NULL,  0.1,   1 ),
    'BSWU' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWU'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSWV' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'SWV'  = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSAT' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'BSRH' = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SRH'  = list( 3, 0.,    100.,   NULL,  NULL,  1.,    1 ),
    'SIX'  = list( 1, 2.,    3.,     NULL,  NULL,  1.,    1 ),
    'BSST' = list( 4, -99.9, 99.9,   NULL,  NULL,  0.1,   1 ),
    'MST'  = list( 1, 0.,    9.,     NULL,  NULL,  1.,    1 ),
    'MSH'  = list( 3, 0.,    999.,   NULL,  NULL,  1.,    1 ),
    'BY'   = list( 4, 0.,    9999.,  NULL,  NULL,  1.,    1 ),
    'BM'   = list( 2, 1.,    12.,    NULL,  NULL,  1.,    1 ),
    'BD'   = list( 2, 1.,    31.,    NULL,  NULL,  1.,    1 ),
    'BH'   = list( 2, 0.,    23.,    NULL,  NULL,  1.,    1 ),
    'BFL'  = list( 2, 0.,    99.,    NULL,  NULL,  1.,    1 )
)
# Metadata attachment
IMMA.attachments[[4]] = 'metadata'
IMMA.parameters[[4]]  = c('C1M','OPM','KOV','COR','TOB','TOT',
                          'EOT','LOT','TOH','EOH','SIM','LOV',
			  'DOS','HOP','HOT','HOB','HOA','SMF',
			  'SME','SMV')
IMMA.definitions[[4]] = list(
    'C1M' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'OPM' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'KOV' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'COR' = list( 2, 65., 90.,    NULL,  NULL,  NULL,  3 ),
    'TOB' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOT' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOT' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'TOH' = list( 1, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'EOH' = list( 2, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'SIM' = list( 3, 32., 126.,   NULL,  NULL,  NULL,  3 ),
    'LOV' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'DOS' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 ),
    'HOP' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOT' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOB' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'HOA' = list( 3, 0.,  999.,   NULL,  NULL,  1.,    1 ),
    'SMF' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SME' = list( 5, 0.,  99999., NULL,  NULL,  1.,    1 ),
    'SMV' = list( 2, 0.,  99.,    NULL,  NULL,  1.,    1 )
)
# Historical attachment
IMMA.attachments[[5]] = 'historical'
IMMA.parameters[[5]]  = c('WFI','WF','XWI','XW','XDI','XD',
                       'SLPI','TAI','TA','XNI','XN')
IMMA.definitions[[5]] = list(
    'WFI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'WF'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XWI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XW'   = list( 3, NULL,  NULL,  NULL,  NULL,  0.1,   1 ),
    'XDI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XD'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SLPI' = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TAI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'TA'   = list( 4, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XNI'  = list( 1, NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'XN'   = list( 2, NULL,  NULL,  NULL,  NULL,  NULL,  1 )
)
# Supplemental attachment
IMMA.attachments[[99]] = 'supplemental'
IMMA.parameters[[99]]  = c('ATTE','SUPD')
IMMA.definitions[[99]] = list(
    'ATTE' = list( 1,     NULL,  NULL,  NULL,  NULL,  NULL,  1 ),
    'SUPD' = list( NULL,  NULL,  NULL,  NULL,  NULL,  NULL,  3 )
)

# Find out which attachment a parameter is in
IMMA.whichAttachment <- function(parameter) {
    for(i in c(100,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

# Check the value for a parameter is inside its acceptable range(s)
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[7] == 3 ) {
        return(result); 
    }
  
    w<-which(!is.null(ob[[parameter]]) & !is.na(ob[[parameter]]) &
             ((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] )) |
             ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= ob[[parameter]] )))
    if(length(w<length(ob[[parameter]]) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        definitions<-IMMA.definitionsFor(parameter)

        # Treat differently according to type
        if(definitions[7]==3) { # Character, just print
          w<-which(!is.null(ob[[parameter]]))
          if(length(w)>0) {
              if(!is.null(definitions[1])) {
                 Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],ob[[parameter]][w])
              } else {  # Unspecified length, supplementary only - use length of data
                 Result[w]<-sprintf("%s%s",Result[w],ob[[parameter]][w])
              }
          }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
              if(!is.null(definitions[1])) {
                 Result[!w]<-sprintf(sprintf("%%s%%.%ss",definitions[1]),Result[!w],' ')
              } else {  # Unspecified length, supplementary only - use length of data
                 Result<-sprintf("%s%s",Result[!w],' ')
              }
          }
        }
        if(definitions[7]==1) { # Integer - check, scale, round and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             Result[w]<-sprintf(sprintf("%%s%%.%dd",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
        if(definitions[7]==3) { # Base36 - check, scale, convert and print
          w<-which(!is.na(ob[[parameter]]) & IMMA.checkParameter(ob,parameter))
          if(length(w)>0) {
             scaled<-ob[[parameter]][w]/definitions[6]
             round<-as.integer(scaled+0.5) # nearest integer
             enc<-IMMA.encode_base36(round)
             Result[w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[w],round)
         }
          if(length(w)<length(Result)) { # Missing and bad values are encoded as blanks
             Result[!w]<-sprintf(sprintf("%%s%%.%ds",definitions[1]),Result[!w],' ')
          }
         }
      }
    # Done all the parameters, add the ID and length to the start
    # (except for core)
    if ( attachment != 100 ) {
        if ( attachment == 99 ) {
            Result = sprintf(" 0%s",Result)
        } else {
            Result = sprintf("%2d%s",nchar(Result)+4,Result)
        }
        Result = sprintf("%2d%s",attachment,Result)
    }

    return(Result)
  }

# Make a string version of the whole record
IMMA.packString <- function(ob) {
  
}




#' Read in all the IMMA records from a connection
#'
#' Currently only reads the core element - discards attachments
#'
#' I'm not sure how to read variable-format records in an efficient fashion
#'  so at the moment this only looks at the fixed-format component.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
#' gets the current screen width.
#'
#' It's highly OS specific, I do ignore if it works on OSX

getConsoleWidth <- function() {
  os <- .Platform$OS.type
  if ( os  %in% c("unix", "Darwin" )) {
    as.numeric(system('tput cols', intern=TRUE))
  } else {
    return(tryCatch({
      txt <- system('cmd /c "mode con /status | grep  \"Colonne:\"',
                    intern=TRUE)
      txt <- unlist(strsplit(txt, ":"))[2]
      as.numeric(txt)
    }, error = function (err) {
      ## please God forgive me
      80
    }))
  }
}

#' Classe S4 per ProgressBar
#'
#' @name ProgressBar
#' @rdname ProgressBar
#' @aliases ProgressBar-class
#' @title ProgressBar with labels
#' @slot value current value 
#' @slot min minimum value
#' @slot max maximum value
#' @slot char char to use as token for progress
#' @slot width current screen width, autoevaluated
#' @slot time time since the beginning of ProgressBar
#' @exportClass ProgressBar
#' @export ProgressBar
#' @import methods

ProgressBar <- setClass(
  "ProgressBar",
  representation(
    value= "numeric",
    min="numeric",                        
    max="numeric",
    char="character",
    width="numeric",
    time="POSIXct"))


setMethod(
  "initialize",
  signature("ProgressBar"),
  function(.Object, min=0, max=1, char="=") {
    .Object@min <- min
    .Object@max <- max
    .Object@char <- char
    .Object@width <- getConsoleWidth()
    .Object@time <- Sys.time()
    return(.Object)
  })

#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @docType methods
#' @rdname kill-methods



setGeneric(
  "kill",
  function(x){
    standardGeneric("kill")
  })
#' Kills current ProgressBar.
#'
#' @name kill
#' @usage kill(x)
#' @param x `ProgressBar` instance
#' @export
#' @aliases kill,ProgressBar-method

setMethod(
  "kill",
  signature("ProgressBar"),
  function(x) {
    cat("\n", file = stderr())
    flush.console()
  })

#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @docType methods
#' @rdname update-methods
#' @export

setGeneric(
  "update",
  function(x, value, label="") {
    standardGeneric("update")
  })
#' Updates `ProgressBar` with `value`
#'
#' `value` has to `min<= value <= max` with `min` and `max` values
#' of the slots
#'
#' `ProgressBar` tries to evaluate an ETA and prints it.
#' 
#' @name update
#' @usage update(x, value, label)
#' @param x `ProgressBar` instance
#' @param value current state of the `ProgressBar` to be updated
#' @param label optional label to be printed with the `ProgressBar`, defaults
#'        to empty string ("")
#' @export
#' @rdname update
#' @aliases update,ProgressBar,ANY-method

setMethod(
  "update",
  signature("ProgressBar", "ANY"),
  function(x, value, label="") {    
    x@value  <- value
    min <- x@min
    if(value == min) {
      .Object@time <- Sys.time()
    }    
    max <- x@max
    char <- x@char
    elapsed <- as.numeric(difftime(Sys.time(),  x@time, units="secs"))
    V <- value/elapsed
    eta <- (max - value) / V
    eta <- if(value == min) {
      "--:--"
    } else if(eta > 3600) {
      sprintf("%02i:%02i:%02i", as.integer(floor(eta/3600)),
              as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    } else {
      sprintf("%02i:%02i", as.integer(floor((eta/60) %% 60)),
              as.integer(floor(eta %% 60)))
    }
    
    if (!is.finite(value) || value < min || value > max)
      return()
    
    nw <- nchar(char,"w")
    pad <- 12 + nchar(eta)
    nlabel <- nchar(label)
    width <- trunc(x@width/nw) - pad - nlabel
    nb <- round(width * (value - min)/(max - min))
    pc <- round(100 * (value - min)/(max - min))
    if(nlabel > 0) {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% - %s %s", pc, label, eta)), collapse = ""),
          file = stderr())
    } else {
      cat(paste(c("\r |", rep.int(char, nb),
                  rep.int(" ", nw * (width - nb)),
                  sprintf("| %3d%% %s", pc, eta)), collapse = ""),
          file = stderr())
      
    }
    flush.console()
    invisible(x)
  })
#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 26, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/cogsci_2015/paper/pics/")
source("rscripts/helpers.r")

# get prior expectations
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = paste(priorexpectations$effect, priorexpectations$object)

# histogram of expectations
ggplot(priorexpectations, aes(x=expectation_corr/15)) +
  geom_histogram() +
  scale_x_continuous(name="Expected value of prior distribution") +
  scale_y_continuous(name="Number of cases")
ggsave("priorexpectations-histogram.pdf")


# get prior allstate-probs
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
row.names(priorprobs) = paste(priorprobs$effect, priorprobs$object)
head(priorprobs)

# histogram of expectations
ggplot(priorprobs, aes(x=X15)) +
  geom_histogram() +
  scale_x_continuous(name="Prior all-state probability") +
  scale_y_continuous(name="Number of cases")
ggsave("priorallprobs-histogram.pdf")


#####################################
# plot model predictions: expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

toplot = droplevels(subset(some, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-expectations.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_exps = ggplot(toplot, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Prior expected number of objects") +
  scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Posterior predicted number of objects")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-expectations-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-expectations-uniform-regular.pdf",width=6.5,height=4.5)


# plot model predictions: allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5 & State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-uniform-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-allprobs.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData")
summary(mp)
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" &  State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-allprobs-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-allprobs-uniform-regular.pdf",width=6.5,height=4.5)

library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_exps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_exps_nolegend = p_exps + theme(legend.position="none")
p_probs_nolegend = p_probs + theme(legend.position="none")

#pdf("rsa-predictions-uniform.pdf",width=10,height=4)
pdf("rsa-predictions.pdf",width=10,height=4)
grid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()

s = subset(r, quantifier=="Some" & Proportion == "100")
nrow(s)

library(lmerTest)
m=lmer(normresponse ~ AllPriorProbability + (1+AllPriorProbability|workerid) + (1|Item), data=s)
summary(m)



#####################################
# plot model predictions: wonkiness
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(wr, QUD == "how-many" & Alternatives == "0_basic" & WonkyWorldPrior == .5 & Wonky == "true"))
nrow(toplot)

toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_color_manual(values=c("#F8766D","#00BF7D","#00B0F6")) +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior expected number of objects") +
  scale_y_continuous(breaks=seq(0,1,by=.25),name="Model predicted wonkiness probability")

ggsave("model-wonkiness-uniform.pdf",width=5.5,height=4)#,width=30,height=10)
ggsave("model-wonkiness-binomial.pdf",width=5.5,height=4)#,width=30,height=10)


###############
## EMPIRICAL PLOTS
###############

# expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")

agr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh

min(agr[agr$quantifier == "Some",]$ProportionResponse)
max(agr[agr$quantifier == "Some",]$ProportionResponse)

p_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=quantifier)) +
  geom_point() +
  #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(breaks=seq(1,15,by=2),name="Posterior mean number of objects") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior mean number of objects")  
ggsave(file="meanresponses.pdf",width=5,height=3.7)


# allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData")

# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)
tmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)
ub = subset(agrr, Proportion == "100")
ub = droplevels(ub)

p_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=quantifier)) +
  geom_point() +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(limits=c(0,1),name="Posterior probability of all-state ") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(limits=c(0,1),name="Prior probability of all-state")  
ggsave(file="empirical-allprobs.pdf",width=5,height=3.7)


library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_eexps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_eexps_nolegend = p_eexps + theme(legend.position="none")
p_eprobs_nolegend = p_eprobs + theme(legend.position="none")

pdf("empirical-results.pdf",width=10,height=4)
grid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()


# plot subejct variability for exclusion
ggplot(r[r$Proportion == "0",], aes(x=normresponse,fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)
ggsave("subject-variability.pdf",width=8,height=35)




############
# empirical wonkiness posteriors
############
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData")
head(r)
nrow(r)

ggplot(r, aes(x=response, fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)
ggsave("subject-variability-wonkiness.pdf",width=7,height=25)

toplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN="mean", data=r)
toplot = droplevels(subset(toplot, quantifier %in% c("All","Some","None")))

ggplot(toplot, aes(x=PriorExpectation, y=response, color=quantifier)) +
  geom_point() +
  geom_smooth() 
ggsave(file="graphs/empirical-wonkiness.pdf",width=6)


######################
### NOAH'S MODEL PREDICTIONS
rsa_allstate = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-allstate.csv",header=F)
head(rsa_allstate)
colnames(rsa_allstate) = c("BinomialCW","PosteriorAllProbability")
ggplot(rsa_allstate, aes(x=BinomialCW,y=PosteriorAllProbability)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Binomial coin weight") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions.pdf",width=4.5,height=3.5)  

rsa_expectation = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectation.csv",header=F)
head(rsa_expectation)
colnames(rsa_expectation) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expectation, aes(x=PriorExpectation/15,y=PosteriorExpectation/15)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior expectation")  
ggsave("noahs-expectation-predictions.pdf",width=4.5,height=3.5)  

rsa_expall = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectedVsallstate.csv",header=F)
head(rsa_expall)
colnames(rsa_expall) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expall, aes(x=PriorExpectation/15,y=PosteriorExpectation)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions-bypriorexp.pdf",width=4.5,height=3.5)  


#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 26, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/cogsci_2015/paper/pics/")
source("rscripts/helpers.r")

# get prior expectations
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = paste(priorexpectations$effect, priorexpectations$object)

# histogram of expectations
ggplot(priorexpectations, aes(x=expectation_corr/15)) +
  geom_histogram() +
  scale_x_continuous(name="Expected value of prior distribution") +
  scale_y_continuous(name="Number of cases")
ggsave("priorexpectations-histogram.pdf")


# get prior allstate-probs
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
row.names(priorprobs) = paste(priorprobs$effect, priorprobs$object)
head(priorprobs)

# histogram of expectations
ggplot(priorprobs, aes(x=X15)) +
  geom_histogram() +
  scale_x_continuous(name="Prior all-state probability") +
  scale_y_continuous(name="Number of cases")
ggsave("priorallprobs-histogram.pdf")


#####################################
# plot model predictions: expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

toplot = droplevels(subset(some, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-expectations.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_exps = ggplot(toplot, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Prior expected number of objects") +
  scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name="Posterior predicted number of objects")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-expectations-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-expectations-uniform-regular.pdf",width=6.5,height=4.5)


# plot model predictions: allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5 & State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +

#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("model-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-uniform-allprobs.pdf",width=5.5,height=4.5)#,width=30,height=10)
save(toplot, file="../data/toplot-allprobs.RData")

toplot_w = toplot
# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData")
summary(mp)
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" &  State == 15))
nrow(toplot)

# adjust speaker optimality at will
toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"

# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
p_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=RSA)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior probability of all-state") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior probability of all-state")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("model-allprobs-binomial-regular.pdf",width=6.5,height=4.5)
ggsave("model-allprobs-uniform-regular.pdf",width=6.5,height=4.5)

library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_exps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_exps_nolegend = p_exps + theme(legend.position="none")
p_probs_nolegend = p_probs + theme(legend.position="none")

#pdf("rsa-predictions-uniform.pdf",width=10,height=4)
pdf("rsa-predictions.pdf",width=10,height=4)
grid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()

s = subset(r, quantifier=="Some" & Proportion == "100")
nrow(s)

library(lmerTest)
m=lmer(normresponse ~ AllPriorProbability + (1+AllPriorProbability|workerid) + (1|Item), data=s)
summary(m)



#####################################
# plot model predictions: wonkiness
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData")
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-binomial.RData")

# plot expectations for best basic model: 
toplot = droplevels(subset(wr, QUD == "how-many" & Alternatives == "0_basic" & WonkyWorldPrior == .5 & Wonky == "true"))
nrow(toplot)

toplot = droplevels(subset(toplot, SpeakerOptimality == 2))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier)) +
  geom_point() + #color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth() + #color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_color_manual(values=c("#F8766D","#00BF7D","#00B0F6")) +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior expected number of objects") +
  scale_y_continuous(breaks=seq(0,1,by=.25),name="Model predicted wonkiness probability")

ggsave("model-wonkiness-uniform.pdf",width=5.5,height=4)#,width=30,height=10)
ggsave("model-wonkiness-binomial.pdf",width=5.5,height=4)#,width=30,height=10)


###############
## EMPIRICAL PLOTS
###############

# expectations
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")

agr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh

min(agr[agr$quantifier == "Some",]$ProportionResponse)
max(agr[agr$quantifier == "Some",]$ProportionResponse)

p_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=quantifier)) +
  geom_point() +
  #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(breaks=seq(1,15,by=2),name="Posterior mean number of objects") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(breaks=seq(1,15,by=2),name="Prior mean number of objects")  
ggsave(file="meanresponses.pdf",width=5,height=3.7)


# allstate-probs
load("~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData")

# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)
tmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)
agrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)
ub = subset(agrr, Proportion == "100")
ub = droplevels(ub)

p_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=quantifier)) +
  geom_point() +
  geom_smooth(method="lm") +
  scale_color_manual(values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6"),breaks=levels(agr$quantifier),labels=c("all","long filler","none","short filler","some")) +
  scale_y_continuous(limits=c(0,1),name="Posterior probability of all-state ") +
  #  geom_abline(intercept=0,slope=1,color="gray70") +
  scale_x_continuous(limits=c(0,1),name="Prior probability of all-state")  
ggsave(file="empirical-allprobs.pdf",width=5,height=3.7)


library(gridExtra)
#  share a legend between multiple plots
g <- ggplotGrob(p_eexps + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
p_eexps_nolegend = p_eexps + theme(legend.position="none")
p_eprobs_nolegend = p_eprobs + theme(legend.position="none")

pdf("empirical-results.pdf",width=10,height=4)
grid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, "npc"), unit(.45, "npc"), unit(.1, "npc")))
dev.off()


# plot subejct variability for exclusion
ggplot(r[r$Proportion == "0",], aes(x=normresponse,fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)
ggsave("subject-variability.pdf",width=8,height=35)




############
# empirical wonkiness posteriors
############
load("/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData")
head(r)
nrow(r)

ggplot(r, aes(x=response, fill=quantifier)) +
  geom_histogram() +
  facet_grid(workerid~quantifier)
ggsave("subject-variability-wonkiness.pdf",width=7,height=25)

toplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN="mean", data=r)
toplot = droplevels(subset(toplot, quantifier %in% c("All","Some","None")))

ggplot(toplot, aes(x=PriorExpectation, y=response, color=quantifier)) +
  geom_point() +
  geom_smooth() 
ggsave(file="graphs/empirical-wonkiness.pdf",width=6)


######################
### NOAH'S MODEL PREDICTIONS
rsa_allstate = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-allstate.csv",header=F)
head(rsa_allstate)
colnames(rsa_allstate) = c("BinomialCW","PosteriorAllProbability")
ggplot(rsa_allstate, aes(x=BinomialCW,y=PosteriorAllProbability)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Binomial coin weight") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions.pdf",width=4.5,height=3.5)  

rsa_expectation = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectation.csv",header=F)
head(rsa_expectation)
colnames(rsa_expectation) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expectation, aes(x=PriorExpectation/15,y=PosteriorExpectation/15)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior expectation")  
ggsave("noahs-expectation-predictions.pdf",width=4.5,height=3.5)  

rsa_expall = read.csv(file="~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectedVsallstate.csv",header=F)
head(rsa_expall)
colnames(rsa_expall) = c("PriorExpectation","PosteriorExpectation")
ggplot(rsa_expall, aes(x=PriorExpectation/15,y=PosteriorExpectation)) +
  geom_point(color="#00B0F6") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Predicted posterior probability of all-state")  
ggsave("noahs-allstate-predictions-bypriorexp.pdf",width=4.5,height=3.5)  


#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and 
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/", 
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#' 
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    if (is.element("data", names(object$output$options))) {
      data_restore_on_exit <- object$output$options$data
      on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
      object$output$options$data <- NULL
    }
    if (is.element("label", names(object$output$options))) {
      label_restore_on_exit <- object$output$options$label
      on.exit(object$output$options$label <- label_restore_on_exit, add = TRUE)
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

 # TODO: (RK) Read default_options in from config, so a user can
 # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- list(data = switch(1 + is.element("data", names(object$output$options)), 
                              NULL, object$output$options$data), 
                label = switch(1 + is.element("label", names(object$output$options)), 
                               NULL, object$output$options$label))

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list();
IMMA.parameters  <- list();
IMMA.definitions <- list();

# Core section
IMMA.attachments[[100]] <- 'core';

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[100]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH');

# For each parameter, provide an array specifying:
#    Its length in bytes, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[100]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)

# Find out which attachment a parameter is in
IMMA.whichAttachment <- function(parameter) {
    for(i in c(100)) {# ,1,2,3,4,5,99)) {
        if(!is.null(IMMA.definitions[[i]][[parameter]])) { return(i) }
    }
    stop(sprintf("No parameter %s in IMMA",parameter))
}

# Get the definitions for a named parameter
IMMA.definitionsFor <- function(parameter) {
    return(IMMA.definitions[[IMMA.whichAttachment(parameter)]][[parameter]])
}

# Convert between numeric and base 36
IMMA.decode_base36 <- function(s) { return(strtoi(s,36)) }
# p specifies a minimum number of characters
IMMA.encode_base36 <- function(n,p=0) {
    n<-as.integer(n)
    s<-rep("",length(n))
    w<-which(n==0)
    if(length(w)>0) s[w]<-'0'
    w<-which(n>0)
    while (length(w)>0) {
       s[w] <- paste(substr(rep("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",length(n[w])),
                          n[w]%%36+1,n[w]%%36+1),
                   s[w],sep='')
       n <-as.integer(n/36)
       w<-which(n>0)
    }
    w<-which(nchar(s)<p)
    # Pad strings of less than minimum length with zeros
    while(length(w)>0) {
      s[w]<-paste('0',s[w],sep='')
      w<-which(nchar(s)<p)
    }
    return(s)
}

# Check the value for a parameter is inside its acceptable range(s)
IMMA.checkParameter <- function(ob,parameter) {

  if(is.null(parameter)) stop ("Missing parameter")
  definitions=IMMA.definitionsFor(parameter)
  if ( is.null(definitions) ) {
     stop("No parameter %s in IMMA.",parameter);
  }

  result<-rep(TRUE,length(ob[[parameter]]))
              
   # Character data can be anything
    if ( definitions[6] == 3 ) {
        return(result); 
    }
  
    w<-which(((is.null(definitions[1]) | definitions[1] <= ob[[parameter]])
        &     (is.null(definitions[2]) | definitions[2] >= ob[[parameter]] )) |
             ((is.null(definitions[3]) | definitions[3] <= ob[[parameter]])
        &     (is.null(definitions[4]) | definitions[4] >= this[[parameter]] )))
    if(length(w<length(ob[[parameter]]) result[!w]<-FALSE
  return(result)
}

# Make a string representation of an attachment
IMMA.encodeAttachment <- function(ob,attachment){

    Result = rep('',length(ob$YR))
    for ( parameter in IMMA.parameters[[attachment]]) {
        if ( this[parameters[i]]!=null 
            && this.checkParameter( parameters[i], definitions ) )
        {
            var Tmp = this[parameters[i]];

            // Scale to integer units for output
            if ( definitions[parameters[i]][5] != null ) {
                Tmp /= definitions[parameters[i]][5];
                Tmp = parseInt(Tmp);
            }

            // Encode as base36 if required
            if ( definitions[parameters[i]][5] == 2 ) {
                Tmp = IMMA.encode_base36(Tmp);
            }

            // Convert to a string of the correct length
            if ( definitions[parameters[i]][6] == 1 ) {

                // Integer
                if ( definitions[parameters[i]][0] != null ) {
                    Tmp=Tmp.toString();
                    while(Tmp.length<definitions[parameters[i]][0]) {
                        Tmp=" "+Tmp;
                    }
                }
                else {

                    // Undefined length - should never happen
                    Tmp=Tmp.toString();
                }
            }
            else {

                // String
                if ( definitions[parameters[i]][0] != null ) {
                    Tmp=Tmp.toString();
                    while(Tmp.length<definitions[parameters[i]][0]) {
                        Tmp=Tmp+" ";
                    }
                }
                else {
                
                   // Undefined length - only for supplementary data
                   Tmp=Tmp.toString(); 
                }
            }
            Result += Tmp;

        }
        else {
            // Undefined data - make a blank string of the corect length
            if ( definitions[parameters[i]][0] != null ) {
                for(var j=0;j<definitions[parameters[i]][0];j++) {
                    Result += " ";
                }
            }
            else {

                // Undefined data with unknown length - treat as blank string
                Result += " ";
            }
        }
    }
    
    // Done all the parameters, add the ID and length to the start
    // (except for core)
    if ( attachment != 0 ) {
        if ( attachment == 99 ) {
            Result = " 0"+Result;
        }
        else {
            var Tmp = (Result.length+4).toString();
            if(Tmp.length<2) { Tmp = " "+Tmp; }
            Result = Tmp+Result;
        }
        Tmp = attachment.toString();
        if(Tmp.length<2) { Tmp= " "+Tmp; }
        Result = Tmp+Result;
    }

    return Result;
}




#' Read in all the IMMA records from a connection
#'
#' Currently only reads the core element - discards attachments
#'
#' I'm not sure how to read variable-format records in an efficient fashion
#'  so at the moment this only looks at the fixed-format component.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	result.df$gene <- factor(result.df$gene, levels=unique(as.character(result.df$gene)))
	result.df$gene <- ordered(result.df$gene)
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df,yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "Combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  df = NULL
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  ## if input dataframe is not null then update the target dataframe with the inputdf genes
  if (!(is.null(inputdf)))
  {
    temp <- as.data.frame(inputdf[,1])
    colnames(temp) <- c("gene")
    resultsSub <- plyr::join(temp,resultsSub,type="inner")          
  }
  ## sort the dataframe to match with results table
  #if (cutoff > 0)
  #{
  #  resultsSub2 <- resultsSub[order(-resultsSub$"score"),] 
  #}else{
  #  resultsSub <- resultsSub[order(resultsSub$"score"),]     
  #}
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(updateProgress = NULL,cancer,inputdf,sample)
{
  if (sample == 'tumors'){
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }else{
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }
  
}

##' view 2
comp1view2Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined") 
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
    }
  }
}
## for user file input
comp1view2FilePlot = function(updateProgress = NULL,cancer,inputdf,sample){

  if (sample == 'tumors'){    
    og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }else{
    og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsog <- plyr::join(temp,rgsog,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste("<a href=\"http://www.genecards.org/cgi-bin/carddisp.pl?gene=",rgs[,1],"\">","Gene Card","</a>",sep="")
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsts <- plyr::join(temp,rgsts,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")

        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsog <- plyr::join(temp,rgsog,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsts <- plyr::join(temp,rgsts,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(updateProgress= NULL,cancer,score,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs) 
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}

## shinyFiles
## lubridate, dplyr
## R-blogger
## http://www.r-bloggers.com/read-excel-files-from-r/
## Plotly or animit

## conditional calculated field: mutate and ddply; see documentation for ddply
## groups: use selectInput with multiple=TRUE and selectize = FALSE
## DONE: add sample data mtcars
## http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information

## optimize what's to save for project
## GitHub Hosting example: https://gist.github.com/mattbrehmer/5645155
## Alternative to ggplot2: https://github.com/ramnathv/rCharts

#options(error = browser)
options(shiny.error=NULL) # NULL
options(shiny.trace = FALSE)  # change to TRUE for trace
#options(shiny.reactlog=TRUE)

require(shiny); require(reshape); require(ggplot2); require(Hmisc); require(uuid); require(plotly);
require(tables); require(tools); require(png); require(plyr); require(shinysky); require(Cairo)
require(knitr); require(rmarkdown); require(shinyAce)

options(shiny.usecairo=TRUE)



InitialTextValue <- 'Xabcde-f9'

MoltenMeasuresName <- 'value'
YFunChoices <- c('Sum'='sum','Mean'='mean','Median'='median','Min'='min','Max'='max',
                 'Standard Deviation'='sd','Variance'='var')
InternalY <- '..y..'


GeomChoices <- c('Text'='text', 'Bar'='bar','Line'='line',
                 'Area'='area',  'Point'='point',
                 'Path'='path','Polygon'='polygon',
                 'Boxplot'='boxplot')
StatChoices <- c('Identity'='identity','Count'='bin','Summary'='summary','Boxplot'='boxplot')


getAesChoices <- function(geom, stat='identity'){
  switch(geom,
         'text'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                           'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                'Color'=c('Alpha'='aesAlpha'),
                                'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Label'='aesLabel','Color'='aesColor','Size'='aesSize',
                                                'Shape'='aesShape','Line Type'='aesLineType','Angle'='aesAngle'),
                                     'Color'=c('Alpha'='aesAlpha'),
                                     'Label'=c('Font Family'='aesFamily','Font Face'='aesFontface','Line Height'='aesLineheight'),
                                     'Justification'=c('Horizontal Adjustment'='aesHjust','Vertical Adjustment'='aesVjust')
                     )
        ),

        'bar'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType','Weight'='aesWeight'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType','Weight'='aesWeight'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'line'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType',
                                           'Grouping'='aesGroup'),
                                'Color'=c('Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType',
                                                'Grouping'='aesGroup'),
                                     'Color'=c('Alpha'='aesAlpha')
                     )
        ),

        'area'=switch(stat,
                     'bin'=list('Coordinates'=c('X'='aesX'),
                                'Common'=c('Color'='aesColor','Size'='aesSize',
                                           'Line Type'='aesLineType'),
                                'Color'=c('Border Color'='aesBorderColor',
                                          'Alpha'='aesAlpha')
                     ),
                     'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                     'Common'=c('Color'='aesColor','Size'='aesSize',
                                                'Line Type'='aesLineType'),
                                     'Color'=c('Border Color'='aesBorderColor',
                                               'Alpha'='aesAlpha')
                     )
        ),

        'point'=switch(stat,
                      'bin'=list('Coordinates'=c('X'='aesX'),
                                 'Common'=c('Color'='aesColor','Size'='aesSize',
                                            'Shape'='aesShape'),
                                 'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      ),
                      'identity'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                      'Common'=c('Color'='aesColor','Size'='aesSize',
                                                 'Shape'='aesShape'),
                                      'Color'=c('Border Color'='aesBorderColor','Alpha'='aesAlpha')
                      )
        ),

        'boxplot'=switch(stat,
                         'boxplot'=list('Coordinates'=c('X'='aesX','Y'='aesY'),
                                        'Common'=c('Color'='aesColor','Size'='aesSize',
                                                   'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                        'Color'=c('Border Color'='aesBorderColor',
                                                  'Alpha'='aesAlpha')
                         ),
                         'identity'=list('Coordinates'=c('X'='aesX','Y Middle'='aesMiddle',
                                                         'Y Lower'='aesLower','Y Upper'='aesUpper',
                                                         'Y Min'='aesYmin','Y Max'='aesYmax'),
                                         'Common'=c('Color'='aesColor','Size'='aesSize',
                                                    'Shape'='aesShape','Line Type'='aesLineType','Weight'='aesWeight'),
                                         'Color'=c('Border Color'='aesBorderColor',
                                                   'Alpha'='aesAlpha')
                         )
        )

  )
}

AesChoicesSimpleList <- unique(unlist(lapply(GeomChoices, getAesChoices), use.names=FALSE))

fonttable <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE,
                        text='
Short,Canonical
mono,Courier
sans,Helvetica
serif,Times
,AvantGarde
,Bookman
,Helvetica-Narrow
,NewCenturySchoolbook
,Palatino
,URWGothic
,URWBookman
,NimbusMon
URWHelvetica,NimbusSan
,NimbusSanCond
,CenturySch
,URWPalladio
URWTimes,NimbusRom
')
FontFamilyChoices <- as.vector(t(as.matrix(fonttable)))
FontFamilyChoices <- FontFamilyChoices[FontFamilyChoices!='']

FontFaceChoices <- c("plain","bold","italic","bold.italic")


load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "Combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  df = NULL
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  ## if input dataframe is not null then update the target dataframe with the inputdf genes
  if (!(is.null(inputdf)))
  {
    temp <- as.data.frame(inputdf[,1])
    colnames(temp) <- c("gene")
    resultsSub <- plyr::join(temp,resultsSub,type="inner")          
  }
  ## sort the dataframe to match with results table
  if (cutoff > 0)
  {
    resultsSub <- resultsSub[order(-resultsSub$"score"),] 
  }else{
    resultsSub <- resultsSub[order(resultsSub$"score"),]     
  }
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(updateProgress = NULL,cancer,inputdf,sample)
{
  if (sample == 'tumors'){
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }else{
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined,-10,cancer,"Combined")
    resultsSub <- subset(resultsSub, cancer == cancer & gene %in% inputdf[,1])
    if (nrow(resultsSub) > 0){
      ## call plot function
      plotHeatmapPage1(resultsSub, score)        
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No genes match the app data. Nothing to plot.")
    }  
  }
  
}

##' view 2
comp1view2Plot = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined") 
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("gene")
        resultsSub <- plyr::join(temp,resultsSub,type="inner")          
      }
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      com <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")
      genes <- unique(com$gene)
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- inputdf[,1]
        genes <- intersect(genes,temp)
      }
      og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% genes)
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% genes)
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
    }
  }
}
## for user file input
comp1view2FilePlot = function(updateProgress = NULL,cancer,inputdf,sample){

  if (sample == 'tumors'){    
    og <- subset(tcgaResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(tcgaResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }else{
    og <- subset(ccleResultsHeatmapOG, cancer == cancer & gene %in% inputdf[,1])
    colnames(og) <- c('genes','ogs','score.type','cancer')
    ts <- subset(ccleResultsHeatmapTS, cancer == cancer & gene %in% inputdf[,1])
    colnames(ts) <- c('genes','tss','score.type','cancer')
    temp <- plyr::join(og,ts,type="inner")
    if (nrow(temp)>0)
    {
      cs <- abs(temp[,2] - temp[,5])
      res <- data.frame(temp[,1],cs,temp[,c(3,4)])
      colnames(res) <- c('gene','score','score.type','cancer')
      plotCategoryOverview(res)  
    }else{
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
    }
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(updateProgress = NULL,cutoff,cancer,score,sample,inputdf = NULL){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsog <- plyr::join(temp,rgsog,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste("<a href=\"http://www.genecards.org/cgi-bin/carddisp.pl?gene=",rgs[,1],"\">","Gene Card","</a>",sep="")
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
          temp <- as.data.frame(inputdf[,1])
          colnames(temp) <- c("Genes")
          rgsts <- plyr::join(temp,rgsts,type="left")          
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")

        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "Combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsog <- plyr::join(temp,rgsog,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"Combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgsts <- plyr::join(temp,rgsts,type="left")            
      }
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## if input dataframe is not null then update the target dataframe with the inputdf genes
      if (!(is.null(inputdf)))
      {
        temp <- as.data.frame(inputdf[,1])
        colnames(temp) <- c("Genes")
        rgscom <- plyr::join(temp,rgscom,type="left")            
      }
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "Combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "Combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(updateProgress= NULL,cancer,score,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs) 
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"Combined")
    rgsog <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"Combined")
    rgsts <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
#' Performs PACo/procustes analysis
#' @param D a list with the data
#' @param nperm Number of permutations
#' @param seed Seed if results need to be reproduced
#' @param margin The margin to sample (1 to sample rows, 2 to sample columns)
#' @export
#' @examples 
#' data(gopherlice)
#' library(ape)
#' gdist <- cophenetic(gophertree)
#' ldist <- cophenetic(licetree)
#' D <- prepare_paco_data(gdist, ldist, gl_links)
#' D <- add_pcoord(D)
#' D <- PACo(D, nperm=10, seed=42)
#' print(D$gof)
PACo <- function(D, nperm=1000, seed=NA, margin=1)
{
   if(!("H_PCo" %in% names(D))) D <- add_pcoord(D)
   proc <- vegan::procrustes(X=D$H_PCo, Y=D$P_PCo)
   Nlinks <- sum(D$HP)
   ## Goodness of fit
   m2ss <- proc$ss
   pvalue <- 0
   if(!is.na(seed)) set.seed(seed)
   for(n in c(1:nperm))
   {
      el <- subset(reshape2::melt(D$HP), value>0)
      try_again = TRUE
      while(try_again)
      {
        el[,margin] <- sample(el[,margin])
        try_again <- (length(unique(paste(el$Var1, el$Var2))) != Nlinks)
      }
      permuted_HP <- reshape2::acast(el, Var1~Var2, length)
      permuted_HP <- permuted_HP[rownames(D$HP),colnames(D$HP)]
      perm_D <- list(H=D$H, P=D$P, HP=permuted_HP)
      perm_paco <- add_pcoord(perm_D)
      perm_proc_ss <- vegan::procrustes(X=perm_paco$H_PCo, Y=perm_paco$P_PCo)$ss
      if(perm_proc_ss <= m2ss) pvalue <- pvalue + 1
   }
   pvalue <- pvalue / nperm
   D$proc <- proc
   D$gof <- list(p=pvalue, ss=m2ss, n=nperm)
   return(D)
}
#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 12, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/models/wonky_world/results/")
source("rscripts/helpers.r")

#' get model predictions
load("data/mp-uniform.RData")
d = read.table("data/parsed_uniform_results.tsv", quote="", sep="\t", header=T)
table(d$Item)
nrow(d)
head(d)
d[d$Item == "ate the seeds birds" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 1,]
d[d$Item == "stuck to the wall baseballs" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 2 & d$Wonky == "true",]
mp = ddply(d, .(Item, QUD, State, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
head(mp)
#mp[mp$Item == "ate the seeds birds" & mp$QUD=="how-many" & mp$Alternatives=="0_basic" & mp$SpeakerOptimality == 1,]
wr = ddply(d, .(Item, QUD, Wonky, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
wr[wr$Item == "ate the seeds birds" & wr$QUD=="how-many" & wr$Alternatives=="0_basic" & wr$SpeakerOptimality == 1,]


# get prior expectations
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = paste(priorexpectations$effect,priorexpectations$object)
mp$PriorExpectation = priorexpectations[as.character(mp$Item),]$expectation
wr$PriorExpectation = priorexpectations[as.character(wr$Item),]$expectation

# get smoothed prior probabilities
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
head(priorprobs)
row.names(priorprobs) = paste(priorprobs$effect,priorprobs$object)
mpriorprobs = melt(priorprobs, id.vars=c("effect", "object"))
head(mpriorprobs)
row.names(mpriorprobs) = paste(mpriorprobs$effect,mpriorprobs$object,mpriorprobs$variable)
mp$PriorProbability = mpriorprobs[paste(as.character(mp$Item)," X",mp$State,sep=""),]$value
mp$AllPriorProbability = priorprobs[paste(as.character(mp$Item)),]$X15
head(mp)

# get empirical state posteriors:
load("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/3_sinking-marbles-nullutterance/results/data/r.RData")
head(r)
r$Item = as.factor(paste(r$effect,r$object))
# because posteriors come in 4 bins, make Bin variable for model prediction dataset:
mp$Proportion = as.factor(ifelse(mp$State == 0, "0", ifelse(mp$State == 15, "100", ifelse(mp$State < 8, "1-50", "51-99"))))

agr = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=mean)
#agr$CILow = aggregate(normresponse ~ Item + quantifier + Proportion,data=r, FUN=ci.low)$normresponse
#agr$CIHigh = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=ci.high)$normresponse
#agr$YMin = agr$normresponse - agr$CILow
#agr$YMax = agr$normresponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Proportion, agr$Quantifier)
mp$PosteriorProbability_empirical = agr[paste(mp$Item,mp$Proportion,mp$Quantifier),]$normresponse

#plot empirical against predicted distributions for "some"
some = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality, PriorExpectation, Proportion, WonkyWorldPrior, PosteriorProbability_empirical), summarise, PosteriorProbability_predicted=sum(PosteriorProbability), PriorProbability_smoothed=sum(PriorProbability))
some= subset(some, Quantifier == "some")
nrow(some)
head(some)
msome = melt(some, measure.vars=c("PosteriorProbability_empirical","PosteriorProbability_predicted","PriorProbability_smoothed"))
msome$ptype = as.factor(ifelse(msome$variable == "PosteriorProbability_empirical", "posterior (empirical)",ifelse(msome$variable == "PosteriorProbability_predicted","posterior (model)", "prior")))
head(msome)
nrow(msome)
summary(msome)

toplot = droplevels(subset(msome, QUD == "how-many" & SpeakerOptimality == 2 & Alternatives == "0_basic"))#"0_basic1_lownum2_extra4_twowords5_threewords"))
nrow(toplot)
toplot$Probability = as.factor(ifelse(toplot$ptype == "prior","prior","posterior"))
toplot$Prop = factor(toplot$Proportion, levels=c("1-50","51-99","100"))
ggplot(toplot, aes(x=Prop, y=value,color=ptype, group=ptype, size=Probability)) +
  geom_point() +
  geom_line() +
  scale_size_discrete(range=c(1,2)) +
  scale_color_manual(values=c("red","blue","black")) +
  facet_wrap(WonkyWorldPrior~Item)
ggsave("graphs/model-empirical-uniform-howmany-2-basic.pdf",width=35,height=30)

#plot empirical against predicted expectations for "some"
load("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")
summary(r)
r$Item = as.factor(paste(r$effect, r$object))
agr = aggregate(ProportionResponse ~ Item + quantifier, data=r, FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ Item + quantifier,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ Item + quantifier,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Quantifier)
mp$PosteriorExpectation_empirical = agr[paste(mp$Item,mp$Quantifier),]$ProportionResponse
mp$PriorExpectation_smoothed = mp$PriorExpectation/15

pexpectations = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality,PriorExpectation_smoothed, WonkyWorldPrior, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = droplevels(subset(pexpectations, Quantifier == "some"))

cors = ddply(some, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorExpectation_predicted, PosteriorExpectation_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)

ggplot(some, aes(x=PosteriorExpectation_predicted, y=PosteriorExpectation_empirical,color=as.factor(SpeakerOptimality), shape=as.factor(WonkyWorldPrior))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
#  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-expectations.pdf",width=30,height=10)

  
#plot empirical against predicted allstate-prbabilities for "some"
allstate = droplevels(subset(mp, State == 15 & Quantifier == "some"))
cors = ddply(allstate, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)
# .59 correlation despite being shitty model

ggplot(allstate, aes(x=PosteriorProbability, y=PosteriorProbability_empirical,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-allstateprobs.pdf",width=30,height=10)

#maybe COGSCI plot basis? plot  predicted allstate-prbabilities for "some" as a function of prior allstate-probabilities

ggplot(allstate, aes(x=PriorProbability, y=PosteriorProbability,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-uniform-allstateprobs.pdf",width=30,height=10)

# get empirical wonkiness posteriors
load("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/11_sinking-marbles-normal/results/data/r.RData")
head(r)
nrow(r)
r$Item = as.factor(paste(r$effect,r$object))

t = as.data.frame(prop.table(table(r$Item, r$quantifier, r$response), mar=c(1,2)))
head(t)
colnames(t) = c("Item","Quantifier","NormalMarbles","Proportion")
t[t$Var1=="ate the seeds birds",]
t$Quantifier = tolower(t$Quantifier)
tail(t)
t$Wonky = as.factor(ifelse(t$NormalMarbles == "yes","false","true"))
row.names(t) = paste(t$Item, t$Quantifier, t$Wonky)

wr$PosteriorProbability_empirical = t[paste(wr$Item, wr$Quantifier, wr$Wonky),]$Proportion
head(wr)
wonky = droplevels(subset(wr, Wonky == "true"))

head(wonky)
toplot = droplevels(subset(wonky, Alternatives == "0_basic" & WonkyWorldPrior == .4 & SpeakerOptimality == 2))

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability, color=Quantifier)) +
  geom_point() +
  geom_smooth() 
ggsave(file="graphs/wonkinessplot.pdf",width=6)

cors = ddply(wonky, .(Alternatives, QUD, SpeakerOptimality, Quantifier, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors,15)

wonky_all = subset(wonky, Quantifier == "all")
wonky_none = subset(wonky, Quantifier == "none")
wonky_some = subset(wonky, Quantifier == "some")

ggplot(wonky_all, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_all.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_none.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_some.pdf", width=30,height=10)



ggplot(wonky_all, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-all-wonkiness.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-none-wonkiness.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-some-wonkiness.pdf", width=30,height=10)

save(mp, file="data/mp-uniform.RData")
save(wr, file="data/wr-uniform.RData")

wonky[wonky$Quantifier == "all" & wonky$PriorExpectation < 4 & wonky$Alternatives == "0_basic" & wonky$QUD == "how-many" & wonky$SpeakerOptimality == 2,]

# get model predictions for all-state with basic alts, spopt==2, and qud==how-many
mp_some_allstate = subset(mp, Alternatives=="0_basic" & SpeakerOptimality == 2 & QUD == "how-many" & State == 15)
head(mp_some_allstate)
nrow(mp_some_allstate)



# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

cors = ddply(some, .(SpeakerOptimality), summarise, r=cor(PosteriorExpectation_predicted, PosteriorExpectation_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)

toplot = droplevels(subset(some, SpeakerOptimality == 1))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform.pdf",width=5.5,height=4.5)
save(toplot, file="data/toplot-expectations.RData")

toplot_w = toplot
load("../../complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"
  
# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted, shape=RSA)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform-regular.pdf",width=6.5,height=4.5)
#' ---
#' title: "Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions"
#' author: "Judith Degen"
#' date: "January 12, 2014"
#' ---

library(ggplot2)
theme_set(theme_bw(18))
setwd("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/models/wonky_world/results/")
source("rscripts/helpers.r")

#' get model predictions
load("data/mp-uniform.RData")
d = read.table("data/parsed_uniform_results.tsv", quote="", sep="\t", header=T)
table(d$Item)
nrow(d)
head(d)
d[d$Item == "ate the seeds birds" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 1,]
d[d$Item == "stuck to the wall baseballs" & d$QUD=="how-many" & d$Alternatives=="0_basic" & d$SpeakerOptimality == 2 & d$Wonky == "true",]
mp = ddply(d, .(Item, QUD, State, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
head(mp)
#mp[mp$Item == "ate the seeds birds" & mp$QUD=="how-many" & mp$Alternatives=="0_basic" & mp$SpeakerOptimality == 1,]
wr = ddply(d, .(Item, QUD, Wonky, Alternatives, Quantifier, SpeakerOptimality, WonkyWorldPrior), summarise, PosteriorProbability=sum(PosteriorProbability))
wr[wr$Item == "ate the seeds birds" & wr$QUD=="how-many" & wr$Alternatives=="0_basic" & wr$SpeakerOptimality == 1,]


# get prior expectations
priorexpectations = read.table(file="~/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt",sep="\t", header=T, quote="")
row.names(priorexpectations) = paste(priorexpectations$effect,priorexpectations$object)
mp$PriorExpectation = priorexpectations[as.character(mp$Item),]$expectation
wr$PriorExpectation = priorexpectations[as.character(wr$Item),]$expectation

# get smoothed prior probabilities
priorprobs = read.table(file="~/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt",sep="\t", header=T, quote="")
head(priorprobs)
row.names(priorprobs) = paste(priorprobs$effect,priorprobs$object)
mpriorprobs = melt(priorprobs, id.vars=c("effect", "object"))
head(mpriorprobs)
row.names(mpriorprobs) = paste(mpriorprobs$effect,mpriorprobs$object,mpriorprobs$variable)
mp$PriorProbability = mpriorprobs[paste(as.character(mp$Item)," X",mp$State,sep=""),]$value
mp$AllPriorProbability = priorprobs[paste(as.character(mp$Item)),]$X15
head(mp)

# get empirical state posteriors:
load("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/3_sinking-marbles-nullutterance/results/data/r.RData")
head(r)
r$Item = as.factor(paste(r$effect,r$object))
# because posteriors come in 4 bins, make Bin variable for model prediction dataset:
mp$Proportion = as.factor(ifelse(mp$State == 0, "0", ifelse(mp$State == 15, "100", ifelse(mp$State < 8, "1-50", "51-99"))))

agr = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=mean)
#agr$CILow = aggregate(normresponse ~ Item + quantifier + Proportion,data=r, FUN=ci.low)$normresponse
#agr$CIHigh = aggregate(normresponse ~ Item + quantifier + Proportion,data=r,FUN=ci.high)$normresponse
#agr$YMin = agr$normresponse - agr$CILow
#agr$YMax = agr$normresponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Proportion, agr$Quantifier)
mp$PosteriorProbability_empirical = agr[paste(mp$Item,mp$Proportion,mp$Quantifier),]$normresponse

#plot empirical against predicted distributions for "some"
some = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality, PriorExpectation, Proportion, WonkyWorldPrior, PosteriorProbability_empirical), summarise, PosteriorProbability_predicted=sum(PosteriorProbability), PriorProbability_smoothed=sum(PriorProbability))
some= subset(some, Quantifier == "some")
nrow(some)
head(some)
msome = melt(some, measure.vars=c("PosteriorProbability_empirical","PosteriorProbability_predicted","PriorProbability_smoothed"))
msome$ptype = as.factor(ifelse(msome$variable == "PosteriorProbability_empirical", "posterior (empirical)",ifelse(msome$variable == "PosteriorProbability_predicted","posterior (model)", "prior")))
head(msome)
nrow(msome)
summary(msome)

toplot = droplevels(subset(msome, QUD == "how-many" & SpeakerOptimality == 2 & Alternatives == "0_basic"))#"0_basic1_lownum2_extra4_twowords5_threewords"))
nrow(toplot)
toplot$Probability = as.factor(ifelse(toplot$ptype == "prior","prior","posterior"))
toplot$Prop = factor(toplot$Proportion, levels=c("1-50","51-99","100"))
ggplot(toplot, aes(x=Prop, y=value,color=ptype, group=ptype, size=Probability)) +
  geom_point() +
  geom_line() +
  scale_size_discrete(range=c(1,2)) +
  scale_color_manual(values=c("red","blue","black")) +
  facet_wrap(WonkyWorldPrior~Item)
ggsave("graphs/model-empirical-uniform-howmany-2-basic.pdf",width=35,height=30)

#plot empirical against predicted expectations for "some"
load("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData")
summary(r)
r$Item = as.factor(paste(r$effect, r$object))
agr = aggregate(ProportionResponse ~ Item + quantifier, data=r, FUN=mean)
#agr$CILow = aggregate(ProportionResponse ~ Item + quantifier,data=r, FUN=ci.low)$ProportionResponse
#agr$CIHigh = aggregate(ProportionResponse ~ Item + quantifier,data=r,FUN=ci.high)$ProportionResponse
#agr$YMin = agr$ProportionResponse - agr$CILow
#agr$YMax = agr$ProportionResponse + agr$CIHigh
agr$Quantifier = as.factor(tolower(agr$quantifier))
row.names(agr) = paste(agr$Item, agr$Quantifier)
mp$PosteriorExpectation_empirical = agr[paste(mp$Item,mp$Quantifier),]$ProportionResponse
mp$PriorExpectation_smoothed = mp$PriorExpectation/15

pexpectations = ddply(mp, .(Item, QUD, Alternatives, Quantifier, SpeakerOptimality,PriorExpectation_smoothed, WonkyWorldPrior, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = droplevels(subset(pexpectations, Quantifier == "some"))

cors = ddply(some, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorExpectation_predicted, PosteriorExpectation_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)

ggplot(some, aes(x=PosteriorExpectation_predicted, y=PosteriorExpectation_empirical,color=as.factor(SpeakerOptimality), shape=as.factor(WonkyWorldPrior))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
#  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-expectations.pdf",width=30,height=10)

  
#plot empirical against predicted allstate-prbabilities for "some"
allstate = droplevels(subset(mp, State == 15 & Quantifier == "some"))
cors = ddply(allstate, .(Alternatives, QUD, SpeakerOptimality, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)
# .59 correlation despite being shitty model

ggplot(allstate, aes(x=PosteriorProbability, y=PosteriorProbability_empirical,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-allstateprobs.pdf",width=30,height=10)

#maybe COGSCI plot basis? plot  predicted allstate-prbabilities for "some" as a function of prior allstate-probabilities

ggplot(allstate, aes(x=PriorProbability, y=PosteriorProbability,color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  #  geom_text(data=cors, aes(label=r)) +
  #scale_size_discrete(range=c(1,2)) +
  #scale_color_manual(values=c("red","blue","black")) +
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-uniform-allstateprobs.pdf",width=30,height=10)

# get empirical wonkiness posteriors
load("/Users/titlis/cogsci/projects/stanford/projects/sinking_marbles/sinking-marbles/experiments/11_sinking-marbles-normal/results/data/r.RData")
head(r)
nrow(r)
r$Item = as.factor(paste(r$effect,r$object))

t = as.data.frame(prop.table(table(r$Item, r$quantifier, r$response), mar=c(1,2)))
head(t)
colnames(t) = c("Item","Quantifier","NormalMarbles","Proportion")
t[t$Var1=="ate the seeds birds",]
t$Quantifier = tolower(t$Quantifier)
tail(t)
t$Wonky = as.factor(ifelse(t$NormalMarbles == "yes","false","true"))
row.names(t) = paste(t$Item, t$Quantifier, t$Wonky)

wr$PosteriorProbability_empirical = t[paste(wr$Item, wr$Quantifier, wr$Wonky),]$Proportion
head(wr)
wonky = droplevels(subset(wr, Wonky == "true"))

head(wonky)
toplot = droplevels(subset(wonky, Alternatives == "0_basic" & WonkyWorldPrior == .4 & SpeakerOptimality == 2))

ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability, color=Quantifier)) +
  geom_point() +
  geom_smooth() 
ggsave(file="graphs/wonkinessplot.pdf",width=6)

cors = ddply(wonky, .(Alternatives, QUD, SpeakerOptimality, Quantifier, WonkyWorldPrior), summarise, r=cor(PosteriorProbability, PosteriorProbability_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors,15)

wonky_all = subset(wonky, Quantifier == "all")
wonky_none = subset(wonky, Quantifier == "none")
wonky_some = subset(wonky, Quantifier == "some")

ggplot(wonky_all, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_all.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_none.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PosteriorProbability, y=PosteriorProbability_empirical, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth(method="lm") +
  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1)) +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)
ggsave("graphs/model-empirical-uniform-wonkiness_some.pdf", width=30,height=10)



ggplot(wonky_all, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-all-wonkiness.pdf", width=30,height=10)

ggplot(wonky_none, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-none-wonkiness.pdf", width=30,height=10)

ggplot(wonky_some, aes(x=PriorExpectation, y=PosteriorProbability, color=as.factor(WonkyWorldPrior), shape=as.factor(SpeakerOptimality))) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits=c(0,1)) +  
  facet_grid(QUD~Alternatives)  
ggsave("graphs/model-uniform-some-wonkiness.pdf", width=30,height=10)

save(mp, file="data/mp-uniform.RData")
save(wr, file="data/wr-uniform.RData")

wonky[wonky$Quantifier == "all" & wonky$PriorExpectation < 4 & wonky$Alternatives == "0_basic" & wonky$QUD == "how-many" & wonky$SpeakerOptimality == 2,]

# get model predictions for all-state with basic alts, spopt==2, and qud==how-many
mp_some_allstate = subset(mp, Alternatives=="0_basic" & SpeakerOptimality == 2 & QUD == "how-many" & State == 15)
head(mp_some_allstate)
nrow(mp_some_allstate)



# plot expectations for best basic model: 
toplot = droplevels(subset(mp, QUD == "how-many" & Alternatives == "0_basic" & Quantifier == "some" & WonkyWorldPrior == .5))
nrow(toplot)

pexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)
head(pexpectations)
some = pexpectations#droplevels(subset(pexpectations, Quantifier == "some"))

cors = ddply(some, .(SpeakerOptimality), summarise, r=cor(PosteriorExpectation_predicted, PosteriorExpectation_empirical))
cors = cors[order(cors[,c("r")],decreasing=T),]
head(cors)

toplot = droplevels(subset(some, SpeakerOptimality == 1))
nrow(toplot)
head(toplot)

ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform.pdf",width=5.5,height=4.5)
save(toplot, file="data/toplot-expectations.RData")

toplot_w = toplot
load("../../complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData")
toplot_r = toplot
head(toplot_w)
summary(toplot_r)
toplot_r$RSA = "regular"
toplot_w$RSA = "wonky"
  
# plot both rRSA and uniform wRSA expectation predictions in same plot
toplot = merge(toplot_r,toplot_w, all=T)
head(toplot)
nrow(toplot)
ggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted, shape=RSA)) +
  geom_point(color="#00B0F6") + #values=c("#F8766D", "#A3A500", "#00BF7D", "#E76BF3", "#00B0F6")
  geom_smooth(color="#00B0F6") +
  #  geom_abline(intercept=0,slope=1,color="gray50") +
  scale_x_continuous(limits=c(0,1), name="Prior expectation") +
  scale_y_continuous(limits=c(0,1), name="Model predicted posterior expectation")
#  geom_text(data=cors, aes(label=r)) +
#scale_size_discrete(range=c(1,2)) +
#scale_color_manual(values=c("red","blue","black")) 
#ggsave("graphs/model-expectations.pdf",width=5.5,height=4.5)#,width=30,height=10)
ggsave("~/cogsci/conferences_talks/_2015/2_cogsci_pasadena/wonky_marbles/paper/pics/model-expectations-uniform-regular.pdf",width=6.5,height=4.5)
# server.R
library(shiny)
library(rworldmap)
library(countrycode)

# We put here all load for performance reasons.
#Nevertheless the load blocks the app a few seconds
data <- moocs[moocs$registered == "1",]

# Adding courses list.
course_id <- unique(data$course_id)

shinyServer(function(input, output) {

  output$leftEd <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  output$leftAge <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  output$leftGender <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  output$leftCountry <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos.\n"
  })
  
  # Visualization by Level of Education
  output$LoEPlot <- renderPlot({
    if(input$radioEd == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectEd,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
    
    # Variable for range of studies
    studies <- data$LoE_DI
    
    colors = c("red", "yellow", "green", "violet","orange", "blue")
    barplot(table(studies),main="Nº de certificados atendiendo al nivel de estudios", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("Missing","Bachelor's","Doctorate","< Secondary", "Master's", "Secondary"))
  })
  
  # Visualization by age
  output$AgePlot <- renderPlot({
    if(input$radioAge == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectAge,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
    
    # Years of students (we traduce year of birth to age)
    years <- 2014 - data$YoB
    # By Age
    categories <- c(10,18,25,30,35,45,55,65,80,90)
    agecat <- cut(years, categories)
    
    colors = c("red", "yellow", "green", "violet","orange", "blue","cyan","grey","pink")
    barplot(table(agecat),main="Nº de certificados atendiendo a la edad", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("10-18","18-25","25-30","30-35", "35-45", "45-55","55-65","65-80","80-90"))
  })
  
  # Visualization by genre
  output$GenderPlot <- renderPlot({
    if(input$radioGender == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectGender,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
    
    #By gender
    gender <- table(data$gender)
    genderpercent <- gender/sum(gender)*100
    labels <- c("Missing","Female","Male","Other")
    genderpercent <- round(genderpercent, digits=0)
    labels <- paste(labels, genderpercent)
    labels <- paste(labels,"%",sep="") # ad % to labels
    
    pie(table(data$gender), labels = labels, 
        main="Nº de certificados atendiendo al género", 
        col=rainbow(length(labels)) # We set some colors
        )
  })
  
  # Visualization by country
  output$CountryPlot <- renderPlot({
    if(input$radioCountry == "2") {
      # We keep only information from users that have obtained a certificate of completion
      data <- moocs[moocs$certified == "1",]
    } else {
      data <- moocs[moocs$registered == "1",]
    }
    
    switch(input$selectCountry,
           "1" = (data <- data[data$registered == "1",]),
           "2" = (data <- data[data$course_id == course_id[1],]),
           "3" = (data <- data[data$course_id == course_id[2],]),
           "4" = (data <- data[data$course_id == course_id[3],]),
           "5" = (data <- data[data$course_id == course_id[4],]),
           "6" = (data <- data[data$course_id == course_id[5],]),
           "7" = (data <- data[data$course_id == course_id[6],]),
           "8" = (data <- data[data$course_id == course_id[7],]),
           "9" = (data <- data[data$course_id == course_id[8],]),
           "10" = (data <- data[data$course_id == course_id[9],]),
           "11" = (data <- data[data$course_id == course_id[10],]),
           "12" = (data <- data[data$course_id == course_id[11],]),
           "13" = (data <- data[data$course_id == course_id[12],]),
           "14" = (data <- data[data$course_id == course_id[13],]),
           "15" = (data <- data[data$course_id == course_id[14],]),
           "16" = (data <- data[data$course_id == course_id[15],]),
           "17" = (data <- data[data$course_id == course_id[16],])
    )
  
    #By Country
    dataf <- table(data$final_cc_cname_DI)
    Countries <- as.data.frame(dataf)
    Countries[1] <- countrycode(Countries$Var1,"country.name", "iso3c")
    sPDF <- joinCountryData2Map(Countries, joinCode = "NAME", nameJoinColumn = "Var1")
    
    par(mai=c(0,0,0.3,0),xaxs="i",yaxs="i")
    
    # creating a user defined palette
    op <- palette(c('green','yellow','orange','red'))
    
    # find quartile breaks
    cutVector <- quantile(sPDF@data[["Freq"]], na.rm=TRUE)
    
    # classify the data to a factor
    sPDF@data[["FreqCategories"]] <- cut(sPDF@data[["Freq"]], cutVector, include.lowest=TRUE)
    
    # rename the categories
    levels(sPDF@data[["FreqCategories"]]) <- c('low', 'medium', 'high', 'very_high')
    
    #mapping
    mapCountryData(sPDF, nameColumnToPlot="FreqCategories",
                                mapTitle="Nº de alumnos certificados atendiendo al País",
                                colourPalette="palette", addLegend=TRUE,
                                oceanCol='lightblue',
                                missingCountryCol='white'
                                )
  })
  
  

})#' IMMA.
#'
#' @name IMMA
#' @docType package

# Definitions of the attachments
IMMA.attachments <- list();
IMMA.parameters  <- list();
IMMA.definitions <- list();

# Core section
IMMA.attachments[[1]] <- 'core';

# List of parameters in core section
# In the order they are in on disc
IMMA.parameters[[1]] <- c('YR','MO','DY','HR','LAT','LON','IM','ATTC',
                          'TI','LI','DS','VS','NID','II','ID','C1',
			  'DI','D','WI','W','VI','VV','WW','W1',
                          'SLP','A','PPP','IT','AT','WBTI','WBT',
		          'DPTI','DPT','SI','SST','N','NH','CL',
		          'HI','H','CM','CH','WD','WP','WH','SD',
		          'SP','SH');

# For each parameter, provide an array specifying:
#    Its length in bytes, on disc,
#    Its minimum value
#    Its maximum value
#    Its minimum value (alternative representation)
#    Its maximum value (alternative representation)
#    Its units scale
#    Its encoding (1 = integer, 3= character, 2= base36)
IMMA.definitions[[1]] <- list(
    'YR'   = list( 4, 1600.,  2024.,  NULL,    NULL,   1.,    1 ),
    'MO'   = list( 2, 1.,     12.,    NULL,    NULL,   1.,    1 ),
    'DY'   = list( 2, 1.,     31.,    NULL,    NULL,   1.,    1 ),
    'HR'   = list( 4, 0.00,   23.99,  NULL,    NULL,   0.01,  1 ),
    'LAT'  = list( 5, -90.00, 90.00,  NULL,    NULL,   0.01,  1 ),
    'LON'  = list( 6, 0.00,   359.99, -179.99, 180.00, 0.01,  1 ),
    'IM'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'ATTC' = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'TI'   = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'LI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'DS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'VS'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NID'  = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'II'   = list( 2, 0.,     10.,    NULL,    NULL,   1.,    1 ),
    'ID'   = list( 9, 32.,    126.,   NULL,    NULL,   NULL,  3 ),
    'C1'   = list( 2, 48.,    57.,    65.,     90.,    NULL,  3 ),
    'DI'   = list( 1, 0.,     6.,     NULL,    NULL,   1.,    1 ),
    'D'    = list( 3, 1.,     362.,   NULL,    NULL,   1.,    1 ),
    'WI'   = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'W'    = list( 3, 0.0,    99.9,   NULL,    NULL,   0.1,   1 ),
    'VI'   = list( 1, 0.,     2.,     NULL,    NULL,   1.,    1 ),
    'VV'   = list( 2, 90.,    99.,    NULL,    NULL,   1.,    1 ),
    'WW'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'W1'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'SLP'  = list( 5, 870.0,  1074.6, NULL,    NULL,   0.1,   1 ),
    'A'    = list( 1, 0.,     8.,     NULL,    NULL,   1.,    1 ),
    'PPP'  = list( 3, 0.0,    51.0,   NULL,    NULL,   0.1,   1 ),
    'IT'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'AT'   = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'WBTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'WBT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'DPTI' = list( 1, 0.,     3.,     NULL,    NULL,   1.,    1 ),
    'DPT'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'SI'   = list( 2, 0.,     12.,    NULL,    NULL,   1.,    1 ),
    'SST'  = list( 4, -99.9,  99.9,   NULL,    NULL,   0.1,   1 ),
    'N'    = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'NH'   = list( 1, 0.,     9.,     NULL,    NULL,   1.,    1 ),
    'CL'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'HI'   = list( 1, 0.,     1.,     NULL,    NULL,   1.,    1 ),
    'H'    = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CM'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'CH'   = list( 1, 0.,     10.,    NULL,    NULL,   1.,    2 ),
    'WD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'WP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'WH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 ),
    'SD'   = list( 2, 0.,     38.,    NULL,    NULL,   1.,    1 ),
    'SP'   = list( 2, 0.,     30.,    99.,     99.,    1.,    1 ),
    'SH'   = list( 2, 0.,     99.,    NULL,    NULL,   1.,    1 )
)

// Find out which attachment a parameter is in
IMMA.whichAttachment = function(parameter) {
    for(i in [0,1,2,3,4,5,99]) {
        if(IMMA.definitions[i][parameter]!=null) { return i; }
    }
    throw new Error("No parameter "+parameter+" in IMMA");
}

// Get the definitions for a named parameter
IMMA.definitionsFor = function(parameter) {
    var attachment = IMMA.whichAttachment(parameter);
    return IMMA.definitions[attachment];
}



#' Read in all the IMMA records from a connection
#'
#' Currently only reads the core element - discards attachments
#'
#' I'm not sure how to read variable-format records in an efficient fashion
#'  so at the moment this only looks at the fixed-format component.
#'
#' @export
#' @param con Connection to read data from.
#' @param n - maximum number of records to read (negative means read all)
#'   repeatedly call with n=1 to get records 1 at a time, use n=-1
#'   (default) to get them all in one go.
#' @return data frame - 1 row per record, column names as in the IMMA
#'  documentation.
IMMA.read<-function(con,n=-1) {
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "Combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(updateProgress = NULL,cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(updateProgress = NULL,cancer,inputdf,sample)
{
  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{
    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
  
}

##' view 2
comp1view2Plot = function(updateProgress = NULL,cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }
}
## for user file input
comp1view2FilePlot = function(updateProgress = NULL,cancer,inputdf,sample){

  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{

      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(updateProgress = NULL,cutoff,cancer,score,sample){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")

        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,4]== cancer,]
        rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsog) <- c("Genes","OG","OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr")
        
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,4]== cancer,]
        rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
        colnames(rgsts) <- c("Genes","TS","TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr")
        
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgscom,rgsog,type="left")
        rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,4,2,3,5,6,7,10,11,12,13,14,15,17,18,19,20,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected",
                               "OG.Meth","OG.CNA","OG.Mut","OG.shRNA","OG.Expr",
                               "TS.Meth","TS.CNA","TS.Mut","TS.shRNA","TS.Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(updateProgress= NULL,cancer,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
#!/usr/bin/env Rscript

# Parse the --file= argument out of command line args and
# determine where base directory is so that we can source
# our common sub-routines
arg0 <- sub("--file=(.*)", "\\1", grep("--file=", commandArgs(), value = TRUE))
dir0 <- dirname(arg0)
source(file.path(dir0, "common.r"))

theme_set(theme_grey(base_size = 17))

# Setup parameters for the script
params = matrix(c(
  'help',    'h', 0, "logical",
  'width',   'x', 2, "integer",
  'height',  'y', 2, "integer",
  'outfile', 'o', 2, "character",
  'indir',   'i', 2, "character",
  'tstart',  '1',  2, "integer",
  'tend',    '2',  2, "integer",
  'ylabel1stgraph', 'Y',  2, "character"
  ), ncol=4, byrow=TRUE)

# Parse the parameters
opt = getopt(params)

if (!is.null(opt$help))
  {
    cat(paste(getopt(params, command = basename(arg0), usage = TRUE)))
    q(status=1)
  }

# Initialize defaults for opt
if (is.null(opt$width))   { opt$width   = 1280 }
if (is.null(opt$height))  { opt$height  = 1280 }
if (is.null(opt$indir))   { opt$indir  = "current"}
if (is.null(opt$outfile)) { opt$outfile = file.path(opt$indir, "summary.png") }
if (is.null(opt$ylabel1stgraph)) { opt$ylabel1stgraph = "Op/sec" }

# Load the benchmark data, passing the time-index range we're interested in
b = load_benchmark(opt$indir, opt$tstart, opt$tend)

# If there is no actual data available, bail
if (nrow(b$latencies) == 0)
{
  stop("No latency information available to analyze in ", opt$indir)
}

png(file = opt$outfile, width = opt$width, height = opt$height)

# First plot req/sec from summary
plot_throughput <- qplot(elapsed, successful / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = "Throughput") +

                geom_smooth(aes(y = successful / window, colour = "ok"), size=0.5) +
                geom_point(aes(y = successful / window, colour = "ok"), size=2.0) +

                geom_smooth(aes(y = failed / window, colour = "error"), size=0.5) +
                geom_point(aes(y = failed / window, colour = "error"), size=2.0) +

                scale_colour_manual("Response", values = c("#FF665F", "#188125"))

plot_sessions_running <- qplot(elapsed, running, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = "# sessions",
                 main = "Sessions Running") +

                 geom_point(aes(y = running, colour = "running"), size=2.0) +
                 geom_line( aes(y = running, colour = "running"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#000000"))

plot_sessions_started <- qplot(elapsed, starts / window, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                 main = "Sessions Started") +

                 geom_point(aes(y = starts / window, colour = "starts"), size=2.0) +
                 geom_line( aes(y = starts / window, colour = "starts"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#188125"))

# Setup common elements of the latency plots
latency_plot <- ggplot(b$latencies, aes(x = elapsed)) +
                   facet_grid(. ~ op) +
                   labs(x = "Elapsed Secs", y = "Latency (ms)")

# Plot median, mean and 95th percentiles
plot_median_mean <- latency_plot + labs(title = "Mean and Median Latency") +
            geom_smooth(aes(y = mean, color = "mean"), size=0.5) +
            geom_point(aes(y = mean, color = "mean"), size=2.0) +

            geom_smooth(aes(y = median, color = "median"), size=0.5) +
            geom_point(aes(y = median, color = "median"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FFA700", "#188125"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot median, mean and 95th percentiles
plot_95 <- latency_plot + labs(title = "95th Percentile Latency") +
            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot 99th percentile
plot_99 <- latency_plot + labs(title = "99th Percentile Latency") +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X99_9th","X99th" ),
            #                 labels = c("99.9th", "99th"))

# Plot 99.9th percentile
plot_999 <- latency_plot + labs(title = "99.9th Percentile Latency") +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

# Plot 100th percentile
plot_max <- latency_plot + labs(title = "Maximum Latency") +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

plot_upper_percentiles <- latency_plot + labs(title = "95th, 99th, 99.9th and 100th Percentile") +
            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FFFE00", "#FFA900", "#FF5600", "#FF0000"))

grid.newpage()

pushViewport(viewport(layout = grid.layout(5, 1)))

vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

print(plot_throughput, vp = vplayout(1,1))
print(plot_sessions_running, vp = vplayout(2,1))
print(plot_sessions_started, vp = vplayout(3,1))
print(plot_median_mean, vp = vplayout(4,1))
print(plot_upper_percentiles, vp = vplayout(5,1))

dev.off()
REBOL [
	Title:   "Red/System linker"
	Author:  "Nenad Rakocevic"
	File: 	 %linker.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

linker: context [
	version: 		1.0.0							;-- emitted linker version
	cpu-class: 		'IA-32							;-- default target
	file-emitter:	none							;-- file emitter object
	verbose: 		0								;-- logs verbosity level
	
	line-record!: make-struct [
		ptr		[integer!]							;-- code pointer
		line	[integer!]							;-- line number
		file	[integer!]							;-- filename string offset
	] none
	
	job-class: context [
		format: 									;-- 'PE | 'ELF | 'Mach-o
		type: 										;-- 'exe | 'obj | 'lib | 'dll | 'drv
		target:										;-- CPU identifier
		sections:									;-- code/data sections
		flags:										;-- global flags
		sub-system:									;-- target environment (GUI | console)
		symbols:									;-- symbols table
		output:										;-- output file name (without extension)
		debug-info:									;-- debugging informations
		base-address:								;-- base address
		buffer: none								;-- output buffer
	]
	
	resolve-symbol-refs: func [
		job 	 [object!] 
		cbuf 	 [binary!]							;-- code buffer
		dbuf 	 [binary!]							;-- data buffer
		code-ptr [integer!]							;-- code memory address
		data-ptr [integer!]							;-- data memory address
		pointer	 [object!]
		/local 
			data-offset
	][
		data-offset: either job/PIC? [data-ptr - code-ptr][data-ptr]
		
		foreach [name spec] job/symbols [
			unless empty? spec/3 [
				all [
					any [
						all [
							spec/1 = 'global		;-- code to data references
							pointer/value: data-offset + spec/2
						]
						all [
							spec/1 = 'native-ref	;-- code to code references
							pointer/value: either job/PIC? [spec/2][code-ptr + spec/2]
						]
					]
					foreach ref spec/3 [
						if integer? ref [change at cbuf ref form-struct pointer]
					]
				]
			]
			if all [	
				spec/1 = 'global
				block? spec/4
			][										;-- data to data references
				pointer/value: data-ptr + spec/2			
				foreach ref spec/4 [change at dbuf ref form-struct pointer]
			]
		]
	]
	
	get-debug-lines-size: func [job [object!] /local size][
		size: 12 * (length? job/debug-info/lines/records) / 3
		foreach file job/debug-info/lines/files [
			size: size + 1 + length? file			;-- file is supposed to be FORMed not MOLDed
		]
		size
	]
	
	build-debug-lines: func [
		job [object!]
		code-ptr [integer!]							;-- code memory address
		pointer [object!]
		/local	records files rec-size buffer table strings record data-buf spec
	][
		records: job/debug-info/lines/records
		files: job/debug-info/lines/files
		
		rec-size: 12 * (length? records) / 3 		;-- 12 = pointer! + integer! + integer!
											 		;--  3 = nb of elements in records (flat structure)
		buffer:  make binary! rec-size		 		;-- main buffer
		table:   make block! length? files	 		;-- intermediary file strings offsets table
		strings: make binary! 32 * length? files	;-- file strings buffer
		
		foreach file files [
			append table length? strings			;-- save file string offsets
			append strings form file
			append strings null
		]
		
		record: make-struct line-record! none
		forskip records 3 [
			record/ptr:  code-ptr + records/1 - 1
			record/line: records/2
			record/file: rec-size + pick table records/3	;-- store file offsets
			append buffer form-struct record
		]
		
		data-buf: job/sections/data/2		
		spec: find job/symbols '__debug-lines
		spec/<data>/2: length? data-buf				;-- patch __debug-lines symbol to point to 1st record
		
		repend data-buf [buffer strings]			;-- append records and strings to data segment
	]
		
	clean-imports: func [imports [block!]][			;-- remove unused imports
		foreach [lib list] imports/3 [
			remove-each [name refs] list [empty? refs]
		]
	]

	make-filename: func [job [object!] /local base provided suffix][
		provided: suffix? base: job/build-basename
		suffix: any [
			job/build-suffix
			select file-emitter/defs/extensions job/type
		]
		if any [none? suffix suffix <> provided][
			base: join base suffix
		]
		join any [job/build-prefix %""] base
	]
	
	build: func [job [object!] /local file fun][
		unless job/target [job/target: cpu-class]
		job/buffer: make binary! 512 * 1024
	
		clean-imports job/sections/import
	
		file-emitter: either encap? [
			do-cache rejoin [%system/formats/ job/format %.r]
		][
			do rejoin [%formats/ job/format %.r]
		]
		file-emitter/build job

		file: make-filename job
		if verbose >= 1 [print ["output file:" file]]
		write/binary/direct file job/buffer
		
		if fun: in file-emitter 'on-file-written [
			do reduce [get fun job file]
		]
		
		if find get-modes file 'file-modes 'owner-execute [
			set-modes file [owner-execute: true]
		]
		file
	]

]
# server.R
library(shiny)
# We put here all load for performance reasons.
#Nevertheless the load blocks the app a few seconds

shinyServer(function(input, output) {

  output$leftEd <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos."
  })
  
  output$leftAge <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos."
  })
  
  output$leftGender <- renderText({ 
    "Bienvenido! Este es el panel de control. Aquí puedes configurar
    las opciones de visualización de los datos."
  })
  
  # Visualization by Level of Education
  output$LoEPlot <- renderPlot({
    colors = c("red", "yellow", "green", "violet","orange", "blue")
    barplot(table(studies),main="Nº de certificados atendiendo al nivel de estudios", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("Missing","Bachelor's","Doctorate","< Secondary", "Master's", "Secondary"))
  })
  
  # Visualization by age
  output$AgePlot <- renderPlot({
    colors = c("red", "yellow", "green", "violet","orange", "blue","cyan","grey","pink")
    barplot(table(agecat),main="Nº de certificados atendiendo a la edad", 
            beside=TRUE, # Separar las categorias en varias barras 
            col=colors, # We set some colors
            names.arg=c("10-18","18-25","25-30","30-35", "35-45", "45-55","55-65","65-80","80-90"))
  })
  
  # Visualization by genre
  output$GenderPlot <- renderPlot({
    #colors = c("red", "blue", "green", "grey")
    pie(table(data$gender), labels = labels, 
        main="Nº de certificados atendiendo al género", 
        col=rainbow(length(labels)) # We set some colors
        )
  })
  
  

})REBOL [
  Title:   "Red run time error test script"
	Author:  "Peter W A Wood"
	File: 	 %run-time-error-test.r
	Rights:  "Copyright (C) 2011-2012 Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/origin/BSD-3-License.txt"
]

~~~start-file~~~ "Red run time errors"

	--test-- "rte-1"
		--compile-and-run-this/error {Red[] i: 1 j: 0 k: i / j}
    	--assert-red-printed? "*** Runtime Error 13: integer divide by zero"
    	
    --test-- "rte-2"
    	--compile-and-run-this/error {Red[] absolute -2147483648}
    	--assert-red-printed? "*** Math Error: integer overflow on ABSOLUTE"
    	
     --test-- "rte-3"
    	--compile-and-run-this/error {Red[] #"^^(01)" + #"^^(10FFFF)"}
    	--assert-red-printed? "*** Math Error: char overflow"
    	
    --test-- "rte-4"
    	--compile-and-run-this/error {Red[] do [#"^^(01)" + #"^^(10FFFF)"]}
    	--assert-red-printed? "*** Math Error: char overflow"
    	
    --test-- "rte-5"
    	--compile-and-run-this/error {Red[] #"^^(00)" - #"^^(01)"}
    	--assert-red-printed? "*** Math Error: char overflow"
    	
    --test-- "rte-6"
    	--compile-and-run-this/error {Red[] do [#"^^(00)" - #"^^(01)"]}
    	--assert-red-printed? "*** Math Error: char overflow"
    	
    --test-- "rte-7"
    	--compile-and-run-this/error {Red[] #"^^(010FFF)" * #"^^(11)"}
    	--assert-red-printed? "*** Math Error: char overflow"
    	
    --test-- "rte-8"
    	--compile-and-run-this/error {Red[] do [#"^^(010FFF)" * #"^^(11)" ]}
    	--assert-red-printed? "*** Math Error: char overflow"
  
~~~end-file~~~ 
REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		forever foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct try
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall forever]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| #get pos: (process-get-directive pos/1 pos)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit [[stack/adjust]]
			][
				mark: tail output
				unless head? path [
					emit [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-change*
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-change*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-change* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-try: does [
		unless block? pc/1 [
			pc: back pc
			comp-word									;-- fallback to interpreter
			exit
		]
		emit [catch RED_ERROR]
		insert-lf -2
		body: comp-sub-block 'try
		if body/1 = 'stack/reset [remove body]
		mark: tail output
		emit-open-frame 'try
		insert body mark
		clear mark
		append body [
			stack/unwind
		]
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
	
	comp-forever: does [
		pc: back pc
		change/part pc [while [true]] 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native words/_body
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec select objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			emit reduce [to set-word! name 'func]
			insert-lf -2
			append/only output spec
			append/only output body
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame op
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-get-directive: func [
		path code [block!] /local obj ctx blk
	][
		unless path? path [
			throw-error ["invalid #get argument:" spec]
		]
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 2
		blk: [red/word/get-in (decorate-exec-ctx ctx) (get-word-index/with last path ctx)]
		insert code compose blk
	]
	
	process-in-directive: func [
		path word code [block!] /local obj ctx blk
	][
		if any [not path? path not any-word? :word][
			throw-error ["invalid #in argument:" mold path mold :word]
		]
		append path word
		obj: object-access? path
		ctx: second obj: find objects obj
		remove/part code 3
		blk: [red/object/get-word (decorate-exec-ctx ctx) (get-word-index/with word ctx)]
		insert code compose blk
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc form load-cache %version.r
				comp-expression
				true
			]
			#build-date [
				change pc mold now
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
REBOL [
	Title:   "Builds and Runs the Red Tests"
	File: 	 %run-all.r
	Author:  "Peter W A Wood"
	Version: 0.5.0
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

;; should we run non-interactively?
batch-mode: all [system/options/args find system/options/args "--batch"]

;; supress script messages
store-quiet-mode: system/options/quiet
system/options/quiet: true

do %../quick-test/quick-test.r
qt/tests-dir: system/script/path

;; set the default script header
qt/script-header: "Red []"

;; make auto files if needed
do %source/units/make-red-auto-tests.r
do %source/units/make-interpreter-auto-tests.r 

;; run the tests
print rejoin ["Quick-Test v" qt/version]
print rejoin ["REBOL " system/version]

start-time: now/precise

--setup-temp-files

***start-run-quiet*** "Red Test Suite"

===start-group=== "Red compiler unit tests"
	--run-unit-test-quiet %source/compiler/lexer-test.r
===end-group===

===start-group=== "Red/System runtime tests"
  	--run-test-file-quiet %source/runtime/tools-test.reds
  	--run-test-file-quiet %source/runtime/unicode-test.reds
===end-group===

===start-group=== "Red Compiler tests"
  	--run-script-quiet %source/compiler/print-test.r
  	--run-script-quiet %source/compiler/regression-tests.r
  	--run-script-quiet %source/compiler/run-time-error-test.r
  	--run-script-quiet %source/compiler/compile-error-test.r
===end-group===

===start-group=== "Red Units tests"
    --run-test-file-quiet %source/units/object-test.red
  	--run-test-file-quiet %source/units/logic-test.red
  	--run-test-file-quiet %source/units/conditional-test.red
  	--run-test-file-quiet %source/units/series-test.red
  	--run-test-file-quiet %source/units/path-test.red
  	--run-test-file-quiet %source/units/serialization-test.red
  	--run-test-file-quiet %source/units/function-test.red
  	--run-test-file-quiet %source/units/loop-test.red
  	--run-test-file-quiet %source/units/type-test.red
  	--run-test-file-quiet %source/units/find-test.red
  	--run-test-file-quiet %source/units/select-test.red
  	--run-test-file-quiet %source/units/binding-test.red
  	--run-test-file-quiet %source/units/evaluation-test.red
  	--run-test-file-quiet %source/units/load-test.red
  	--run-test-file-quiet %source/units/switch-test.red
  	--run-test-file-quiet %source/units/case-test.red
  	--run-test-file-quiet %source/units/routine-test.red
  	--run-test-file-quiet %source/units/append-test.red
  	--run-test-file-quiet %source/units/insert-test.red
  	--run-test-file-quiet %source/units/make-test.red
  	--run-test-file-quiet %source/units/system-test.red
  	--run-test-file-quiet %source/units/parse-test.red
  	--run-test-file-quiet %source/units/bitset-test.red
  	--run-test-file-quiet %source/units/same-test.red
  	--run-test-file-quiet %source/units/strict-equal-test.red
  	--run-test-file-quiet %source/units/integer-test.red
  	--run-test-file-quiet %source/units/char-test.red
  	--run-test-file-quiet %source/units/float-test.red
===end-group===

===start-group=== "Red Library tests"
	
===end-group===

===start-group=== "Auto-tests"
  	--run-test-file-quiet %source/units/auto-tests/integer-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-not-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/not-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/infix-greater-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/greater-equal-auto-test.red
===end-group===

===start-group=== "Interpreter Auto-tests"
  	--run-test-file-quiet %source/units/auto-tests/interp-binding-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-case-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-conditional-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-evaluation-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-find-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-function-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-load-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-logic-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-loop-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-select-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-serialization-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-series-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-type-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-switch-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-append-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-insert-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-system-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-parse-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-bitset-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-integer-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-float-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-char-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-object-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-same-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-strict-equal-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-greater-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-inf-not-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-integer-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-float-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-lesser-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-lesser-equal-auto-test.red
  	--run-test-file-quiet %source/units/auto-tests/interp-not-equal-auto-test.red
  	
===end-group===

***end-run-quiet***

--delete-temp-files

end-time: now/precise
print ["       in" difference end-time start-time newline]
system/options/quiet: store-quiet-mode
either batch-mode [
	quit/return either qt/test-run/failures > 0 [1] [0]
][
	print ["The test output was logged to" qt/log-file]
	ask "hit enter to finish"
	print ""
	qt/test-run/failures
]
#!/usr/bin/env Rscript

# Josep Ll. Berral-García
# ALOJA-BSC-MSR hadoop.bsc.es
# 2014-12-11
# Launcher of ALOJA-ML
 
# usage: ./aloja_cli.r -m method [-d dataset] [-l learned model] [-p param1=aaaa:param2=bbbb:param3=cccc:...] [-a] [-n dims] [-v]
#	 ./aloja_cli.r --method method [--dataset dataset] [--learned learned model] [--params param1=aaaa:param2=bbbb:param3=cccc:...] [--allvars] [--numvars dims] [--verbose]
#
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1
#	 ./aloja_cli.r -m aloja_regtree -d aloja-dataset.csv -p saveall=m5p1-small:vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size"
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p1 -d m5p1-tt.csv -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":sorted=asc -v
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p1 -p inst_predict="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L":vin="Benchmark,Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":sorted=asc -v
#	 ./aloja_cli.r -m aloja_outlier_dataset -d m5p1-tt.csv -l m5p1 -p sigma=3:hdistance=3:saveall=m5p1test
#
#	 ./aloja_cli.r -m aloja_pca -d aloja-dataset.csv -p saveall=pca1
#	 ./aloja_cli.r -m aloja_regtree -d pca1-transformed.csv -p prange=1e-4,1e+4:saveall=m5p-simple-redim -n 20
#	 ./aloja_cli.r -m aloja_predict_instance -l m5p-simple-redim -p inst_predict="1922.904354752,70.1570440421649,2.9694955079494,-3.64259027685954,-0.748746678239734,0.161321484374316,0.617610510007444,-0.459044093400257,0.251211132013151,0.251937462205716,-0.142007748147355,-0.0324862729758309,0.406308900544488,0.13593705166432,0.397452596451088,-0.731635384355167,-0.318297127484775,-0.0876192175148721,-0.0504762335523307,-0.0146283091875174" -v
#	 ./aloja_cli.r -m aloja_predict_dataset -l m5p-simple-redim -d m5p-simple-redim-tt.csv -v
#	 ./aloja_cli.r -m aloja_transform_data -d newdataset.csv -p pca_name=pca1:saveall=newdataset
#	 ./aloja_cli.r -m aloja_transform_instance -p pca_name=pca1:inst_transform="sort,ETH,RR3,8,10,1,65536,None,32,Azure L" -v
#
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1
#	 ./aloja_cli.r -m aloja_dataset_collapse -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1
#	 ./aloja_cli.r -m aloja_dataset_collapse_expand -d aloja-dataset.csv -p dimension1="Benchmark":dimension2="Net,Disk,Maps,IO.SFac,Rep,IO.FBuf,Comp,Blk.size,Cluster":dimname1="Benchmark":dimname2="Configuration":saveall=dsc1:model_name=m5p1:inst_general="sort,ETH,RR3,8|10,10,1,65536,*,32,Azure L"
#	 ./aloja_cli.r -m aloja_best_configurations -p bvec_name=dsc1 -v

library(devtools);
source_url("https://raw.githubusercontent.com/Aloja/aloja-ml/master/functions.r");

###############################################################################
# Read arguments from CLI

	suppressPackageStartupMessages(require(optparse));

	option_list = list(
		make_option(c("-m", "--method"), action="store", default=NULL, type='character', help="Method to be executed"),
		make_option(c("-p", "--params"), action="store", default=NULL, type='character', help="Generic list of parameters, separated by two points and no spaces"),
		make_option(c("-v", "--verbose"), action="store_true", default=FALSE, help="Outputs the result of the method"),
		make_option(c("-d", "--dataset"), action="store", default=NULL, type='character', help="For training methods: Dataset source of data"),
		make_option(c("-a", "--allvars"), action="store_true", default=FALSE, help="All vars are input but first one (for reduced dimensions)"),
		make_option(c("-n", "--numvars"), action="store", default=NULL, type='integer', help="All n vars after first one are input (for reduced dimensions)"),
		make_option(c("-l", "--learned"), action="store", default=NULL, type='character', help="For prediction methods: Learned model for prediction")
	);

	opt = parse_args(OptionParser(option_list=option_list));

###############################################################################
# Error and Warning messages on arguments

	if (is.null(opt$method))
	{
		cat("[ERROR] No method selected. Aborting mission.\n");
		quit(save="no", status=-1);
	}

###############################################################################
# Read datasets

	dataset <- NULL;

	if (!is.null(opt$dataset))
	{
		# Call for aloja_get_data
		params_1 <- list();
		params_1[["fread"]] = opt$dataset;

		dataset <- do.call(aloja_get_data,params_1);
	}

###############################################################################
# Parse parameters

	params <- list();
	params[["ds"]] <- dataset;

	if (opt$method %in% c("aloja_regtree","aloja_nneighbors","aloja_linreg","aloja_nnet","aloja_pca","aloja_dataset_collapse","aloja_dataset_collapse_expand","aloja_outlier_dataset"))
	{
		if (is.null(opt$vout)) params[["vout"]] <- "Exe.Time";

		if (is.null(opt$vin))
		{
			if (opt$allvars)
			{
				params[["vin"]] = colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))];
			} else if (!is.null(opt$numvars)) {
				params[["vin"]] = (colnames(dataset)[!(colnames(dataset) %in% c("ID",params$vout))])[1:opt$numvars];
			} else {
				params[["vin"]] = c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster");
			}
		}
	}

	if (opt$method  == "aloja_predict_instance" || opt$method  == "aloja_predict_dataset" || opt$method == "aloja_outlier_dataset")
	{
		params_2 <- list();
		params_2[["tagname"]] <- opt$learned;
		params[["learned_model"]] <- do.call(aloja_load_object,params_2);
	}

	if (opt$method == "aloja_dataset_clustering")
	{
		params_3 <- list();
		params_3[["tagname"]] <- opt$learned;
		params[["na.predict"]] <- do.call(aloja_load_object,params_3);
	}

	if (!is.null(opt$params))
	{
		saux_1 <- strsplit(opt$params, ":");
		saux_2 <- strsplit(saux_1[[1]],"=");

		for (i in 1:length(saux_2))
		{
			params[[saux_2[[i]][1]]] <- strsplit(saux_2[[i]][2],",")[[1]];
		}
		rm(saux_1,saux_2);
	}

	if (is.null(params$vin) && opt$method  == "aloja_predict_instance")
	{
		if (length(params$inst_predict) == length(params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster");
		}
	}
	if (is.null(params$vin) && opt$method  == "aloja_predict_dataset")
	{
		if (all(colnames(params$ds) %in% params$learned_model$varin))
		{
			params[["vin"]] <- params$learned_model$varin;
		} else {
			params[["vin"]] <- c("Benchmark","Net","Disk","Maps","IO.SFac","Rep","IO.FBuf","Comp","Blk.size","Cluster");
		}
	}

###############################################################################
# Execute call

	result <- do.call(opt$method,params);

	if (opt$verbose) result;

###############################################################################
# C'est fini

	quit(save="no", status=0);


require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_gbp)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gbp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
  geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      df = tcgaResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = tcgaResultsHeatmapTS
    }else{
      df = tcgaResultsHeatmapCombined
    }
  }else{
    if(score == 'og.score'){
      df = ccleResultsHeatmapOG
    }else if(score == 'ts.score'){
      df = ccleResultsHeatmapTS
    }else{
      df = ccleResultsHeatmapCombined
    }
  }
  
  ## subset data frame based on user input
  resultsSub <- page1DataFrame(df, cutoff, cancer,"Combined")
  if (nrow(resultsSub) > 0){
    ## call plot function
    plotHeatmapPage1(resultsSub, score)        
  }else{
    plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
    text(1,"Empty result set returned by filter. Nothing to plot.")
  }  

}

## for user file input
comp1view1FilePlot = function(cancer,inputdf,sample)
{
  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{
    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
  
}

##' view 2
comp1view2Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }
}
## for user file input
comp1view2FilePlot = function(cancer,inputdf,sample){

  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{

      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(cutoff,cancer,score,sample){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(cancer,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
load("starter.RData")

##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType, comstring) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == comstring & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type == comstring & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="gray98", og.score="gray98") 
	colorMid = list(combined.score="gray98")
	colorHigh = list(combined.score="#880000", ts.score="#034b87", og.score="#880000")
	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
  geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=10, face="bold"),
	      axis.title.x=element_text(color="gray30", size=10, face="bold"),
	      strip.text.x=element_text(color="gray30", size=10, face="bold"),
	      legend.text=element_text(color="gray30", size=10, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotHeatmapPage1(resultsSub, score)        
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotHeatmapPage1(resultsSub, score)        
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotHeatmapPage1(resultsSub, score)        
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "combined")
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotHeatmapPage1(resultsSub, score)        
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
        
      }
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer, "combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotHeatmapPage1(resultsSub, score)        
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
        
      }
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotHeatmapPage1(resultsSub, score)        
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }
    }
  }
}
## for user file input
comp1view1FilePlot = function(cancer,inputdf,sample)
{
  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{
    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
  
}

##' view 2
comp1view2Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user inputn 
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")      
      if (nrow(resultsSub) > 0){
        ## call plot function
        plotCategoryOverview(resultsSub)             
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"Empty result set returned by filter. Nothing to plot.")
      }      
    }else{
      ## subset data frame based on user input
      og <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer,"combined")
      colnames(og) <- c('genes','ogs','score.type','cancer')
      ts <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      colnames(ts) <- c('genes','tss','score.type','cancer')
      temp <- plyr::join(og,ts,type="inner")
      if (nrow(temp)>0)
      {
        cs <- abs(temp[,2] - temp[,5])
        res <- data.frame(temp[,1],cs,temp[,c(3,4)])
        colnames(res) <- c('gene','score','score.type','cancer')
        plotCategoryOverview(res)  
      }else{
        plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
        text(1,"No overlapping genes were found using the same cutoff score. Nothing to plot.")        
      }
      
#       resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer,"Combined")      
#       if (nrow(resultsSub) > 0){
#         ## call plot function
#         plotCategoryOverview(resultsSub)             
#       }else{
#         plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
#         text(1,"Empty result set returned by filter. Nothing to plot.")
#       }      
    }
  }
}
## for user file input
comp1view2FilePlot = function(cancer,inputdf,sample){

  if (sample == 'tumors'){    
      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }else{

      plot(1,xaxt='n',yaxt='n',ann=FALSE,type="p",col="white")
      text(1,"Nothing to plot.")
    
  }
}





##' main call to page1 gene data frame
geneDataFrameResultSet = function(cutoff,cancer,score,sample){
  
  rgsog= NULL
  rgsts= NULL
  rgscom= NULL
  dfgenes = NULL
  
  if (sample == 'tumors'){
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer,"combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),] 
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
  }else{
    
    if(score == 'og.score'){
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer, "combined")
      rgsog <- resultsSub[resultsSub[,4]== cancer,]
      rgsog <- reshape(rgsog[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsog))
      {
        clist <- c(clist,cancer)
      }
      rgsog <- data.frame(rgsog,clist)
      colnames(rgsog) <- c("Genes","Oncogene Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsog)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer, "combined")
        rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsog,rgsts,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Oncogene.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","OG Score","TS Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }      
      
    }else if(score == 'ts.score'){
    
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer,"combined")
      rgsts <- resultsSub[resultsSub[,4]== cancer,]
      rgsts <- reshape(rgsts[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgsts))
      {
        clist <- c(clist,cancer)
      }
      rgsts <- data.frame(rgsts,clist)
      colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Meth","CNA","Mut","shRNA","Expr","Cancer")
      ## handle empty result set
      if (nrow(rgsts)>0){
        ## select others
        resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer, "combined")
        rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
        rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
        colnames(rgscom) <- c("Genes","Combined Score","Cancer")
        ## make final data frame
        temp <- plyr::join(rgsts,rgsog,type="left")
        rgs <- plyr::join(temp,rgscom,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgs[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgs[,c(1,2,9,10,3,4,5,6,7,8)],gc)
        temp <- temp[order(-temp$"Tumor.Suppressor.Score"),]
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgs)
        colnames(dfgenes) <- c("Genes","TS Score","OG Score","Combined Score","Meth","CNA","Mut","shRNA","Expr","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }else{
      
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer, "Combined")
      rgscom <- resultsSub[resultsSub[,4]== cancer,]
      rgscom <- reshape(rgscom[,c(1,2,3)], direction = "wide", idvar="gene",timevar='score.type')
      clist <- NULL
      for (i in 1:nrow(rgscom))
      {
        clist <- c(clist,cancer)
      }
      rgscom <- data.frame(rgscom,clist)
      colnames(rgscom) <- c("Genes","Oncogene Score","Tumor Suppressor Score","Combined Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer")
      ## handle empty result set
      if (nrow(rgscom)>0){
        ## select others
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer, "combined")
        #rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
        #resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer, "combined")
        #rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
        #colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
        ## make final data frame
        #temp <- plyr::join(rgscom,rgsog,type="left")
        #rgs <- plyr::join(temp,rgsts,type="left")
        gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',rgscom[,1],'">','Gene Card','</a>',sep='')
        temp <- data.frame(rgscom[,c(1,4,2,3,5,6,7,8)],gc)
        if (cutoff > 0)
        {
          temp <- temp[order(-temp$"Combined.Score"),]          
        }else{
          temp <- temp[order(temp$"Combined.Score"),]
        }
        dfgenes <- replace(temp, is.na(temp), "-")
        rm(temp)
        rm(rgscom)
        colnames(dfgenes) <- c("Genes","Combined Score","OG Score","TS Score","OG Score Affected","TS Score Affected","Combined Score Affected","Cancer","External links")
        dfgenes
      }else{
        dfgenes <- data.frame(c("Empty result set returned by filter. Nothing to show."))
        colnames(dfgenes) <- c("Empty result set")
        dfgenes
      }
      
    }
    
  }
}

geneFileDataFrameResultSet = function(cancer,inputdf,sample){
  
  if (sample == 'tumors'){
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }else{
    
    res <- NULL
    ## subset data frame based on user input
    resultsSub <- page1DataFrame(ccleResultsHeatmapOG, -10, cancer,"combined")
    rgsog <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsog) <- c("Genes","Oncogene Score","Cancer")
    ## select others
    resultsSub <- page1DataFrame(ccleResultsHeatmapTS, -10, cancer,"combined")
    rgsts <- resultsSub[resultsSub[,3] == 'combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgsts) <- c("Genes","Tumor Suppressor Score","Cancer")
    resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, -10, cancer, "Combined")
    rgscom <- resultsSub[resultsSub[,3] == 'Combined' & resultsSub[,4]== cancer,c(1,2,4)]
    colnames(rgscom) <- c("Genes","Combined Score","Cancer")
    ## make final data frame
    temp <- plyr::join(rgsog,rgsts,type="left")
    rgs <- plyr::join(temp,rgscom,type="left")
    temp <- inputdf[,1]
    temp <- as.data.frame(temp)
    colnames(temp) <- c("Genes")
    res <- plyr::join(temp,rgs,type="left")
    cnc <- NULL
    for (i in 1:nrow(res))
    {
      cnc <- c(cnc,cancer)
    }
    gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',res[,1],'">','Gene Card','</a>',sep='')
    res <- data.frame(res[,c(1,2,4,5)],cnc,gc)
    colnames(res) <- c("Genes","OG Score","TS Score","Combined Score","Cancer","External links")
    res <- data.frame(res,inputdf)
    res <- replace(res, is.na(res), "-")
    rm(temp)
    rm(rgs)
    if (nrow(res)>0){
      res
    }else{
      res <- data.frame(c("Empty result set returned by filter. Nothing to show."))
      colnames(res) <- c("Empty result set")
      res
    }
    
  }
  
}
#' @include hcl.r
NULL

#' IWantHue palette generator.
#'
#' @field v8 The V8 context.
#' @export
IWantHue <- setRefClass("IWantHue",
  fields = list(v8 = "ANY"),
  methods = list(
  	initialize = function(context) {
  		v8 <<- context;
		v8$source(system.file("chroma.js", package = "rwantshue"))
		v8$source(system.file("chroma.palette-gen.js", package = "rwantshue"))
		v8$source(system.file("lodash.js", package = "rwantshue"))
		v8$eval("iwanthue = function(n, force_mode, quality, js_color_mapper, color_space) {
			filter_colors = function(color) {
			    var hcl = color.hcl();
			    return hcl[0] >= color_space[0][0] && hcl[0] <= color_space[0][1]
			      && hcl[1] >= color_space[1][0] && hcl[1] <= color_space[1][1]
			      && hcl[2] >= color_space[2][0] && hcl[2] <= color_space[2][1];
			}
			var colors = paletteGenerator.generate(n, filter_colors, force_mode, quality);
			colors = paletteGenerator.diffSort(colors);
			colors = _.map(colors, js_color_mapper);
			return JSON.stringify(colors);
		}")
  	},
  	palette = function(n = 8, force_mode = FALSE, quality = 50, color_space = hcl_presets$fancy_light,
  		js_color_mapper = "function(color) { return color.hex(); }") {
  		"Generate a new iwanthue palette"
  		assert_that(is.numeric(n), length(n) == 1)
  		assert_that(is.logical(force_mode), length(force_mode) == 1)
  		assert_that(is.numeric(quality), length(quality) == 1)
  		assert_that(is.hcl(color_space))
  		assert_that(is.character(js_color_mapper))
  		json <- v8$call("iwanthue", as.integer(n), force_mode, as.integer(quality), I(js_color_mapper), color_space)
  		fromJSON(json)
  	},
    hex = function(...) {
	  	"Generate a vector of colors in hex format"
	  	.self$palette(...)	  	
	},
	rgb = function(...) {
		"Generate a matrix of colors in rgb format"
		.self$palette(..., js_color_mapper = I("function(color) { return color.rgb; }"))
	}
  )
)

#' Create a new \linkS4class{IWantHue} object.
#' 
#' @export
iwanthue <- function() {
	IWantHue$new(new_context())
}#' @include hcl.r
NULL

#' IWantHue palette generator.
#'
#' @field v8 The V8 context.
#' @export
IWantHue <- setRefClass("IWantHue",
  fields = list(v8 = "ANY"),
  methods = list(
  	initialize = function(context) {
  		v8 <<- context;
		v8$source(system.file("chroma.js", package = "rwantshue"))
		v8$source(system.file("chroma.palette-gen.js", package = "rwantshue"))
		v8$source(system.file("lodash.js", package = "rwantshue"))
		v8$eval("iwanthue = function(n, force_mode, quality, js_color_mapper, color_space) {
			filter_colors = function(color) {
			    var hcl = color.hcl();
			    return hcl[0] >= color_space[0][0] && hcl[0] <= color_space[0][1]
			      && hcl[1] >= color_space[1][0] && hcl[1] <= color_space[1][1]
			      && hcl[2] >= color_space[2][0] && hcl[2] <= color_space[2][1];
			}
			var colors = paletteGenerator.generate(n, filter_colors, force_mode, quality);
			colors = paletteGenerator.diffSort(colors);
			colors = _.map(colors, js_color_mapper);
			return JSON.stringify(colors);
		}")
  	},
  	palette = function(n = 8, force_mode = FALSE, quality = 50, color_space = hcl_presets$fancy_light,
  		js_color_mapper = I("function(color) { return color.hex(); }")) {
  		"Generate a new iwanthue palette"
  		assert_that(is.numeric(n))
  		assert_that(is.logical(force_mode))
  		assert_that(is.numeric(quality))
  		assert_that(is.hcl(color_space))
  		json <- v8$call("iwanthue", as.integer(n), force_mode, as.integer(quality), js_color_mapper, color_space)
  		fromJSON(json)
  	},
    hex = function(...) {
	  	"Generate a vector of colors in hex format"
	  	.self$palette(...)	  	
	},
	rgb = function(...) {
		"Generate a matrix of colors in rgb format"
		.self$palette(..., js_color_mapper = I("function(color) { return color.rgb; }"))
	}
  )
)

#' Create a new \linkS4class{IWantHue} object.
#' 
#' @export
iwanthue <- function() {
	IWantHue$new(new_context())
}
require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_gdp)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gdp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 

require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)

human_numbers <- function(x = NULL, smbl =""){
  humanity <- function(y){             
    
    if (!is.na(y)){
      
      b <- round_any(y / 1000000000, 0.1)
      m <- round_any(y / 1000000, 0.1)
      k <- round_any(y / 1000, 0.1)
      
      if ( y >= 0 ){ 
        y_is_positive <- ""
      } else {
        y_is_positive <- "-"
      }
      
      if  ( m < 1){
        paste (y_is_positive, smbl,  k , "k", sep = "")
      } else if (b < 1){
        paste (y_is_positive, smbl, m ,"m", sep = "")
      } else {
        paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
      }
    }
  }
  
  sapply(x,humanity)
}

#' Human versions of large currency numbers - extensible via smbl

human_gdp   <- function(x){human_numbers(x, smbl = "£")}
human_usd   <- function(x){human_numbers(x, smbl = "$")}
human_euro  <- function(x){human_numbers(x, smbl = "€")} 
#' rwantshue is an R adaptor for the "I want hue" color palette generator
#'
#' @docType package
#' @import V8 jsonlite
#' @name rwantshue
NULL#' Evaluate the bandwidth selection criterion for a given bandwidth
#' 
#' @param formula symbolic representation of the model
#' @param data data frame containing observations of all the terms represented in the formula
#' @param weights vector of prior observation weights (due to, e.g., overdispersion). Not related to the kernel weights.
#' @param family exponential family distribution of the response
#' @param bw bandwidth for the kernel
#' @param kernel kernel function for generating the local observation weights
#' @param coords matrix of locations, with each row giving the location at which the corresponding row of data was observed
#' @param longlat \code{TRUE} indicates that the coordinates are specified in longitude/latitude, \code{FALSE} indicates Cartesian coordinates. Default is \code{FALSE}.
#' @param varselect.method criterion to minimize in the regularization step of fitting local models - options are \code{AIC}, \code{AICc}, \code{BIC}, \code{GCV}
#' @param tol.loc tolerance for the tuning of an adaptive bandwidth (e.g. \code{knn} or \code{nen})
#' @param bw.type type of bandwidth - options are \code{dist} for distance (the default), \code{knn} for nearest neighbors (bandwidth a proportion of \code{n}), and \code{nen} for nearest effective neighbors (bandwidth a proportion of the sum of squared residuals from a global model)
#' @param bwselect.method criterion to minimize when tuning bandwidth - options are \code{AICc}, \code{BICg}, and \code{GCV}
#' @param verbose print detailed information about our progress?
#' 
#' @return value of the \code{bwselect.method} criterion for the given bandwidth
#' 
lagr.tune.bw = function(x, y, weights, coords, dist, family, bw, kernel, env, oracle, varselect.method, tol.loc, bw.type, bwselect.method, min.dist, max.dist, lambda.min.ratio, n.lambda, lagr.convergence.tol, lagr.max.iter, verbose) {    
    #Fit the model with the given bandwidth:
    cat(paste('Bandwidth: ', round(bw, 3), '; ', sep=""))
print(bw)
    # Tell lagr.dispatch whether to select bandwidth via the jacknife
    if (bwselect.method=='jacknife') {
        jacknife = TRUE
    } else {
        jacknife = FALSE
    }


    vcr.model = lagr.dispatch(
        x=x,
        y=y,
        coords=coords,
        fit.loc=NULL,
        D=dist,
        family=family,
        prior.weights=weights,
        tuning=TRUE,
        predict=FALSE,
        simulation=FALSE,
        oracle=oracle,
        varselect.method=varselect.method,
        verbose=verbose,
        bw=bw,
        bw.type=bw.type,
        kernel=kernel,
        min.dist=min.dist,
        max.dist=max.dist,
        tol.loc=tol.loc,,
        lambda.min.ratio=lambda.min.ratio,
        n.lambda=n.lambda, 
        lagr.convergence.tol=lagr.convergence.tol,
        lagr.max.iter=lagr.max.iter
    )
    
    res = mget('trace', env=env, ifnotfound=list(matrix(NA, nrow=0, ncol=3)))
    res$trace = as.data.frame(rbind(res$trace, c(bw, vcr.model[[bwselect.method]], vcr.model$df)))
    colnames(res$trace) = c("bw", "loss", "df")
    res$trace = res$trace[order(res$trace$bw),]
    assign('trace', res$trace, env=env)
    
    cat(paste('df: ', round(vcr.model$df,4), '; Loss: ', signif(vcr.model[[bwselect.method]], 5), '\n', sep=''))
    return(vcr.model[[bwselect.method]])
}
`%||%` <- function(x, y) if (is.null(x)) y else x

#' Merge two lists and overwrite latter entries with former entries
#' if names are the same.
#'
#' For example, \code{list_merge(list(a = 1, b = 2), list(b = 3, c = 4))}
#' will be \code{list(a = 1, b = 3, c = 4)}.
#' @param list1 list
#' @param list2 list
#' @return the merged list.
#' @examples
#' stopifnot(identical(syberiaStages:::list_merge(list(a = 1, b = 2), list(b = 3, c = 4)),
#'                     list(a = 1, b = 3, c = 4)))
#' stopifnot(identical(syberiaStages:::list_merge(NULL, list(a = 1)), list(a = 1)))
# TODO: (RK) This is a duplicate of the function in mungebits -- is there
# any way to pull them out into one place? Maybe Ramd?
list_merge <- function(list1, list2) {
  list1 <- list1 %||% list()
  # Pre-allocate memory to make this slightly faster.
  list1[Filter(function(x) nchar(x) > 0, names(list2) %||% c())] <- NULL
  for (i in seq_along(list2)) {
    name <- names(list2)[i]
    if (!identical(name, NULL) && !identical(name, "")) list1[[name]] <- list2[[i]]
    else list1 <- append(list1, list(list2[[i]]))
  }
  list1
}

#' Parse functions out of a custom resource.
#'
#' @param functions character. The names of functions to parse out.
#' @param provided_env environment. The environment the resource was loaded from.
#' @param type character. The keyword for the resource.
#' @param resource_type character. The type of the resource (e.g., "classifier",
#'   "adapter", etc.). This will be used to generate error messages.
#' @param strict logical. Whether or not to error if the functions are not found.
#' @return a list containing keys same as the \code{functions} argument.
#'    and predict functions.
parse_custom_functions <- function(functions, provided_env, type,
                                   resource_type = 'classifier', strict = TRUE) {
  provided_fns <- setNames(vector('list', length(functions)), functions)
  for (function_type in names(provided_fns)) {
    fn <- Filter(
      function(x) is.function(provided_env[[x]]),
      grep(function_type, ls(provided_env), value = TRUE)
    )
    # TODO: (RK) Refactor this to be more careful about idempotent resources.
    error <- function(snip = 'a') paste0("The custom ", resource_type, " in ",
      "lib/", resource_type, "s/", type, ".R should define ", snip, " '",
      testthat::colourise(function_type, 'green'), "' function.")
    if (length(fn) == 0 && identical(strict, TRUE)) stop(error(), call. = FALSE)
    else if (length(fn) > 1)
      stop(error('only one'), " Instead, you defined ", length(fn), ", namely: ",
           paste0(fn, collapse = ', '), call. = FALSE)
    else if (length(fn) == 1)
      provided_fns[[function_type]] <- provided_env[[fn]]
  }
  provided_fns
}

#' Helper function to recursively check the existence of a given name.
#'
#' TODO: (fye) Check if this function can be simplified.
#name_exists <- function(object_name, envir = parent.frame()) {
#  names <- strsplit(object_name, split="\\$")[[1]]
#  if (!names[1] %in% ls(envir, all.names = TRUE)) return(FALSE)
#  if (length(names) == 1) return(TRUE)
#  if (is.list(envir[[names[1]]]))
#    Recall(paste(names[-1], collapse = "$"), envir = list2env(envir[[names[1]]]))
#  else if (is.environment(envir[[names[1]]]))
#    Recall(paste(names[-1], collapse = "$"), envir = envir[[names[1]]])
#  else 
#    FALSE
#}
#'  Package to read from ADIOS, including staging.
#'
#' @name pbdADIOS-package
#'
#' @exportPattern "^adios\\.[[:alpha:]]+"
#'
#' @useDynLib pbdADIOS,
#   ### Reader
#'  R_adios_read_init_method,
#'  R_adios_read_open,
#'  R_adios_read_close,
#'  R_adios_read_finalize_method,
#'  R_adios_inq_var,
#'  R_custom_inq_var_ndim,
#'  R_custom_inq_var_dims,
#'  R_adios_inq_var_blockinfo,
#'  R_adios_selection_bounding_box,
#'  R_adios_schedule_read,
#'  R_custom_data_access,
#'  R_adios_perform_reads,
#'  R_adios_advance_step,
#'  R_adios_errno,
#   ### Writer
#'  R_adios_init_noxml,
#'  R_adios_allocate_buffer,
#'  R_adios_declare_group,
#'  R_adios_select_method,
#'  R_adios_define_var,
#'  R_adios_open,
#'  R_adios_group_size,
#'  R_adios_write,
#'  R_adios_close,
#'  R_adios_finalize
#'
#' @import pbdMPI
#' @docType package
#' @title logisticPCA-package
#' @author Pragneshkumar Patel, George Ostrouchov, Wei-Chen Chen, Drew Schmidt
#' @keywords package
NULL

require(scales)

# ---------------------------------------------------------------------------------------------
# Formatting functions for ggplot  graph axis
# ---------------------------------------------------------------------------------------------

#' Human Numbers: Format numbers so they're legible for humans
#' Use this in ggplot for labels where you might use the comma or percent functions from the 
#' Scales package.
#' 
#' Checks whether numbers are positive or negative. 
#' Allows up to 1 significant figure
#' sapply used for element-wise application of the humanity function as a vector may include
#' numbers where billions, millions or thousands are appropriate.
#'
#' @return a character vector the same length as the input vector
#' @param x a numeric vector to format, smbl a symbol you'd like to prefix your numbers by
#' @examples
#' human_numbers(c(1000000 , 1500000, 10000000000))
#' human_numbers(c(1.200000e+05, -2.154660e+05, 2.387790e+05, 4.343500e+04 ,5.648675e+12), "$")
#' ggplot2 + scale_y_continuous(labels = human_numbers)
#' ggplot2 + scale_x_continuous(labels = human_numbers)

human_numbers <- function(x, smbl = ""){
    humanity <- function(y){             
        
        if (!is.na(y)){
        
            b <- round_any(y / 1000000000, 0.1)
            m <- round_any(y / 1000000, 0.1)
            k <- round_any(y / 1000, 0.1)
            
            if ( y >= 0 ){ 
                y_is_positive <- ""
            } else {
                y_is_positive <- "-"
            }
                    
            if  ( m < 1){
                paste (y_is_positive, smbl,  k , "k", sep = "")
            } else if (b < 1){
                paste (y_is_positive, smbl, m ,"m", sep = "")
            } else {
                paste (y_is_positive, smbl,  comma(b), "b", sep = "")    
            }
        }
    }
    
   sapply(x,humanity)
}
# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # Functions which intertwine with the objectdiff package
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

 #SNOPSIS

 #runs principal component analysis using prcomp

 #AUTHOR
 # Isaak Y Tecle (iyt2@cornell.edu)


options(echo = FALSE)

library(imputation)

allArgs <- commandArgs()


outFile <- grep("output_files",
                allArgs,
                ignore.case = TRUE,
                perl = TRUE,
                value = TRUE
                )

outFiles <- scan(outFile,
                 what = "character"
                 )

genoDataFile <- grep("genotype_data",
                   allArgs,
                   ignore.case = TRUE,
                   fixed = FALSE,
                   value = TRUE
                   )



scoresFile <- grep("pca_scores",
                        outFiles,
                        ignore.case = TRUE,
                        fixed = FALSE,
                        value = TRUE
                        )
loadingsFile <- grep("pca_loadings",
                        outFiles,
                        ignore.case = TRUE,
                        fixed = FALSE,
                        value = TRUE
                        )



message("genotype file: ", genoDataFile)
message("pca scores file: ", scoresFile)
message("pca loadings file: ", loadingsFile)


if (is.null(genoDataFile))
{
  stop("genotype dataset missing.")
}

if (is.null(scoresFile))
{
  stop("Scores output file is missing.")
}

if (is.null(loadingsFile))
{
  stop("Laodings file is missing.")
}

genoData <- read.table(genoDataFile,
                        header = TRUE,
                        row.names = 1,
                        sep = "\t",
                        na.strings = c("NA", " ", "--", "-", "."),
                        dec = "."
                        )


if (sum(is.na(genoData)) > 0) {
    message("sum of geno missing values, ", sum(is.na(genoData)) )
    genoData <-kNNImpute(genoData, 10)
    genoData <-as.data.frame(genoData)

    #extract columns with imputed values
    genoData <- subset(genoData,
                       select = grep("^x", names(genoData))
                       )

    #remove prefix 'x.' from imputed columns
    names(genoData) <- sub("x.", "", names(genoData))

    genoData <- round(genoData, digits = 0)
    genoData <- data.matrix(genoData)
  }

pca <- prcomp(genoData, retx=TRUE)

scores <- round(pca$x[, 1:10], digits=2)

loadings <- round(pca$rotation[, 1:10], digits=5)

totalVar <- sum((pca$sdev)^2)

percentVar <- unlist(lapply(pca$sdev, function(x) round((x^2 / totalVar)*100, digits=2)))

totalperc <- sum(percentVar)

write.table(scores,
            file = scoresFile,
            sep = "\t",
            col.names = NA,
            quote = FALSE,
            append = FALSE
            )

write.table(loadings,
            file = loadingsFile,
            sep = "\t",
            col.names = NA,
            quote = FALSE,
            append = FALSE
            )

q(save = "no", runLast = FALSE)
# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  if (a<0) 
    stop("haven't handled the negative case but shouldn't happen for 289 million years when reading a unix time in ms so should be safe")
  c = a*2^32 +b
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
latencySeconds=readInteger()
src = readShort()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(latencySeconds)
print(src)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(12, latencySeconds)
assertEquals(1, src)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  if (a<0) 
    stop("haven't handled the negative case but shouldn't happen for millions of years when reading a unix time in ms so should be safe")
  c = a*2^32 +b
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
latencySeconds=readInteger()
src = readShort()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(latencySeconds)
print(src)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(12, latencySeconds)
assertEquals(1, src)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readInteger = function() readBin(file, integer(), size=4, endian="big")
readLong = function() { 
  a = readBin(file, integer(), size=4, endian="big")
  b = readBin(file, integer(), size=4, endian="big")
  # now need to do some bit manipulations to get the desired 8 byte integer as a double
  0
}
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { 
    warning(sprintf("expected %s but was %s", expected, actual)) 
  }

lat = readSingle()
lon = readSingle()
time = readLong()
latencySeconds=readInteger()
src = readShort()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(latencySeconds)
print(src)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(12, latencySeconds)
assertEquals(1, src)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    if (!other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using tracked_environments with ",
           "those using vanilla environments", call. = FALSE)
    }

    compare_head <- function(x, y) {
      m <- seq_len(min(length(x), length(y)))
      x[m] != y[m]
    }

    # TODO: (RK) Compare actual names rather than indices.
    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    if (other_runner$with_tracked_environment()) {
      stop("Cannot coalesce stageRunners using vanilla environments with ",
           "those using tracked_environments", call. = FALSE)
    }

    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    # TODO: (RK) Compare actual names rather than indices.
    compare_head <- function(x, y) { m <- min(length(x), length(y)); x[m] != y[m] }
    common <- sum(cumsum(compare_head(.self$stage_names(), other_runner$stage_names())) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  # We must do our own type checking on context for compatibility with
  # objectdiff::tracked_environment.
  if (!is.environment(context)) {
    stop("Please pass an ", sQuote("environment"), " as the context for ",
         "a stageRunner")
  }

  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (isTRUE(remember)) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()
    if (.self$with_tracked_environment()) {
      .self$.set_prefixes()
    } else if (length(stages) > 0) {
      # Set the first cache environment
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage)) { 
          function(...) { stage$run(verbose = verbose, .depth = .depth + 1, ...) }
        } else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) { stage$run(...) }
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]])) {
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        }

        function(...) {
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
        }
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message) {
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)
    }

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      if (nested_run) {
        before_env <- run_stage(..., remember_flag = TRUE)$before
      } else { # a leaf / terminal node
        before_env <- .self$.before_env(stage_index)
      }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) { run_stage(...) }
    }
    else if (remember) { run_stage(..., remember_flag = FALSE) }
    else { run_stage(...) }

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      .self$.mark_finished(stage_index)
    }

    if (display_message) {
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
    }
  }

  if (remember && remember_flag) { list(before = before_env, after = context) }
  else { invisible(TRUE) }
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
#' @note coalescing is ill-defined for stageRunner with unnamed stages,
#'    since it is impossible to tell when a stage has changed.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()

  if (.self$with_tracked_environment()) {
    common <- sum(cumsum(.self$stage_names() != other_runner$stage_names()) == 0)
    # Warning: Coalescing stageRunners with tracked_environments does not
    # duplicate the tracked_environment, so the other_runner becomes invalidated,
    # and this is a destructive action.
    # TODO: (RK) What if the tracked_environment given initially to the stageRunner
    # already has some commits?
    commits     <- package_function("objectdiff", "commits")
    `context<-` <- function(obj, value) {
      if (is.stagerunner(obj)) {
        obj$context <- value
        for (stage in obj$stages) { Recall(stage, value) }
      } else if (is.stageRunnerNode(obj)) {
        obj$.context <- value
        if (is.stagerunner(obj$callable)) { Recall(obj$callable, value) }
      }
    }
    .self$context  <- other_runner$context
    for (stage in .self$stages) { context(stage) <- other_runner$context }
    other_runner$context <- new.env(parent = emptyenv())
    commit_count   <- length(commits(.self$context)) 
    mismatch_count <- commit_count - (common + 1)
    if (mismatch_count > 0) {
      package_function("objectdiff", "force_push")(.self$context, commit_count)
      package_function("objectdiff", "rollback")  (.self$context, mismatch_count)
    }
  } else {
    stagenames <- names(other_runner$stages) %||% character(length(other_runner$stages))
    lapply(seq_along(other_runner$stages), function(stage_index) {
      # TODO: Match by name *OR* index
      if (stagenames[[stage_index]] %in% names(stages)) {
        # If both are stageRunners, try to coalesce our sub-stages.
        if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            is.stagerunner(other_runner$stages[[stage_index]])) {
            stages[[names(stages)[stage_index]]]$coalesce(
              other_runner$stages[[stage_index]])
        # If both are not stageRunners, copy the cached_env if and only if
        # the stored function and its environment are identical
        } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
            !is.stagerunner(other_runner$stages[[stage_index]]) &&
            !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
            #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
            #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
            # This is way too tricky and far beyond my abilities..
            #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
            #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
            ) {
          stages[[names(stages)[stage_index]]]$cached_env <<-
            new.env(parent = parent.env(context))
          if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
              is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
            copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                     other_runner$stages[[stage_index]]$cached_env)
            stages[[names(stages)[stage_index]]]$executed <<- 
              other_runner$stages[[stage_index]]$executed
          }
        }
      }
    })
    .set_parents()
  }
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Get an environment representing the context directly before executing a given stage.
#'
#' @note If there is a lot of data in the remembered environment, this function
#'   may be computationally expensive as it has to create a new environment
#'   with a copy of all the relevant data.
#' @param stage_index integer. The substage for which to grab the before
#'   environment.
#' @return a fresh new environment representing what would have been in
#'   the context as of right before the execution of that substage.
stageRunner__.before_env <- function(stage_index) {
  cannot_run_error <- function() {
    stop("Cannot run this stage yet because some previous stages have ",
         "not been executed.")
  }

  if (.self$with_tracked_environment()) {
    # We are using the objectdiff package and its tracked_environment,
    # so we have to "roll back" to a previous commit.
    current_commit <- paste0(.self$.prefix, stage_index)

    if (!current_commit %in% names(package_function("objectdiff", "commits")(context))) {
      if (`first_commit?`(current_commit)) {
        # TODO: (RK) Do this more robustly. This will fail if there is a 
        # first sub-stageRunner with an empty list as its stages.
        package_function("objectdiff", "commit")(context, current_commit)
      } else {
        cannot_run_error()
      }
    } else {
      package_function("objectdiff", "force_push")(context, current_commit)
    }

    env <- new.env(parent = package_function("objectdiff", "parent.env.tracked_environment")(context))
    copy_env(env, package_function("objectdiff", "environment")(context))
    env
  } else {
    env <- stages[[stage_index]]$cached_env
    if (is.null(env)) { cannot_run_error() }

    # Restart execution from cache, so set context to the cached environment.
    copy_env(context, env)
    env
  }
}

#' Mark a given stage as being finished.
#' 
#' @param stage_index integer. The index of the substage in this stageRunner.
stageRunner__.mark_finished <- function(stage_index) {
  node <- treeSkeleton$new(stages[[stage_index]])$successor()

  if (!is.null(node)) { # Prepare a cache for the future!
    if (.self$with_tracked_environment()) {
      # We assume the head for the tracked_environment is set correctly.
      package_function("objectdiff", "commit")(context, node$object$index())
    } else {
      node$object$cached_env <- new.env(parent = parent.env(context))
      copy_env(node$object$cached_env, context)
    }
  } else {
    # TODO: Remove this hack used for printing
    root <- .self$.root()
    root$.finished <- TRUE
  }
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'ANY', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical',
                .prefix = 'character'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root,

    # objectdiff intertwined functionality
    .set_prefixes  = stageRunner__.set_prefixes,
    .before_env    = stageRunner__.before_env,
    .mark_finished = stageRunner__.mark_finished,
    with_tracked_environment = function() { is(context, 'tracked_environment') }
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) },

    # objectdiff intertwining functions
    index    = function() {
      ix <- which(vapply(.self$.parent$stages,
        function(x) identical(.self, x$.self), logical(1)))
      paste0(.self$.parent$.prefix, ix)
    }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

library(github)
context("Basic Tests")

test_that("A basic rgithub context can be acquired", {
  create.github.context("https://api.github.com")
  repos <- get.user.repositories("cscheid")
  repos_overview <- do.call("rbind",
                            lapply(repos$content[1:5], function(x) {
                              data.frame(name = x$name,
                                         owner = x$owner$login,
                                         updated_at = x$updated_at)}))
  cat("\n")
  print(repos_overview)
})
library(xlsx)
dataset <- read.xlsx("karina/dataset.xlsx", sheetIndex=1)
options(width=10000) 

get <- function(geneName) {
  a = dataset[dataset$Genes == geneName,];
  return (a) 
}

genes <- function() {
    return (as.character(dataset$David.Input))
} 

fc <- function(genes) {
    a = dataset[match(genes, dataset$Genes),];
    b = as.numeric(as.character(a$dm))
    return (b) 
}

pvalues <- function(genes) { 
    a = dataset[match(genes, dataset$Genes),];
    b = as.numeric(as.character(a$BH_adj_pval))
    return(b) 
}

exprs <- function(gene) { 
  return 
}
file = file("target/123456790.track","rb")
readSingle = function() readBin(file, single(), size=4, endian="big")
readLong = function() readBin(file, integer(), size=8, endian="big")
readByte = function() readBin(file, integer(), size=1, endian="big")
readShort = function() readBin(file, integer(), size=2, endian="big") 
assertEquals = function(expected, actual) 
  if (expected != actual) { warning(sprintf("expected %s but was %s", expected, actual)) }

lat = readSingle()
lon = readSingle()
time = readLong()
nav = readByte()
rot = readByte()
sog = readShort()
cog = readShort()
heading = readShort()
cls = readByte()

print(lat)
print(lon)
print(time)
print(nav)
print(rot)
print(sog)
print(cog)
print(heading)
print(cls)

# test returned values
assertEquals(-10, lat)
assertEquals(135, lon)
assertEquals(1421708455237, time)
assertEquals(7, nav)
assertEquals(75, sog)
assertEquals(450, cog)
assertEquals(46, heading)
assertEquals(1, cls)


setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                defining_environment = 'environment',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director, defining_environment) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      defining_environment <<- defining_environment
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        environment(injects$resource) <- defining_environment
        injects$resource_name <- resource_key
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        environment(injects$helper) <- defining_environment
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        fn <- function(source_args) { do.call(base::source, source_args)$value }
        environment(fn) <- defining_environment
        list(value = fn(source_args), preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                defining_environment = 'environment',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director, defining_environment) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      defining_environment <<- defining_environment
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_name <- resource_key
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        fn <- function(source_args) { do.call(base::source, source_args)$value }
        environment(fn) <- defining_environment
        list(value = fn(source_args), preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
load("starter.RData")
load("gloc.RData")


##' Fetches the chromosomal locations for all genes and sorts them within each chromosome. 
##' @params tcgaResults the list with TCGA results
##' @params ccleResults the list with CCLE results
##' @return a data.frame with locations for all genes
##' @author Andreas Schlicker (a.schlicker@nki.nl)
sortGenesByLocation = function(tcgaResults, ccleResults) {
	# Genes in all cancer types
	genes = rownames(tcgaResults[[1]]$prioritize.combined)
	for (n in 2:length(tcgaResults)) {
		genes = intersect(genes, rownames(tcgaResults[[n]]$prioritize.combined))
	}
	for (n in 1:length(ccleResults)) {
		genes = intersect(genes, rownames(ccleResults[[n]]$prioritize.combined))
	}

	# Find all gene locations
	mart = useMart(host="ensembl.org", path="/biomart/martservice", biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
	geneLoc = getBM(attributes=c("hgnc_symbol", "chromosome_name", "start_position", "end_position", "strand", "band"), filters=c("hgnc_symbol"), values=genes, mart=mart)
	# Remove all non-standard chromosome names and make everything numeric
	geneLoc = geneLoc[which(geneLoc[, "chromosome_name"] %in% c("1", "2", "3", "4", "5", "6", "7", "8", 
																															"9", "10", "11", "12", "13", "14", "15", 
																															"16", "17", "18", "19", "20", "21", "22", 
																															"X", "Y")), ]
	geneLoc[which(geneLoc[, "chromosome_name"] == "X"), "chromosome_name"] = "23"
	geneLoc[which(geneLoc[, "chromosome_name"] == "Y"), "chromosome_name"] = "24"
	geneLoc[, "chromosome_name"] = as.integer(geneLoc[, "chromosome_name"])
	
	geneLoc[which(geneLoc[, "strand"] == 1), "strand"] = "+"
	geneLoc[which(geneLoc[, "strand"] == -1), "strand"] = "-"
	
	# Return the sorted gene information
	geneLoc[order(geneLoc$chromosome_name, geneLoc$start_position), ]
}


##' Generates a chromosome plot for the selected score or the number of affected samples.
##' @params geneLocs the data.frame returned by sortGenesByLocation()
##' @params results either tcgaResults or ccleResults
##' @params cancType the selected four letter cancer code
##' @params chrom the selected chromosome; X is coded as 23 and Y as 24
##' @params scoreType which score was selected; one of "OG", "TS", "CO"
##' @return a list with two plotting objects, "score" the actual score and "affected" the percentage of affected samples
##' @author Andreas Schlicker (a.schlicker@nki.nl) 
getScorePlot = function(geneLocs, results, cancType, chrom, scoreType) {
	scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
	
	# Get the genes for the selected chromosome
	genes = subset(geneLocs, chromosome_name==chrom)
	
	# Get the score vector
	score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.score"]
	# And the percentage of affected samples
	affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"]
	if (scoreType == "TS") {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.score"] * -1
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	} else {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "combined.score"]
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"] - 
							 results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	}
	
	# Plot two tracks, one for scores and the other one for percent affected samples 
	list(score=plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
						ranges=IRanges(start=genes[, "start_position"],
						       	       end=genes[, "end_position"]),
						score,
					        strand="*")), 
			      type=c("h", "g"),
			      ylim=c(min(score), max(score)),
			      col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
			      main=""),
	     affected=plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
		      	      			   ranges=IRanges(start=genes[, "start_position"],
		      	      			   		  end=genes[, "end_position"]),
		      	      			   affected,
						   strand="*")), 
				 type=c("h", "g"),
				 ylim=c(min(affected), max(affected)),
				 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
				 main=""))
}

## function for plotting the score data track across selected chromosome and cancer
getScorePlot2 = function(geneLocs, results, cancType, chrom, scoreType) {
  scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
  
  # Get the genes for the selected chromosome
  genes = subset(geneLocs, chromosome_name==chrom)
  
  # Get the score vector and the percentage of affected samples
  if (scoreType == "OG"){
    score = results[[cancType]][genes[, "hgnc_symbol"], "og.score"]
    #affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"]    
  }else if (scoreType == "TS") {
    score = results[[cancType]][genes[, "hgnc_symbol"], "ts.score"] * -1
    #affected = results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  } else {
    score = results[[cancType]][genes[, "hgnc_symbol"], "combined.score"]
    #affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"] - 
      results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  }
  
  # Plot two tracks, one for scores and the other one for percent affected samples 
  plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
                                          ranges=IRanges(start=genes[, "start_position"],
                                                         end=genes[, "end_position"]),
                                          score,
                                          strand="*")), 
                        type=c("h", "g"),
                        ylim=c(min(score), max(score)),
                        col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
                        main="")
}

## function for plotting the percentage of affected samples data track across selected chromosome and cancer
getAffectedPlot2 = function(geneLocs, results, cancType, chrom, scoreType) {
  scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
  
  # Get the genes for the selected chromosome
  genes = subset(geneLocs, chromosome_name==chrom)
  
  # Get the score vector and the percentage of affected samples
  if (scoreType == "OG"){
    #score = results[[cancType]][genes[, "hgnc_symbol"], "og.score"]
    affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"]    
  }else if (scoreType == "TS") {
    #score = results[[cancType]][genes[, "hgnc_symbol"], "ts.score"] * -1
    affected = results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  } else {
    #score = results[[cancType]][genes[, "hgnc_symbol"], "combined.score"]
    affected = results[[cancType]][genes[, "hgnc_symbol"], "og.affected.rel"] - 
      results[[cancType]][genes[, "hgnc_symbol"], "ts.affected.rel"]
  }
  
  # Plot two tracks, one for scores and the other one for percent affected samples 
  plotTracks(DataTrack(GRanges(seqnames=as.character(chrom),
                                             ranges=IRanges(start=genes[, "start_position"],
                                                            end=genes[, "end_position"]),
                                             affected,
                                             strand="*")), 
                           type=c("h", "g"),
                           ylim=c(min(affected), max(affected)),
                           col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
                           main="")
}


## main call to plot function
## view 1
comp3view1Plot <- function (cancer,scoreType,chr)
{
  if (scoreType == "TS")
  {
    res <- getScorePlot2(gloc, tcgaResultsPlotTrack, cancer, chr, 'TS')
  }else{
    res <- getScorePlot2(gloc, ccleResultsPlotTrack, cancer, chr, 'OG')
  }
  res
}

## view 2
comp3view2Plot <- function (cancer,scoreType,chr)
{
  if (scoreType == "TS")
  {
    res <- getAffectedPlot2(gloc, tcgaResultsPlotTrack, cancer, chr, 'TS')
  }else{
    res <- getAffectedPlot2(gloc, ccleResultsPlotTrack, cancer, chr, 'OG')
  }
  res
}

#' GUI for running LandsatLinkr
#'
#' GUI for running LandsatLinkr
#' @export

run_landsatlinkr = function(){
  
  choices = c("Prepare MSS",
              "Prepare TM/ETM+",
              "Calibrate MSS to TM/ETM+",
              "Composite imagery")
  
  selection = select.list(choices, title = "Select a process to run")
  if(selection == "Prepare MSS"){process = seq(1:5)}
  if(selection == "Prepare TM/ETM+"){process = 6}
  if(selection == "Calibrate MSS to TM/ETM+"){process = 7}
  if(selection == "Composite imagery"){process = 8}
  
  
  choices = c("No", "Yes")
  selection = select.list(choices, title = "Process in parallel using 2 cores when possible?")
  if(selection == "No"){cores = 1}
  if(selection == "Yes"){cores = 2}
  
  if(sum(process %in% seq(1,6)) > 0){
    scenedir = choose.dir(caption = "Select an MSS or TM/ETM+ scene directory. ex. 'C:/mss/036032'")
    reso = 60 #set default
    proj = "albers" #set default
    if(sum(process %in% c(1,6)) > 0){
      choices = c("30 meter", "60 meter")
      selection = select.list(choices, title = "Select a pixel resolution to use")
      if(selection == "30 meter"){reso = 30}
      if(selection == "60 meter"){reso = 60}
      
      choices = c("Native NAD83 UTM", "USGS North American Albers")
      selection = select.list(choices, title = "Select a map projection to use")
      if(selection == "Native NAD83 UTM"){proj = "default"}
      if(selection == "USGS North American Albers"){proj = "albers"}
    }
    
    demfile=NULL
    if(all(is.na(match(process,5))) == F){
      demfile = choose.files(caption = "Select a scene corresponding DEM file", multi=F)
    }
    #return(list(scenedir, demfile, proj, reso, process,cores))
    prepare_images(scenedir, demfile, proj=proj, reso=reso, process=process,cores=cores)
  }
  
  ################################
  #msscal and mixel
  if(sum(process %in% c(7,8)) > 0){
    if(sum(process %in% 7) > 0){
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      outdir=NULL
      index=NULL
      runname=NULL  
    }
    
    
    if(sum(process %in% 8) > 0){
      choices = c("No", "Yes")
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-1 scene directory to add?")
        if(answer == "Yes"){msswrs1dir = c(msswrs1dir, choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'"))}
      }
      
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-2 scene directory to add?")
        if(answer == "Yes"){msswrs2dir = c(msswrs2dir, choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'"))}
      }
      
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another TM WRS-2 scene directory to add?")
        if(answer == "Yes"){tmwrs2dir = c(tmwrs2dir, choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'"))}
        
        
        outdir = choose.dir(caption = "Select a directory to write the outputs to. ex. 'C:/composites/wrs2_034032'")
        
        choices = c("Tasseled cap angle",
                    "Tasseled cap brightness",
                    "Tasseled cap greenness",
                    "Tasseled cap wetness",
                    "All")
        selection = select.list(choices, title = "Select an index to create composites for")
        if(selection == "Tasseled cap angle"){index = "tca"}
        if(selection == "Tasseled cap brightness"){index = "tcb"}
        if(selection == "Tasseled cap greenness"){index = "tcg"}
        if(selection == "Tasseled cap wetness"){index = "tcw"}
        if(selection == "All"){index = "all"}
        
        runname = readline("Provide a unique name for the composite series. ex. project1: ")
        
        choices = c("From file",
                    "Provide coordinates")
        selection = select.list(choices, title = "What area do you want to create composites for?")
        if(selection == "From file"){useareafile = choose.files(caption = "Select a 'usearea' file", multi=F)}
        if(selection == "Provide coordinates"){
          check = 0
          while(check != 2){
            print("Please provide min and max xy coordinates (in image set projection units) defining a study area that intersects the image set")
            xmx = as.numeric(readline("max x coordinate: "))
            xmn = as.numeric(readline("min x coordinate: "))
            ymx = as.numeric(readline("max y coordinate: "))
            ymn = as.numeric(readline("min y coordinate: "))
            check = (xmx > xmn) + (ymx > ymn)
            if(check != 2){print("error - coordinates do not create a square - try again")}
          }
          useareafile = file.path(outdir, paste(runname,"_usearea.tif",sep=""))
          make_usearea_file(msswrs1dir[i], useareafile, xmx, xmn, ymx, ymn)
        }
      }
    }
    if(sum((process %in% 7) > 0)){process[1] = 1}
    if(sum((process %in% 8) > 0)){process[process==8] = 2}
    #return(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,cores,process)
    calibrate_and_composite(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=cores, process=process)
  } 
}
#' Convert DN values to surface reflectance
#'
#' Convert DN values to surface reflectance using the COST model with dark object subtraction
#' @param file The full path name of the *archv file
#' @param drkobjv dark object values from mssdofinder
#' @import raster
#' @export


msscost = function(file, drkobjv){
  
  #link to the equations to convert DN to TOA and TOA to SR
  #http://landsathandbook.gsfc.nasa.gov/data_prod/prog_sect11_3.html
  
  #read in the image metadata  
  info = get_metadata(file)
  
  #define esun values for mss (chander et al 2009 summary of current radiometric calibration coefficients... RSE 113)
  if(info$sensor == "LANDSAT_1"){esun = c(1823,1559,1276,880.1)}
  if(info$sensor == "LANDSAT_2"){esun = c(1829,1539,1268,886.6)}
  if(info$sensor == "LANDSAT_3"){esun = c(1839,1555,1291,887.9)}
  if(info$sensor == "LANDSAT_4"){esun = c(1827,1569,1260,866.4)}
  if(info$sensor == "LANDSAT_5"){esun = c(1824,1570,1249,853.4)}
  
  #define the earth sun distance 
  d = 1.01497  #Earth-Sun Distance in Astronomical Units at DOY 213
  
  #read in the DN image data  
  b = brick(file)
  img = as.array(b) 
  
  drkobjv[1] = (info$b1gain*drkobjv[1])+info$b1bias
  drkobjv[2] = (info$b2gain*drkobjv[2])+info$b2bias
  drkobjv[3] = (info$b3gain*drkobjv[3])+info$b3bias
  drkobjv[4] = (info$b4gain*drkobjv[4])+info$b4bias
  
  img[,,1] = ((info$b1gain*img[,,1])+info$b1bias)-drkobjv[1]
  img[,,2] = ((info$b2gain*img[,,2])+info$b2bias)-drkobjv[2]
  img[,,3] = ((info$b3gain*img[,,3])+info$b3bias)-drkobjv[3]
  img[,,4] = ((info$b4gain*img[,,4])+info$b4bias)-drkobjv[4]
  
  img[img<0] = 0
  
  #convert solar zenith angle to radians for cos calculation (r expects radians)
  sunzenith = info$sunzen/57.2958 
  
  #calulate SR from DOS TOA
  img[,,1] = (pi * img[,,1] * (d^2))/(esun[1] * cos(sunzenith))
  img[,,2] = (pi * img[,,2] * (d^2))/(esun[2] * cos(sunzenith))
  img[,,3] = (pi * img[,,3] * (d^2))/(esun[3] * cos(sunzenith))
  img[,,4] = (pi * img[,,4] * (d^2))/(esun[4] * cos(sunzenith))
  
  #scale
  img = round(img * 10000)
  
  img = setValues(b,img)
  dataType(img) = "INT2S"
  projection(img) = set_projection(file)
  img = as(img, "SpatialGridDataFrame")         #convert the raster to SGHF so it can be written using GDAL (faster than writing it with the raster package)
  outfile = sub("archv", "dos_sr", file)
  writeGDAL(img, outfile, drivername = "GTiff", type = "Int16", mvFlag = -32768, options="INTERLEAVE=BAND")
  
}# Command line tools don’t want to clutter their output with unnecessary noise.
library = function (...)
    suppressMessages(base::library(...))

#' The command line arguments
args = commandArgs(trailingOnly = TRUE)

#' Quit the program
#'
#' @param code numeric exit code (default: \code{0})
exit = function (code = 0)
    quit(save = 'no', status = if (is.null(code)) 0 else code)

#' Execute the \code{entry_point} function defined by the caller
run = function (entry_point = main) {
    caller = parent.frame()
    caller_name = evalq(modules::module_name(), envir = caller)

    if (is.null(caller_name)) {
        if (class(substitute(entry_point)) == '{')
            exit(entry_point)

        exit(eval(substitute(main(), list(main = entry_point)), envir = caller))
    }
}

# Load the Motor Trend data set
data(mtcars)
columns <- c(2,8,10,11) # Columns to convert to factors
mtcars[, columns] <- lapply(mtcars[,columns], as.factor) 
mtcars[, 9] <- factor(mtcars[, 9], labels=c("Auto", "Manual"))
predict_mtcars <- mtcars[1,]
rownames(predict_mtcars) <-NULL
shinyServer(function(input, output, session) {
        output$controls <- renderUI({
                if (is.null(input$tabs)) return()
                list(
                        if(any(input$predictors == "cyl")) 
                                sliderInput("cyl", 
                                            "Number of cylinders:", 
                                            min = 4, 
                                            max = 8,
                                            value = 4,
                                            step = 2),
                        if(any(input$predictors=="disp")) 
                                sliderInput("disp", 
                                            "Displacement:", 
                                            min = min(mtcars$disp), 
                                            max = max(mtcars$disp),
                                            value = min(mtcars$disp)),
                         if(any(input$predictors=="hp"))
                                sliderInput("hp", 
                                    "Gross Horsepower:", 
                                    min = min(mtcars$hp), 
                                    max = max(mtcars$hp),
                                    value = min(mtcars$hp)),
                        if(any(input$predictors=="drat"))
                                sliderInput("drat", 
                                    "Rear axle ratio:", 
                                    min = min(mtcars$drat), 
                                    max = max(mtcars$drat),
                                    value = min(mtcars$drat)),
                        if(any(input$predictors=="wt"))
                                sliderInput("wt", 
                                    "Weight:", 
                                    min = min(mtcars$wt), 
                                    max = max(mtcars$wt),
                                    value = min(mtcars$wt)),
                        if(any(input$predictors=="qsec"))
                                sliderInput("qsec", 
                                    "1/4 mile time:", 
                                    min = min(mtcars$qsec), 
                                    max = max(mtcars$qsec),
                                    value = min(mtcars$qsec)),
                        if(any(input$predictors=="vs"))
                                selectInput("vs", label = "Engine shape:", 
                                    choices = list("V" = 0, "Straight" = 1), 
                                    selected = 0),
                        if(any(input$predictors=="am"))
                                selectInput("am", label = "Transmission:", 
                                    choices = list("Automatic" = "Auto", "Manual" = "Manual"), 
                                    selected = 0),
                        if(any(input$predictors=="gear"))
                                sliderInput("gear", 
                                    "Gears:", 
                                    min = 3, 
                                    max = 5,
                                    value = 3,
                                    step=1),
                        if(any(input$predictors=="carb"))
                                selectInput("carb", label="Carburators:", 
                                    choices = list("1"=1,"2"=2,"3"=3,"4"=4,"6"=6,"8"),
                                    selected=1)
                )
                
        })
        
        model <- reactive({
                input$goButton
                isolate({
                        predictors <- input$predictors
                        sub_mtcars <<- mtcars[,c("mpg", predictors)]
                        lm(mpg ~ ., data=sub_mtcars)
                })
        })
        
        output$plot <- renderPlot({
                par(mfrow=c(2,2))
                plot(model())
        })
        output$summary <- renderPrint({
                summary(model())
        }) 

        observe({
                if (length(input$predictors) == 0)
                        updateCheckboxGroupInput(session, "predictors",
                                                 selected = "cyl")
        })        
        
        observe({
                if(input$tabs == "Model") return()
                if (!all(sort(input$predictors)==sort(names(sub_mtcars)[-1]))) 
                        updateTabsetPanel(session, "tabs", selected = "Model")
                
        })
        
        output$prediction <- renderPrint({
                if(!is.null(input$cyl)) predict_mtcars$cyl <- as.factor(input$cyl)
                if(!is.null(input$disp)) predict_mtcars$disp <- input$disp
                if(!is.null(input$hp)) predict_mtcars$hp <- input$hp
                if(!is.null(input$drat)) predict_mtcars$drat <-input$drat
                if(!is.null(input$wt)) predict_mtcars$wt <- input$wt
                if(!is.null(input$qsec)) predict_mtcars$qsec <- input$qsec
                if(!is.null(input$vs)) predict_mtcars$vs <- as.factor(input$vs)
                if(!is.null(input$am)) predict_mtcars$am <- as.factor(input$am)
                if(!is.null(input$gear)) predict_mtcars$gear <- as.factor(input$gear)
                if(!is.null(input$carb)) predict_mtcars$carb <- as.factor(input$carb)
                output$values <- renderPrint({
                        predict_mtcars[names(sub_mtcars[])]
                })
                paste(round(predict(model(),predict_mtcars),2), "mpg")
                    
        }) 
        
        
 
}
)# Pobrišemo PDF-je in počistimo delovno okolje
silent <- TRUE
source("clearpdf.r", encoding = "UTF-8")

# 2. faza: Obdelava, uvoz in čiščenje podatkov
source("uvoz/uvoz.r", encoding = "UTF-8")

# 3. faza: Analiza in vizualizacija podatkov
source("vizualizacija/vizualizacija.r", encoding = "UTF-8")

# 4. faza: Napredna analiza podatkov
source("analiza/analiza.r", encoding = "UTF-8")

cat("Končano.\n")REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Canonical words"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Purpose: {
		These words are used internally by REBOL and must have specific canon
		word values in order to be correctly identified.
	}
]

any-type!
any-word!
any-path!
any-function!
number!
scalar!
series!
any-string!
any-object!
any-block!

datatypes

native
self
none
true
false
on
off
yes
no
pi

rebol

system

;boot levels
base
sys
mods

;reflectors:
spec
body
words
values
types
title

x
y
+
-
*
unsigned
-unnamed- 	; lambda (unnamed) functions
-apply-		; apply func
code		; error field
delect

; Secure:  (add to system/state/policies object too)
secure
protect
net
call
envr
eval
memory
debug
browse
extension
;dir - below
;file - below

; Time:
hour
minute
second

; Date:
year
month
day
time
date
weekday
julian
yearday
zone
utc

; Parse: - These words must not reserved above!!
parse
|	 ; must be first
; prep words:
set  
copy
some
any
opt
not
and
then
remove
insert
change
if
fail
reject
while
return
limit
??
accept
break
; match words:
skip
to
thru
quote
do
into
only
end  ; must be last

; Event:
type
key
port
mode
window
double
control
shift

; Checksum
sha1
md4
md5
crc32
adler32

; Codec actions
identify
decode
encode

; Schemes
console
file
dir
event
callback
dns
tcp
udp
clipboard
serial
signal

; Serial parameters
; Parity
odd
even
; Control flow
hardware
software

; Struct
uint8
int8
uint16
int16
uint32
int32
uint64
int64
float
;double ;reuse earlier definition
pointer
addr
raw-memory
raw-size
rebval

;routine
void
library
name
abi
stdcall
fastcall
sysv
thiscall
unix64
ms-cdecl
win64
default
vfp ;arm
o32; mips abi
n32; mips abi
n64; mips abi
o32-soft-float; mips abi
n32-soft-float; mips abi
n64-soft-float; mips abi
...
varargs

; Gobs:
gob
offset
size
pane
parent
image
draw
text
effect
color
flags
rgb
alpha
data
resize
rotate
no-title
no-border
dropable
transparent
popup
modal
on-top
hidden
owner
active
minimize
maximize
restore 
fullscreen

*port-modes*

; posix signal names
all
sigalrm
sigabrt
sigbus
sigchld
sigcont
sigfpe
sighup
sigill
sigint
sigkill
sigpipe
sigquit
sigsegv
sigstop
sigterm
sigtstp
sigttin
sigttou
sigusr1
sigusr2
sigpoll
sigprof
sigsys
sigtrap
sigurg
sigvtalrm
sigxcpu
sigxfsz

bits
crash
crash-dump
watch-recycle
watch-obj-copy
stack-size

;call/info
id
exit-code
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Canonical words"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Purpose: {
		These words are used internally by REBOL and must have specific canon
		word values in order to be correctly identified.
	}
]

any-type!
any-word!
any-path!
any-function!
number!
scalar!
series!
any-string!
any-object!
any-block!

datatypes

native
self
none
true
false
on
off
yes
no
pi

rebol

system

;boot levels
base
sys
mods

;reflectors:
spec
body
words
values
types
title

x
y
+
-
*
unsigned
-unnamed- 	; lambda (unnamed) functions
-apply-		; apply func
code		; error field
delect

; Secure:  (add to system/state/policies object too)
secure
protect
net
call
envr
eval
memory
debug
browse
extension
;dir - below
;file - below

; Time:
hour
minute
second

; Date:
year
month
day
time
date
weekday
julian
yearday
zone
utc

; Parse: - These words must not reserved above!!
parse
|	 ; must be first
; prep words:
set  
copy
some
any
opt
not
and
then
remove
insert
change
if
fail
reject
while
return
limit
??
accept
break
; match words:
skip
to
thru
quote
do
into
only
end  ; must be last

; Event:
type
key
port
mode
window
double
control
shift

; Checksum
sha1
md4
md5
crc32
adler32

; Codec actions
identify
decode
encode

; Schemes
console
file
dir
event
callback
dns
tcp
udp
clipboard
serial
signal

; Serial parameters
; Parity
odd
even
; Control flow
hardware
software

; Struct
uint8
int8
uint16
int16
uint32
int32
uint64
int64
float
;double ;reuse earlier definition
pointer
addr
raw-memory
raw-size
rebval

;routine
void
library
name
abi
stdcall
fastcall
sysv
thiscall
unix64
ms-cdecl
win64
default
vfp ;arm
o32; mips abi
n32; mips abi
n64; mips abi
o32-soft-float; mips abi
n32-soft-float; mips abi
n64-soft-float; mips abi
...
varargs

; Gobs:
gob
offset
size
pane
parent
image
draw
text
effect
color
flags
rgb
alpha
data
resize
rotate
no-title
no-border
dropable
transparent
popup
modal
on-top
hidden
owner
active
minimize
maximize
restore 
fullscreen

*port-modes*

; posix signal names
all
sigalrm
sigabrt
sigbus
sigchld
sigcont
sigfpe
sighup
sigill
sigint
sigkill
sigpipe
sigquit
sigsegv
sigstop
sigterm
sigtstp
sigttin
sigttou
sigusr1
sigusr2
sigpoll
sigprof
sigsys
sigtrap
sigurg
sigvtalrm
sigxcpu
sigxfsz

bits
crash
crash-dump
watch-recycle
watch-obj-copy
stack-size

;call/info
id
exit-code
##' Generates pathview plots for all given results. This function can be used to plot 
##' different scores for one cancer type or one score across different cancer types.
##' If cancers == "all", only the first score in scores is plotted. In all other cases,
##' all scores are plotted for the first cancer only. 
##' @param tcgaResults the result list from a TCGA prioritization run
##' @param ccleResults the result list from a CCLE prioritization run
##' @param pathways vector with KEGG pathway IDs to plot; default: NULL (all pathways)
##' @param cancers vector of names of cancer types to plot; default: all
##' @param scores vector of names of the scores to plot; default: combined.score
##' @param out.dir directory for output files; default: "."
##' @param out.suffix suffix to be added to output plots; default: ""
##' @param kegg.dir directory with predownloaded KEGG files; all new downloaded files will be stored there;
##' default: "."
##' @author Andreas Schlicker
generatePathview = function(tcgaResults, ccleResults, pathway, cancers="avg",
			    what=c("tcga", "ccle", "both"),
			    out.dir=".", out.suffix="", kegg.dir=".", 
	                    scores="combined.score") {
	# Get the score matrix and combine them if necessary
	if (what == "tcga") {
		if (cancers == "all") {
			cancers = names(tcgaResults)
		}
		scoreMat = pathviewMat(tcgaResults[intersect(cancers, names(tcgaResults))], scores[1])
	} else if (what == "ccle") {
		f (cancers == "all") {
			cancers = names(ccleResults)
		}
		scoreMat = pathviewMat(ccleResults[intersect(cancers, names(ccleResults))], scores[1])
	} else {
		scoreMat = cbind(tcgaResults[[cancers[1]]]$prioritize.combined[, scores],
				 ccleResults[[cancers[1]]]$prioritize.combined[, scores])
	}
	
	if (scores == "combined.score") {
		low = list(gene="#034b87", cpd="blue")
		mid = list(gene="gray98", cpd="gray")
		high = list(gene="#880000", cpd="yellow")
		both.dirs = list(gene=TRUE, cpd=TRUE)
	} else if (scores == "og.score") {
		low = list(gene="gray98", cpd="blue")
		mid = list(gene="gray98", cpd="gray")
		high = list(gene="#880000", cpd="yellow")
		both.dirs = list(gene=FALSE, cpd=FALSE)
	} else (scores == "ts.score") {
		low = list(gene="gray98", cpd="blue")
		mid = list(gene="gray98", cpd="gray")
		high = list(gene="#034b87", cpd="yellow")
		both.dirs = list(gene=FALSE, cpd=FALSE)
	}
	
	limit = ifelse(is.null(limit), max(abs(scoreMat), na.rm=TRUE), limit)
	
	# Save working directory and switch to new one
	oldwd = getwd()
	setwd(out.dir)
	
	# Generate plots
	invisible(pathview(gene.data=scoreMat, pathway.id=pathway,
		           kegg.native=TRUE, gene.idtype="SYMBOL",
		           out.suffix=out.suffix, kegg.dir=kegg.dir,
		           limit=list(gene=limit, cpd=1), node.sum="max.abs",
		           multi.state=TRUE, low=low, mid=mid, high=high),
			   both.dirs=both.dirs)
	# Set old working directory
	setwd(oldwd)
}
#!/usr/bin/env Rscript

# Parse the --file= argument out of command line args and
# determine where base directory is so that we can source
# our common sub-routines
arg0 <- sub("--file=(.*)", "\\1", grep("--file=", commandArgs(), value = TRUE))
dir0 <- dirname(arg0)
source(file.path(dir0, "common.r"))

theme_set(theme_grey(base_size = 17))

# Setup parameters for the script
params = matrix(c(
  'help',    'h', 0, "logical",
  'width',   'x', 2, "integer",
  'height',  'y', 2, "integer",
  'outfile', 'o', 2, "character",
  'indir',   'i', 2, "character",
  'tstart',  '1',  2, "integer",
  'tend',    '2',  2, "integer",
  'ylabel1stgraph', 'Y',  2, "character"
  ), ncol=4, byrow=TRUE)

# Parse the parameters
opt = getopt(params)

if (!is.null(opt$help))
  {
    cat(paste(getopt(params, command = basename(arg0), usage = TRUE)))
    q(status=1)
  }

# Initialize defaults for opt
if (is.null(opt$width))   { opt$width   = 1280 }
if (is.null(opt$height))  { opt$height  = 1280 }
if (is.null(opt$indir))   { opt$indir  = "current"}
if (is.null(opt$outfile)) { opt$outfile = file.path(opt$indir, "summary.png") }
if (is.null(opt$ylabel1stgraph)) { opt$ylabel1stgraph = "Op/sec" }

# Load the benchmark data, passing the time-index range we're interested in
b = load_benchmark(opt$indir, opt$tstart, opt$tend)

# If there is no actual data available, bail
if (nrow(b$latencies) == 0)
{
  stop("No latency information available to analyze in ", opt$indir)
}

png(file = opt$outfile, width = opt$width, height = opt$height)

# First plot req/sec from summary
plot1 <- qplot(elapsed, successful / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = "Throughput") +

                geom_smooth(aes(y = successful / window, colour = "ok"), size=0.5) +
                geom_point(aes(y = successful / window, colour = "ok"), size=2.0) +

                geom_smooth(aes(y = failed / window, colour = "error"), size=0.5) +
                geom_point(aes(y = failed / window, colour = "error"), size=2.0) +

                scale_colour_manual("Response", values = c("#FF665F", "#188125"))

plot2 <- qplot(elapsed, starts / window, data = b$sessions,
                 geom = c("point"),
                 xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                 main = "Sessions") +

                 geom_point(aes(y = starts / window, colour = "starts"), size=2.0) +
                 geom_line( aes(y = starts / window, colour = "starts"), size=0.1) +

                 geom_point(aes(y = running, colour = "running"), size=2.0) +
                 geom_line( aes(y = running, colour = "running"), size=0.1) +

                 scale_colour_manual("Starts", values = c("#188125", "#FF665F"))

# Setup common elements of the latency plots
latency_plot <- ggplot(b$latencies, aes(x = elapsed)) +
                   facet_grid(. ~ op) +
                   labs(x = "Elapsed Secs", y = "Latency (ms)")

# Plot median, mean and 95th percentiles
plot3 <- latency_plot + labs(title = "Mean, Median, and 95th Percentile Latency") +
            geom_smooth(aes(y = median, color = "median"), size=0.5) +
            geom_point(aes(y = median, color = "median"), size=2.0) +

            geom_smooth(aes(y = mean, color = "mean"), size=0.5) +
            geom_point(aes(y = mean, color = "mean"), size=2.0) +

            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot 99th percentile
plot4 <- latency_plot + labs(title = "99th Percentile Latency") +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X99_9th","X99th" ),
            #                 labels = c("99.9th", "99th"))

# Plot 99.9th percentile
plot5 <- latency_plot + labs(title = "99.9th Percentile Latency") +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

# Plot 100th percentile
plot6 <- latency_plot + labs(title = "Maximum Latency") +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

grid.newpage()

pushViewport(viewport(layout = grid.layout(6, 1)))

vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

print(plot1, vp = vplayout(1,1))
print(plot2, vp = vplayout(2,1))
print(plot3, vp = vplayout(3,1))
print(plot4, vp = vplayout(4,1))
print(plot5, vp = vplayout(5,1))
print(plot6, vp = vplayout(6,1))

dev.off()
#' General-purpose data munging
#'
#' One can use \code{munge} to take a \code{data.frame}, apply a given set
#' of transformations, and persistently store the operations on
#' the \code{data.frame}, ready to run on a future \code{data.frame}.
#'
#' @param dataframe a data set to operate on.
#' @param ... usually a list specifying the necessary operations (see
#'    examples).
#' @param stagerunner logical or list. Whether to run the munge procedure or
#'    return the parametrizing stageRunner object (see package stagerunner).
#'    If a list, one can specify \code{remember = TRUE} to pass to the
#'    stageRunner initializer.
#' @param train_only logical. Whether or not to leave the \code{trained}
#'    parameter on each mungebit to \code{TRUE} or \code{FALSE} accordingly.
#'    For example, if \code{stagerunner = TRUE} and we are planning to re-use
#'    the stagerunner for prediction, it makes sense to leave the mungebits
#'    untrained. (Note that this will prevent one from being able to run the
#'    predict functions!)
#' @return data.frame that has had the specified operations applied to it,
#'    along with an additional property \code{mungepieces} that records
#'    the history of applied functions. These can be used to reproduce
#'    the transformations on e.g., a dataset that needs to have a
#'    prediction run.
#' @export
#' @examples
#' \dontrun{
#' iris2 <- munge(iris,
#'   list(column_transformation(function(x) 2 * x), 'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#'
#' iris2 <- munge(iris,
#'    # train function & predict function
#'    list(c(column_transformation(function(x) 2 * x),
#'         column_transformation(function(x) 3 * x)),
#'    # arguments to pass to transformation, i.e. column names in this case
#'    'Sepal.Length'))
#' stopifnot(iris2[['Sepal.Length']] == iris[['Sepal.Length']] * 2)
#' iris3 <- munge(iris, attr(iris2, 'mungepieces'))
#' # used transformations ("mungepieces") stored on iris2 and apply to iris3.
#' # They will remember that they've been trained already and run the
#' # prediction routine instead of the training routine. Note the above is
#' # also equivalent to the shortcut: munge(iris, iris2)
#' stopifnot(iris3[['Sepal.Length']] == iris[['Sepal.Length']] * 3)
#' }
munge <- function(dataframe, ..., stagerunner = FALSE, train_only = FALSE) {
  mungepieces <- list(...)
  if (length(mungepieces) == 0) return(dataframe)

  plane <- if (is.environment(dataframe)) dataframe else mungeplane(dataframe)

  if (is.data.frame(mungepieces[[1]]))
    mungepieces[[1]] <- attr(mungepieces[[1]], 'mungepieces')
  else if (is(mungepieces[[1]], 'tundraContainer'))
    mungepieces[[1]] <- mungepieces[[1]]$munge_procedure

  # If mungepieces[[1]] is of the form
  # list(list|mungepiece|function, list|mungepiece|function, ...)
  # just put it into mungepieces. This is so munge can be called as either
  # munge(dataframe, list(...)) or munge(dataframe, ...)
  if (length(mungepieces) == 1 && is.list(mungepieces[[1]]) &&
      all(unlist(lapply(mungepieces[[1]],
        function(x) is.mungepiece(x) || is.mungebit(x) || is.list(x) || is.function(x))))) {
      mungepieces <- mungepieces[[1]]
  }

  mungepieces <- lapply(mungepieces, parse_mungepiece,
                        train_only = !identical(train_only, FALSE))

  # order matters, do not parallelize!
  stages <- lapply(mungepieces, function(piece) {
    force(piece); function(env) piece$run(env)
  })
  stages <- append(stages, list(function(env) {
    # For now, store the mungepieces on the dataframe
    if (length(mungepieces) > 0)
      attr(env$data, 'mungepieces') <- append(attr(env$data, 'mungepieces'), mungepieces)
  }))
  names(stages)[length(stages)] <- "(Internal) Store munge procedure on dataframe"

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) require(stagerunner)
  remember <- if ('remember' %in% names(stagerunner)) stagerunner$remember else FALSE
  runner <- stageRunner$new(as(plane, 'environment'), stages, remember = remember)

  if (!missing(stagerunner) && !identical(stagerunner, FALSE)) runner
  else {
    runner$run()
    plane$data
  }
}

context("Basic Tests")

test_that("A basic rgithub context can be acquired", {
	create.github.context("https://api.github.com")
	repos <- get.user.repositories("cscheid")
	repos_overview <- do.call("rbind",
														lapply(repos$content[1:5], function(x) {
															data.frame(name = x$name,
																				 owner = x$owner$login,
																				 updated_at = x$updated_at)}))
	cat("\n")
	print(repos_overview)
})
context("Basic Tests")

test_that("A basic rgithub context can be acquired", {
  create.github.context("https://api.github.com")
  repos <- get.user.repositories("cscheid")
  print(repos)
})
#' GUI for running LandsatLinkr
#'
#' GUI for running LandsatLinkr
#' @export

run_landsatlinkr = function(){
  
  choices = c("Prepare MSS",
              "Prepare TM/ETM+",
              "Calibrate MSS to TM/ETM+",
              "Composite imagery")
  
  selection = select.list(choices, title = "Select a process to run")
  if(selection == "Prepare MSS"){process = seq(1:5)}
  if(selection == "Prepare TM/ETM+"){process = 6}
  if(selection == "Calibrate MSS to TM/ETM+"){process = 7}
  if(selection == "Composite imagery"){process = 8}
  
  
  choices = c("No", "Yes")
  selection = select.list(choices, title = "Process in parallel using 2 cores when possible?")
  if(selection == "No"){cores = 1}
  if(selection == "Yes"){cores = 2}
  
  if(sum(process %in% seq(1,6)) > 0){
    scenedir = choose.dir(caption = "Select an MSS or TM/ETM+ scene directory. ex. 'C:/mss/036032'")
    reso = 60 #set default
    proj = "albers" #set default
    if(sum(process %in% c(1,6)) > 0){
      choices = c("30 meter", "60 meter")
      selection = select.list(choices, title = "Select a pixel resolution to use")
      if(selection == "30 meter"){reso = 30}
      if(selection == "60 meter"){reso = 60}
      
      choices = c("Native NAD83 UTM", "USGS North American Albers")
      selection = select.list(choices, title = "Select a map projection to use")
      if(selection == "Native NAD83 UTM"){proj = "default"}
      if(selection == "USGS North American Albers"){proj = "albers"}
    }
    
    demfile=NULL
    if(all(is.na(match(process,5))) == F){
      demfile = choose.files(caption = "Select a scene corresponding DEM file", multi=F)
    }
    #return(list(scenedir, demfile, proj, reso, process,cores))
    prepare_images(scenedir, demfile, proj=proj, reso=reso, process=process,cores=cores)
  }
  
  ################################
  #msscal and mixel
  if(sum(process %in% c(7,8)) > 0){
    if(sum(process %in% 7) > 0){
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      outdir=NULL
      index=NULL
      runname=NULL  
    }
    
    
    if(sum(process %in% 8) > 0){
      choices = c("Yes", "No")
      msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-1 scene directory to add?")
        if(answer == "Yes"){msswrs1dir = c(msswrs1dir, choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'"))}
      }
      
      msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another MSS WRS-2 scene directory to add?")
        if(answer == "Yes"){msswrs2dir = c(msswrs2dir, choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'"))}
      }
      
      tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
      answer = "Yes"
      while(answer == "Yes"){
        answer = select.list(choices, title = "Is there another TM WRS-2 scene directory to add?")
        if(answer == "Yes"){tmwrs2dir = c(tmwrs2dir, choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'"))}
        
        
        outdir = choose.dir(caption = "Select a directory to write the outputs to. ex. 'C:/composites/wrs2_034032'")
        
        choices = c("Tasseled cap angle",
                    "Tasseled cap brightness",
                    "Tasseled cap greenness",
                    "Tasseled cap wetness")
        selection = select.list(choices, title = "Select an index to create composites for")
        if(selection == "Tasseled cap angle"){index = "tca"}
        if(selection == "Tasseled cap brightness"){index = "tcb"}
        if(selection == "Tasseled cap greenness"){index = "tcg"}
        if(selection == "Tasseled cap wetness"){index = "tcw"}
        
        runname = readline("Provide a unique name for the composite series. ex. project1: ")
        
        choices = c("From file")
        selection = select.list(choices, title = "What area do you want to create composites for?")
        if(selection == "From file"){useareafile = choose.files(caption = "Select a 'usearea' file", multi=F)}
      }
    }
    if(sum((process %in% 7) > 0)){process[1] = 1}
    if(sum((process %in% 8) > 0)){process[process==8] = 2}
    #return(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,cores,process)
    calibrate_and_composite(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=cores, process=process)
  } 
}
#' Calibrate MSS imagery to TM and make cloud-free composites 
#'
#' Calibrate MSS imagery to TM and make cloud-free composites   
#' @param msswrs1dir character. mss wrs1 directory path
#' @param msswrs2dir character. mss wrs2 directory path
#' @param tmwrs2dir character. tm wrs2 directory path
#' @param index character. spectral index to make composites for. options: "tca", "tcb", "tcg", "tcw"
#' @param outdir character. path to output directory
#' @param runname character. unique name for the composite set
#' @param useareafile character. path to usearea file
#' @param doyears ??? what years to composite
#' @param order character. how to order the images options "sensor_and_doy" and "doy"
#' @param overlap character. how to deal with overlapping images. options: "mean"
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @param process numeric. integer or vector specifying which processes to run: 1=msscal, 2=mixel
#' @import foreach
#' @import doParallel
#' @export


calibrate_and_composite = function(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=2, process=c(1,2)){
  
  #msscal
  if(all(is.na(match(process,1))) == F){
    print("Running msscal")
    t=proc.time()
    msscal(msswrs1dir, msswrs2dir, tmwrs2dir, cores=cores)
    print(proc.time()-t)
  }
  
  #mixel
  if(all(is.na(match(process,2))) == F){
    print("Running mixel")
    t=proc.time()
    mixel(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean")
    print(proc.time()-t)
  }
}#!/usr/bin/env Rscript

library(DNAcopy)

options(warn=-1)
args <-commandArgs(trailingOnly = TRUE)

setwd(args[1])

c1 <- read.table("ChrI")
c2 <- read.table("ChrII")
c3 <- read.table("ChrIII")
c4 <- read.table("ChrIV")
c5 <- read.table("ChrV")
c6 <- read.table("ChrVI")
c7 <- read.table("ChrVII")
c8 <- read.table("ChrVIII")
c9 <- read.table("ChrIX")
c10 <- read.table("ChrX")
c11 <- read.table("ChrXI")
c12 <- read.table("ChrXII")
c13 <- read.table("ChrXIII")
c14 <- read.table("ChrXIV")
c15 <- read.table("ChrXV")
c16 <- read.table("ChrXVI")

c1$chr <- 1
c2$chr <- 2
c3$chr <- 3
c4$chr <- 4
c5$chr <- 5
c6$chr <- 6
c7$chr <- 7
c8$chr <- 8
c9$chr <- 9
c10$chr <- 10
c11$chr <- 11
c12$chr <- 12
c13$chr <- 13
c14$chr <- 14
c15$chr <- 15
c16$chr <- 16


merged <- rbind(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16)

CNA.object <- CNA(merged$V1, merged$chr, merged$V2, data.type=("logratio"), presorted=TRUE)
CNA.smooth <- smooth.CNA(CNA.object)
CNA.segm <- segment(CNA.smooth)

pdf("cnv_report.pdf")

plot(CNA.segm, plot.type="w")
plot(CNA.segm, plot.type="s")
plot(CNA.segm, plot.type="p")

dev.off()








########################################
#
# Program to run DESeq2 on the count data
#
########################################

setwd("~/jen/Files/")
require(DESeq2)
require(plyr)
require(biomaRt)

##### Part 1: Read in the data

alldirectories = c("run60msrnaseqwtsplnlungbbreg","run61msrnaseqdkospbbregwtlnbreg","run68mousernaseqtregsplnlung","run69mousernaseqtregs")
countdirectory="/home/trevor/jen/counts/"
summarytabledirectory="/home/trevor/jen/summarytables/"

# Count data
curfilesc = NULL
filenamesc = NULL
curtablefilec = vector("list",length(alldirectories))
removesummaryinfo <- function(data) {
	newdata = data[-which(substr(data$V1,1,2)=="__"),]
return(newdata)
}
for(i in 1:length(alldirectories)) {
	curdirectory = alldirectories[i]
	filenames = list.files(paste(countdirectory,curdirectory,"/",sep=""), pattern="*.txt", full.names=FALSE)
	curfiles = lapply(paste(countdirectory,curdirectory,"/",filenames,sep=""), read.table)
	curfilesc = c(curfilesc,lapply(curfiles,removesummaryinfo))
	filenamesc = c(filenamesc,paste(substr(curdirectory,1,5),filenames,sep=""))
	# Meta data
	curtablefilec[[i]] = read.table(paste(summarytabledirectory,curdirectory,"table.txt",sep=""), skip=3, sep="\t", header=TRUE)
	curtablefilec[[i]]$Sample.IDmod = paste(substr(curdirectory,1,5),curtablefilec[[i]][,3],sep="")
}
# Comparisons data
fc = file(paste(summarytabledirectory,"mousecomparisonswreps.txt",sep=""))
comparisonsfile = strsplit(readLines(fc), "\t")
close(fc)

##### Part 2: Format for DESeq analysis

countData = join_all(curfilesc,by="V1")
names(curtablefilec[[3]]) = names(curtablefilec[[1]])
allcolData = do.call(rbind,curtablefilec)
colnames(countData) = c("genes",sapply(strsplit(filenamesc,split="\\."),"[",1))
rownames(countData) = countData[,1]; countData2 = countData[,-1]
# Remove samples that were 0 in all runs
countData3 = countData2[-which(apply(countData2,1,sum)==0),]

##### Part 3: Run differential expression analysis on each comparison

allresults = vector("list",length(comparisonsfile))
for(i in 1:length(comparisonsfile)) {
	print(i)
	curcompsi = comparisonsfile[[i]]
	curcomps = NULL
	cursets = NULL
	for(j in 1:length(curcompsi)) {
		pullcomps = unlist(strsplit(curcompsi[[j]],split=" "))
		curcomps = c(curcomps,pullcomps)
		cursets = c(cursets,rep(j,length(pullcomps)))
	}
	pullcounts = which(colnames(countData3)%in%curcomps)
	pullcols = which(allcolData$Sample.IDmod%in%curcomps)
	curcolData = data.frame(condition=allcolData$Sample.Description[pullcols],group=as.factor(cursets))
	rownames(curcolData) = allcolData$Sample.IDmod[pullcols]
	curcountdata = countData3[,pullcounts]
	curcountdataorder = curcountdata[,match(colnames(curcountdata),rownames(curcolData))]
	dds = DESeqDataSetFromMatrix(countData = curcountdataorder, colData = curcolData, design = ~ group)
	dds = DESeq(dds)
	res = results(dds)
	ressort = res[order(res$padj,decreasing=FALSE),]
	allresults[[i]] = ressort
}

##### Part 4: Annotate the results

for(i in 1:length(allresults)) {
ensembl = useMart("ensembl")
ensembl = useDataset("mmusculus_gene_ensembl",mart=ensembl)
annodata = getBM(attributes=c("ensembl_gene_id","external_gene_name","description"),filters="ensembl_gene_id",values=allresults[[i]]@rownames,mart=ensembl)
allresults[[i]]@listData = cbind(DataFrame(allresults[[i]]),annodata[match(allresults[[i]]@rownames,annodata$ensembl_gene_id),-1])
}

##### Part 5: Save the data

save(allresults,file="mouseanalysisresuls.rdata")
########################################
#
# Program to run DESeq2 on the count data
#
########################################

setwd("~/jen/Files/")
require(DESeq2)
require(plyr)

##### Part 1: Read in the data

alldirectories = c("run60msrnaseqwtsplnlungbbreg","run61msrnaseqdkospbbregwtlnbreg","run68mousernaseqtregsplnlung")
countdirectory="/home/trevor/jen/counts/"
summarytabledirectory="/home/trevor/jen/summarytables/"

# Count data
curfilesc = NULL
filenamesc = NULL
curtablefilec = vector("list",length(alldirectories))
removesummaryinfo <- function(data) {
	newdata = data[-which(substr(data$V1,1,2)=="__"),]
return(newdata)
}
for(i in 1:length(alldirectories)) {
	curdirectory = alldirectories[i]
	filenames = list.files(paste(countdirectory,curdirectory,"/",sep=""), pattern="*.txt", full.names=FALSE)
	curfiles = lapply(paste(countdirectory,curdirectory,"/",filenames,sep=""), read.table)
	curfilesc = c(curfilesc,lapply(curfiles,removesummaryinfo))
	filenamesc = c(filenamesc,paste(substr(curdirectory,1,5),filenames,sep=""))
	# Meta data
	curtablefilec[[i]] = read.table(paste(summarytabledirectory,curdirectory,"table.txt",sep=""), skip=3, sep="\t", header=TRUE)
	curtablefilec[[i]]$Sample.IDmod = paste(substr(curdirectory,1,5),curtablefilec[[i]][,3],sep="")
}
# Comparisons data
fc = file(paste(summarytabledirectory,"mousecomparisons.txt",sep=""))
comparisonsfile = strsplit(readLines(fc), "\t")
close(fc)

##### Part 2: Format for DESeq analysis

countData = join_all(curfilesc,by="V1")
names(curtablefilec[[3]]) = names(curtablefilec[[1]])
allcolData = do.call(rbind,curtablefilec)
colnames(countData) = c("genes",sapply(strsplit(filenamesc,split="\\."),"[",1))
rownames(countData) = countData[,1]; countData2 = countData[,-1]
# Remove samples that were 0 in all runs
countData3 = countData2[-which(apply(countData2,1,sum)==0),]

##### Part 3: Run differential expression analysis on each comparison

allresults = vector("list",length(comparisonsfile))
for(i in 1:length(comparisonsfile)) {
	print(i)
	curcomps = comparisonsfile[[i]]
	pullcounts = which(colnames(countData3)%in%curcomps)
	pullcols = which(allcolData$Sample.IDmod%in%curcomps)
	curcolData = data.frame(condition=allcolData$Sample.Description[pullcols])
	rownames(curcolData) = allcolData$Sample.IDmod[pullcols]
	curcountdata = countData3[,pullcounts]
	curcountdataorder = curcountdata[,match(colnames(curcountdata),rownames(curcolData))]
	dds = DESeqDataSetFromMatrix(countData = curcountdataorder, colData = curcolData, design = ~ condition)
	dds = DESeq(dds)
	res = results(dds)
	ressort = res[order(res$padj,decreasing=FALSE),]
	allresults[[i]] = ressort
}

##### Part 4: Save the data

save(allresults,file="mouseanalysisresuls.rdata")
##' Fetches the chromosomal locations for all genes and sorts them within each chromosome. 
##' @params tcgaResults the list with TCGA results
##' @params ccleResults the list with CCLE results
##' @return a data.frame with locations for all genes
##' @author Andreas Schlicker (a.schlicker@nki.nl)
sortGenesByLocation = function(tcgaResults, ccleResults) {
	# Genes in all cancer types
	genes = rownames(tcgaResults[[1]]$prioritize.combined)
	for (n in 2:length(tcgaResults)) {
		genes = intersect(genes, rownames(tcgaResults[[n]]$prioritize.combined))
	}
	for (n in 1:length(ccleResults)) {
		genes = intersect(genes, rownames(ccleResults[[n]]$prioritize.combined))
	}

	# Find all gene locations
	mart = useMart(host="ensembl.org", path="/biomart/martservice", biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
	geneLoc = getBM(attributes=c("hgnc_symbol", "chromosome_name", "start_position", "end_position", "strand", "band"), filters=c("hgnc_symbol"), values=genes, mart=mart)
	# Remove all non-standard chromosome names and make everything numeric
	geneLoc = geneLoc[which(geneLoc[, "chromosome_name"] %in% c("1", "2", "3", "4", "5", "6", "7", "8", 
																															"9", "10", "11", "12", "13", "14", "15", 
																															"16", "17", "18", "19", "20", "21", "22", 
																															"X", "Y")), ]
	geneLoc[which(geneLoc[, "chromosome_name"] == "X"), "chromosome_name"] = "23"
	geneLoc[which(geneLoc[, "chromosome_name"] == "Y"), "chromosome_name"] = "24"
	geneLoc[, "chromosome_name"] = as.integer(geneLoc[, "chromosome_name"])
	
	geneLoc[which(geneLoc[, "strand"] == 1), "strand"] = "+"
	geneLoc[which(geneLoc[, "strand"] == -1), "strand"] = "-"
	
	# Return the sorted gene information
	geneLoc[order(geneLoc$chromosome_name, geneLoc$start_position), ]
}


##' Generates a chromosome plot for the selected score or the number of affected samples.
##' @params geneLocs the data.frame returned by sortGenesByLocation()
##' @params results either tcgaResults or ccleResults
##' @params cancType the selected four letter cancer code
##' @params chrom the selected chromosome; X is coded as 23 and Y as 24
##' @params scoreType which score was selected; one of "OG", "TS", "CO"
##' @return a list with two plotting objects, "score" the actual score and "affected" the percentage of affected samples
##' @author Andreas Schlicker (a.schlicker@nki.nl) 
getScorePlot = function(geneLocs, results, cancType, chrom, scoreType) {
	scoreType = match.arg(scoreType, c("TS", "OG", "CO"))
	
	# Get the genes for the selected chromosome
	genes = subset(geneLocs, chromosome_name==chrom)
	
	# Get the score vector
	score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.score"]
  # And the percentage of affected samples
	affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"]
	if (scoreType == "TS") {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.score"] * -1
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	} else {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "combined.score"]
		affected = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"] - 
							 results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	}
	
	# Get two tracks, one for scores and the other one for percent affected samples 
	tracks = list(DataTrack(GRanges(seqnames=as.character(chrom),
																	ranges=IRanges(start=genes[, "start_position"],
																								 end=genes[, "end_position"]),
																	score,
																	strand="*"),
																	name="", 
																	background.title="white",
																	background.panel="white"),
			
								DataTrack(GRanges(seqnames=as.character(chrom),
																	ranges=IRanges(start=genes[, "start_position"],
																								 end=genes[, "end_position"]),
																	affected,
																	strand="*"),
																	name="",
																	background.title="white",
																	background.panel="white"))
			
	list(score=plotTracks(tracks[1], type=c("h", "g"),
						 ylim=c(min(unlist(lapply(tracks, function(x) { min(x@data) }))), 
										max(unlist(lapply(tracks, function(x) { max(x@data) })))),
						 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
						 main=""),
			 affected=plotTracks(tracks[2], type=c("h", "g"),
						 ylim=c(min(unlist(lapply(tracks, function(x) { min(x@data) }))), 
										max(unlist(lapply(tracks, function(x) { max(x@data) })))),
						 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
						 main=""))
}

# TODO: silently install packages if not installed!!!

library('jsonlite')

connectToServer = function(port) {
  while(TRUE) {
    socket = try(suppressWarnings(socketConnection('localhost', port, open="w+", blocking=TRUE)), TRUE)
    if(inherits(socket, 'try-error')) {
      Sys.sleep(0.1)
    } else {
      break
    }
  }
  return(socket)
}

listenToMessages = function() {
  while(TRUE) {
    message = readLines(SOCKET, n=1, skipNul=TRUE)
    # debug('received', message)
    message = try(fromJSON(message), TRUE)

    if(is.list(message)) {
      if(message$type == 'query') {
        processQuery(message$query)
      }
    }
  }
}

processQuery = function(query) {
  # test if it parses
  parsed_query = try(parse(text=query), TRUE)
  if(inherits(parsed_query, 'try-error')) {
    sendError("Parse error")
    return(FALSE)
  } else {
    # run code in an isolated scope
    new_environment = new.env()
    results = eval(parsed_query, env=new_environment)

    sendResults(results)

    return(TRUE)
  }
}

# send message functions

sendResults = function(results) {
  message = list(type = 'results', results = processResults(results))
  sendMessage(message)
}

sendError = function(error) {
  message = list(type = 'error', error = error)
  sendMessage(message)
}

sendMessage = function(message) {
  encoded_message = toJSON(message, auto_unbox=TRUE)
  writeLines(encoded_message, SOCKET)
  flush(SOCKET)
  debug('sent', encoded_message)
}

# process results

processResults = function(results) {
  serializeJSON(results)
}

# nasty debug function (will be removed soon...)

debug = function(title, message) {
  message(paste0("!! ", toupper(title), ": ", message))
}

#' Dispatch the fitting of local models to parallel cores, if registered
#' 
#' Loops through estimation locations with foreach, sending each local model to a core for fitting. If zero or one cores are registered, then foreach computes the local models sequentially.
#' 
#' @param x matrix of observed covariates
#' @param y vector of observed responses
#' @param family exponential family distribution of the response
#' @param coords matrix of locations, with each row giving the location at which the corresponding row of data was observed
#' @param fit.loc matrix of locations where the local models should be fitted
#' @param kernel kernel function for generating the local observation weights
#' @param bw bandwidth parameter
#' @param bw.type type of bandwidth - options are \code{dist} for distance (the default), \code{knn} for nearest neighbors (bandwidth a proportion of \code{n}), and \code{nen} for nearest effective neighbors (bandwidth a proportion of the sum of squared residuals from a global model)
#' @param tol.loc tolerance for the tuning of an adaptive bandwidth (e.g. \code{knn} or \code{nen})
#' @param varselect.method criterion to minimize in the regularization step of fitting local models - options are \code{AIC}, \code{AICc}, \code{BIC}, \code{GCV}
#' @param tuning logical indicating whether this model will be used to tune the bandwidth, in which case only the tuning criteria are returned
#' @param D pre-specified matrix of distances between locations
#' @param verbose print detailed information about our progress?
#' 
lagr.dispatch = function(x, y, family, coords, fit.loc, oracle, D, bw, bw.type, verbose, varselect.method, prior.weights, tuning, predict, simulation, kernel, min.bw, max.bw, min.dist, max.dist, tol.loc, lambda.min.ratio, n.lambda, lagr.convergence.tol, lagr.max.iter, jacknife=FALSE, bootstrap.index=NULL) {
    if (!is.null(fit.loc)) { coords.fit = fit.loc }
    else { coords.fit = coords }
    n = nrow(coords.fit)

    vcr.model = list()

    #For the adaptive bandwith methods, use a default tolerance if none is specified:
    if (is.null(tol.loc)) {tol.loc = bw / 1000}

    #The knn bandwidth is a proportion of the total prior weight, so compute the total prior weight:
    if (bw.type == 'knn') {
        prior.weights = drop(prior.weights)
        total.weight = sum(prior.weights)
    }
    
    group.id = attr(x, 'assign')
    
models = list()
#    models = foreach(i=1:n, .errorhandling='stop') %dopar% {
for (i in 1:n) {
        if (!is.null(fit.loc)) {
            dist = drop(D[nrow(coords)+i,1:nrow(coords)])
        } else { dist = drop(D[i,]) }
        loc = coords.fit[i,]

        #If we are seeking the bandwidth via the jacknife, then remove any observations with zero distance.
        if (jacknife==TRUE || jacknife=='anti') {
            indx = which(dist!=0)
        } else {
            indx = 1:nrow(x)
        }

        if (!is.null(bootstrap.index)) {
            indx = indx[bootstrap.index]
        }

        if (jacknife=='anti') {
            indx = c(indx, which(indx==0))
        }
        
        #Use a prespecified distance as the bandwidth?
        if (bw.type == 'dist') {
            bandwidth = bw
            kernel.weights = drop(kernel(dist, bandwidth))

        #Compute the bandwidth that sets the sum of weights around location i equal to bw?
        } else if (bw.type == 'knn') {
            opt = optimize(
                lagr.knn,
                lower=min.dist,
                upper=max.dist,
                maximum=FALSE,
                tol=tol.loc,
                loc=loc,
                coords=coords[indx,],
                kernel=kernel,
                verbose=verbose,
                dist=dist[indx],
                total.weight=total.weight,
                prior.weights=prior.weights[indx],
                target=bw
            )
            bandwidth = opt$minimum
            kernel.weights = drop(kernel(dist, bandwidth))
            
        #Compute the bandwidth so that the sum of the local weighted squared error equals the bw?
        } else if (bw.type == 'nen') {
            opt = optimize(
                lagr.ssr,
                lower=min.dist,
                upper=max.dist, 
                maximum=FALSE,
                tol=tol.loc,
                x=x[indx,],
                y=y[indx],
                group.id=group.id,
                family=family,
                loc=loc,
                coords=coords[indx,],
                dist=dist[indx],
                kernel=kernel,
                target=bw,
                varselect.method=varselect.method,
                oracle=oracle,
                prior.weights=prior.weights[indx],
                verbose=verbose,
                lambda.min.ratio=lambda.min.ratio,
                n.lambda=n.lambda, 
                lagr.convergence.tol=lagr.convergence.tol,
                lagr.max.iter=lagr.max.iter
            )
            bandwidth = opt$minimum
            kernel.weights = drop(kernel(dist, bandwidth))
        }
        
        #If we have specified covariates via an oracle, then use those
        if (!is.null(oracle)) {oracle.loc = oracle[[i]]}
        else {oracle.loc = NULL}

        #Fit the local model
        m = list(tunelist=list('ssr-loc'=list('pearson'=Inf, 'deviance'=Inf), 'df-local'=1), 'sigma2'=0, 'nonzero'=vector(), 'weightsum'=sum(kernel.weights))
        try(m <- lagr.fit.inner(
            x=x[indx,],
            y=y[indx],
            group.id=group.id,
            family=family,
            coords=as.matrix(coords[indx,]),
            loc=loc,
            varselect.method=varselect.method,
            tuning=tuning,
            predict=predict,
            simulation=simulation,
            lambda.min.ratio=lambda.min.ratio,
            n.lambda=n.lambda, 
            lagr.convergence.tol=lagr.convergence.tol,
            lagr.max.iter=lagr.max.iter,
            verbose=verbose,
            kernel.weights=kernel.weights[indx],
            prior.weights=prior.weights[indx],
            oracle=oracle.loc)
        )
        if (verbose) {
            cat(paste("For i=", i, "; location=(", paste(round(loc,3), collapse=","), "); bw=", round(bandwidth,3), "; s=", m[['s']], "; dispersion=", round(tail(m[['dispersion']],1),3), "; nonzero=", paste(m[['nonzero']], collapse=","), "; weightsum=", round(m[['weightsum']],3), ".\n", sep=''))
        }        
        m[['bw']] = bandwidth
#        return(m)
models[[i]] = m
    }
    
    vcr.model[['fits']] = models
    
    #Calculate information criteria:
    fitted = vector()
    df = 0
    n = nrow(x)
    
    #Compute model-average fitted values and degrees of freedom:
    for (x in models) {
        #Compute the model-averaging weights:
        crit = x[['tunelist']][['criterion']]        
        if (varselect.method %in% c("AIC", "AICc", "BIC")) {
            crit.weights = as.numeric(crit==min(crit))
        } else if (varselect.method %in% c("wAIC", "wAICc")) {
            crit.weights = -crit
        }
        
        fitted = c(fitted, sum(x[['tunelist']][['localfit']] * crit.weights) / sum(crit.weights))
        df = df + sum((1+x[['model']][['results']][['df']]) * crit.weights / x[['weightsum']] ) / sum(crit.weights)
    }

    dev.resids = family$dev.resids(y, fitted, prior.weights)
    ll = family$aic(y, n, fitted, prior.weights, sum(dev.resids))

    #Compute the information criteria:
    vcr.model[['AICc']] = ll + 2*df + 2*df*(df+1)/(n-df-1)
    vcr.model[['AIC']] = ll + 2*df
    vcr.model[['GCV']] = ll
    vcr.model[['BIC']] = ll + log(n)*df

    vcr.model[['df']] = df
    
    return(vcr.model)
}
#' Calibrate MSS images to TM images
#'
#' Calibrate MSS images to TM images using linear regression
#' @param msswrs2dir character. MSS WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import ggplot2
#' @import gridExtra
#' @export


msscal_single = function(mss_file, tm_file){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  write_coef = function(mss_file, ref_file, index, coef,r){
    info = data.frame(mss_file = basename(mss_file),
                      ref_file = basename(ref_file),
                      index = index,
                      yint = as.numeric(coef[1]),
                      b1c = as.numeric(coef[2]),
                      b2c = as.numeric(coef[3]),
                      b3c = as.numeric(coef[4]),
                      b4c = as.numeric(coef[5]),
                      r=r)
    
    coefoutfile = file.path(outdir,paste(mssimgid,"_",index,"_cal_coef.csv",sep=""))
    write.csv(info, coefoutfile, row.names=F)
  }
  
  sample_it = function(img, bins, n){
    
    mi = min(img, na.rm=T)
    ma = max(img, na.rm=T)
    
    step = (ma - mi)/bins
    breaks = seq(mi,ma,step)
    
    min_samp = array(n, bins)
    for(i in 1:(length(breaks)-1)){
      these = which(img > breaks[i] & img <= breaks[i+1])
      if(i == 1){samp = sample(these, size=min(min_samp[i],length(these)))} else {
        samp = c(samp, sample(these, size=min(min_samp[i],length(these))))
      } 
    }
    return(samp)
  }
  
  #define the filenames
  mss_sr_file = mss_file
  mss_mask_file = sub("dos_sr.tif", "cloudmask.tif", mss_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #load files as raster
  mss_sr_img = brick(mss_sr_file)
  mss_mask_img = raster(mss_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(mss_sr_img)  = alignExtent(mss_sr_img, ref_tc_img, snap="near")
  extent(mss_mask_img) = alignExtent(mss_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(mss_sr_file,mss_mask_file,ref_tc_file,ref_tca_file,ref_mask_file))
  mss_sr_img = crop(mss_sr_img,int)
  mss_mask_img = crop(mss_mask_img,int)
  ref_tc_img = crop(ref_tc_img,int)
  ref_tca_img = crop(ref_tca_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask
  mss_mask_img = as.matrix(mss_mask_img)
  ref_mask_img = as.matrix(ref_mask_img)
  mask = mss_mask_img*ref_mask_img
  goods = which(mask == 1)
  
  refpix = as.matrix(ref_tca_img)[goods]
  
  #samp = sample_it(refpix, bins=20, n=1000)
  samp = sample(1:length(goods), 15000)
  samp = goods[samp]
  
  mss_mask_img = ref_mask_img = mask = refpix =  0
  
  b1samp = as.matrix(subset(mss_sr_img, 1))[samp]
  b2samp = as.matrix(subset(mss_sr_img, 2))[samp]
  b3samp = as.matrix(subset(mss_sr_img, 3))[samp]
  b4samp = as.matrix(subset(mss_sr_img, 4))[samp]
  samplen = length(samp)
  
  
  #predict the indices
  dname = dirname(mss_sr_file)
  mssimgid = substr(basename(mss_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", mssimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #TCB
  refsamp = as.matrix(subset(ref_tc_img, 1))[samp]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcb", sampoutfile, samplen)
  bcoef = model[[1]]
  bsamp = model[[2]]
  bplot = model[[3]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  #TCG
  refsamp = as.matrix(subset(ref_tc_img, 2))[samp]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcg", sampoutfile, samplen)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gplot = model[[3]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  refsamp = as.matrix(subset(ref_tc_img, 3))[samp]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcw", sampoutfile, samplen)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wplot = model[[3]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  singlepred = atan(gsamp$singlepred/bsamp$singlepred) * (180/pi) * 100
  refsamp = atan(gsamp$refsamp/bsamp$refsamp) * (180/pi) * 100
  tbl = data.frame(mss_img = rep(basename(mss_sr_file),length(singlepred)),
                   ref_img = rep(basename(ref_tc_file),length(singlepred)),
                   index = rep("tca",length(singlepred)),
                   refsamp,singlepred)
  final = tbl[complete.cases(tbl),]
  sampoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  write.csv(final, sampoutfile, row.names=F)
  
  
  r = cor(final$refsamp, final$singlepred)
  coef = rlm(final$refsamp ~ final$singlepred)
  g = ggplot(final, aes(singlepred, refsamp)) +
    stat_binhex(bins = 100)+
    scale_fill_gradientn(name = "Count", colours = rainbow(7))+
    xlab(paste(basename(mss_sr_file),"tca")) +
    ylab(paste(basename(ref_tc_file),"tca")) +
    ggtitle(paste("tca linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))) +
    theme(plot.title = element_text(size = 12)) +
    geom_smooth(method="rlm", colour = "black", se = FALSE) + 
    coord_fixed(ratio = 1)+
    theme_bw()  
  pngout = sub("samp.csv", "plot.png",sampoutfile)
  png(pngout,width=700, height=700)
  print(g)
  dev.off()
  
  info = data.frame(mss_file = basename(mss_sr_file), ref_file = basename(ref_tc_file),
                    index = "tca", yint = as.numeric(coef$coefficients[1]),
                    b1c = as.numeric(coef$coefficients[2]), r=r)
  
  coefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  write.csv(info, coefoutfile, row.names=F)
  

  write_coef(mss_sr_file, ref_tc_file, "tcb", bcoef, br)
  write_coef(mss_sr_file, ref_tc_file, "tcg", gcoef, gr)
  write_coef(mss_sr_file, ref_tc_file, "tcw", wcoef, wr)

  
  outfile = file.path(outdir,paste(mssimgid,"_tc_cal_planes.png",sep=""))
  make_tc_planes_comparison(bsamp, gsamp, wsamp, outfile)
  
}
#' GUI for running LandsatLinkr
#'
#' GUI for running LandsatLinkr
#' @export

run_landsatlinkr = function(){
  
  choices = c("Prepare MSS",
              "Prepare TM/ETM+",
              "Calibrate MSS to TM/ETM+",
              "Composite")
  
  selection = select.list(choices, title = "Select a process to run")
  if(selection == "Prepare MSS"){process = seq(1:5)}
  if(selection == "Prepare TM/ETM+"){process = 6}
  if(selection == "Calibrate MSS to TM/ETM+"){process = 7}
  if(selection == "Composite imagery"){process = 8}
  
  
  choices = c("No", "Yes")
  selection = select.list(choices, title = "Process in parallel using 2 cores when possible?")
  if(selection == "No"){cores = 1}
  if(selection == "Yes"){cores = 2}
  
  if(sum(process %in% seq(1,6)) > 0){
    scenedir = choose.dir(caption = "Select an MSS or TM/ETM+ scene directory. ex. 'C:/mss/036032'")
    reso = 60 #set default
    proj = "albers" #set default
    if(sum(process %in% c(1,6)) > 0){
      choices = c("30 meter", "60 meter")
      selection = select.list(choices, title = "Select a pixel resolution to use")
      if(selection == "30 meter"){reso = 30}
      if(selection == "60 meter"){reso = 60}
      
      choices = c("Native NAD83 UTM", "USGS North American Albers")
      selection = select.list(choices, title = "Select a map projection to use")
      if(selection == "Native NAD83 UTM"){proj = "default"}
      if(selection == "USGS North American Albers"){proj = "albers"}
    }
    
    demfile=NULL
    if(all(is.na(match(process,5))) == F){
      demfile = choose.files(caption = "Select a scene corresponding DEM file", multi=F)
    }
    #return(list(scenedir, demfile, proj, reso, process,cores))
    prepare_images(scenedir, demfile, proj=proj, reso=reso, process=process,cores=cores)
  }
  
  ################################
  #msscal and mixel
  
  if(sum(process %in% c(7,8)) > 0){
    choices = c("Yes", "No")
    msswrs1dir = choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'")
    answer = "Yes"
    while(answer == "Yes"){
      answer = select.list(choices, title = "Is there another MSS WRS-1 scene directory to add?")
      if(answer == "Yes"){msswrs1dir = c(msswrs1dir, choose.dir(caption = "Select a MSS WRS-1 scene directory. ex. 'C:/mss/wrs1/036032'"))}
    }
    
    msswrs2dir = choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'")
    answer = "Yes"
    while(answer == "Yes"){
      answer = select.list(choices, title = "Is there another MSS WRS-2 scene directory to add?")
      if(answer == "Yes"){msswrs2dir = c(msswrs2dir, choose.dir(caption = "Select a MSS WRS-2 scene directory. ex. 'C:/mss/wrs2/034032'"))}
    }
      
    tmwrs2dir = choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'")
    answer = "Yes"
    while(answer == "Yes"){
      answer = select.list(choices, title = "Is there another TM WRS-2 scene directory to add?")
      if(answer == "Yes"){tmwrs2dir = c(tmwrs2dir, choose.dir(caption = "Select a TM WRS-2 scene directory. ex. 'C:/tm/wrs2/034032'"))}
    }
  
    outdir=NULL
    index=NULL
    runname=NULL
    if(sum(process %in% 8) > 0){
      outdir = choose.dir(caption = "Select a directory to write the outputs to. ex. 'C:/composites/wrs2_034032'")
      
      choices = c("Tasseled cap angle",
                  "Tasseled cap brightness",
                  "Tasseled cap greenness",
                  "Tasseled cap wetness")
      selection = select.list(choices, title = "Select an index to create composites for")
      if(selection == "Tasseled cap angle"){index = "tca"}
      if(selection == "Tasseled cap brightness"){index = "tcb"}
      if(selection == "Tasseled cap greenness"){index = "tcg"}
      if(selection == "Tasseled cap wetness"){index = "tcw"}
      
      runname = readline("Provide a unique name for the composite series. ex. project1: ")
      
      choices = c("From file")
      selection = select.list(choices, title = "What area do you want to create composites for?")
      if(selection == "From file"){useareafile = choose.files(caption = "Select a 'usearea' file", multi=F)}
    }
    
    if(sum((process %in% 7) > 0)){process[1] = 1}
    if(sum((process %in% 8) > 0)){process[process==8] = 2}
    #return(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,cores,process)
    calibrate_and_composite(msswrs1dir,msswrs2dir,tmwrs2dir,index,outdir,runname,useareafile,doyears="all",order="sensor_and_doy",overlap="mean", cores=cores, process=process)
  } 
}
#' Decompress, stack, and reproject LPSG MSS images
#'
#' Decompresses, stacks, and optionally reprojects LPGS MSS images recieved from USGS EROS as .tar.gz files
#' @param file character. full path name of the surface reflectance file
#' @param outtype coded integer designating what units are desired in the output image: 1=DN, 2=radiance, 3=surface reflectance
#' @import raster
#' @import gdalUtils
#' @export

# http://earthexplorer.usgs.gov/ Landsat CDR TM and ETM+ images
tmunpackr = function(file, proj="default", reso=60){
  #tcset = "all", "tc", "tca"
  
  #set new directories
  randomstring = paste(sample(c(0:9, letters, LETTERS), 6, replace=TRUE),collapse="")
  tempdir = file.path(dirname(file),randomstring) #temp
  year = substr(basename(file),10,13)
  
  pieces = unlist(strsplit(dirname(file), "/")) #break up the directory and unlist so the pieces can be called by index
  len = length(pieces)-1 #get the ending index for "scene"
  newpieces = paste(pieces[1:len], collapse = "/") #subset the directory pieces so the last piece is the scene
  outdir = file.path(newpieces, "images", year)
  dir.create(tempdir, recursive=T, showWarnings=F)
  dir.create(outdir, recursive=T, showWarnings=F)
  
  #decompress the image and get/set files names
  untar(file, exdir=tempdir) #decompress the file
  files = list.files(tempdir, full.names=T)
  bands = grep("band", files, value=T)
  shadow = grep("cloud_shadow_qa", files, value=T) #0 okay, 255 bad
  cloud = grep("sr_cloud_qa.tif", files, value=T) #0 okay, 255 bad
  snow = grep("sr_cloud_qa.tif", files, value=T) #0 okay, 255 bad
  fmask = grep("cfmask", files, value=T) # <= 1 okay background 255
  outbase = substr(basename(file),1,16) 
  tempstack = file.path(tempdir,paste(outbase,"_tempstack.tif",sep=""))
  tempvrt = sub("tempstack.tif", "tempmask.vrt", tempstack)
  tempmask = sub("tempstack", "tempmask", tempstack)
  projstack = sub("tempstack", "projstack", tempstack)
  projmask = sub("tempstack", "projmask", tempstack)
  finalstack = file.path(outdir,paste(outbase,"_ledaps.tif", sep=""))
  finalmask = file.path(outdir,paste(outbase,"_cloudmask.tif", sep=""))
  tcfile = file.path(outdir,paste(outbase,"_tc.tif", sep=""))
  tcafile = file.path(outdir,paste(outbase,"_tca.tif", sep=""))
  outprojfile = file.path(outdir,paste(outbase,"_proj.txt", sep=""))
  
  ref = raster(bands[1]) #set a reference raster for setting values and getting projection
  origproj = projection(ref)
  
  #stack the image bands and write out
  gdalbuildvrt(gdalfile=bands, output.vrt = tempvrt, separate=T) #, tr=c(reso,reso)
  gdal_translate(src_dataset=tempvrt, dst_dataset=tempstack, of = "GTiff", co="INTERLEAVE=BAND")
  
   #s = stack(bands)
   #origproj = projection(s)
   #s = as(s, "SpatialGridDataFrame")       
   #writeGDAL(s, tempstack, drivername = "ENVI", type = "Int16", mvFlag = -9999)
  
  #make a composite cloudmask
  s = !is.na(as.matrix(raster(shadow)))
  c = !is.na(as.matrix(raster(cloud)))
  sn = !is.na(as.matrix(raster(snow)))
  f = as.matrix(raster(fmask)) <= 1
  mask = s*c*f*sn
  mask = setValues(ref,mask)
  mask = as(mask, "SpatialGridDataFrame")        #convert the raster to SGHF so it can be written using GDAL (faster than writing it with the raster package)
  writeGDAL(mask, tempmask, drivername = "GTiff", type = "Byte", mvFlag = 255, options="INTERLEAVE=BAND")
  
  s=c=sn=f=mask=0 #clear the memory
  
  #reproject the image #need to add in writing proj file for default
  if(proj == "default"){proj = origproj}
  if(proj == "albers"){proj = "+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs"}
    write(proj, outprojfile)
    gdalwarp(srcfile=tempstack, dstfile=projstack, 
               s_srs=origproj, t_srs=proj, of="GTiff", 
               r="bilinear", srcnodata=-9999, dstnodata=-32768, multi=T, #"near"
               tr=c(reso,reso), co="INTERLEAVE=BAND")
    
    #project the mask
    gdalwarp(srcfile=tempmask, dstfile=projmask, 
             s_srs=origproj, t_srs=proj, of="GTiff", 
             r="mode", srcnodata=255, dstnodata=255, multi=T,
             tr=c(reso,reso), co="INTERLEAVE=BAND")

  

  #trim the na rows and cols
  if(proj != "default"){
    infile = projstack
    inmask = projmask
  } else {
    infile = tempstack
    inmask = tempmask
  } 
  trim_na_rowcol(infile, finalstack, inmask, finalmask)
  
  #tasseled cap
  ref = raster(finalstack, 1)
  b1 = as.matrix(raster(finalstack, 1))
  b2 = as.matrix(raster(finalstack, 2))
  b3 = as.matrix(raster(finalstack, 3))
  b4 = as.matrix(raster(finalstack, 4))
  b5 = as.matrix(raster(finalstack, 5))
  b6 = as.matrix(raster(finalstack, 6))
  
  bcoef = c(0.2043, 0.4158, 0.5524, 0.5741, 0.3124, 0.2303)
  gcoef = c(-0.1603, -0.2819, -0.4934, 0.7940, -0.0002, -0.1446)
  wcoef = c(0.0315, 0.2021, 0.3102, 0.1594,-0.6806, -0.6109)
  
  tcset="all" #hardwire

  bright = (b1*bcoef[1])+(b2*bcoef[2])+(b3*bcoef[3])+(b4*bcoef[4])+(b5*bcoef[5])+(b6*bcoef[6])
  green = (b1*gcoef[1])+(b2*gcoef[2])+(b3*gcoef[3])+(b4*gcoef[4])+(b5*gcoef[5])+(b6*gcoef[6])
  if(tcset == "all" | tcset == "tc"){wet = (b1*wcoef[1])+(b2*wcoef[2])+(b3*wcoef[3])+(b4*wcoef[4])+(b5*wcoef[5])+(b6*wcoef[6])}
  
  b1=b2=b3=b4=b5=b6=0
  
  #calc tc and convert to a raster
  if(tcset == "all" | tcset == "tc"){
    tcb = setValues(ref,bright)
    tcg = setValues(ref,green)
    tcw = setValues(ref,wet)
    tc = stack(tcb,tcg,tcw)
    projection(tc) = set_projection(tcfile)
    tc = as(tc, "SpatialGridDataFrame")
    writeGDAL(tc, tcfile, drivername = "GTiff", type = "Int16", mvFlag = -32768, options="INTERLEAVE=BAND")
  }
  
  if(tcset == "all" | tcset == "tca"){
    #calc tc angle and convert to a raster
    tca = atan(green/bright) * (180/pi) * 100
    tca = setValues(ref,tca)
    projection(tca) = set_projection(tcafile)
    tca = as(tca, "SpatialGridDataFrame")
    writeGDAL(tca, tcafile, drivername = "GTiff", type = "Int16", mvFlag = -32768, options="INTERLEAVE=BAND")
  }
  
  #delete temporary files
  unlink(tempdir, recursive=T, force=T)
}

# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Enkrat prvak", "Dvakrat prvak", "Večkrat prvak")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
veckrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) > 2))
dvakrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) == 2))
enkrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) < 2))
stevilo.naslovov.dirkaca[veckrat.prvak] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[dvakrat.prvak] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[enkrat.prvak] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)




source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()

# Funkcija, ki uvozi podatke iz datoteke drzave.csv
uvoziDrzave <- function() {
  return(read.table("podatki/drzave.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))
  
}

# Zapišimo podatke v razpredelnico države.
cat("Uvažam podatke o državah...\n")
drzave <- uvoziDrzave()


# 3. faza: Izdelava zemljevida

# Uvozimo funkcijo za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r")

# Uvozimo zemljevid.
cat("Uvažam zemljevid...\n")
svet <- uvozi.zemljevid("http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip",
                          "Svet", "ne_110m_admin_0_countries.shp", mapa = "zemljevid",
                          encoding = "Windows-1250")


t <- table(Stevilo.naslovov.dirkaca$Država)

najvec.zmag <- max(t)
najmanj.zmag <- min(t)

u <- unique(t)
u <- u[order(u)]
barve <- rgb(0, 0, 1, match(t, u)/length(u))


# Narišimo zemljevid v PDF.
cat("Rišem zemljevid...\n")
pdf("slike/Zmage_po_drzavah.pdf", width=10, height=8)

plot(svet, col = barve[as.character(svet$name_long)], border = "grey")
title("Število svetovnih prvakov po državah")
legend("left", legend = u, fill = rgb(0, 0, 1, (1:length(u))/length(u)), bg="white")

#imena držav
text(coordinates(drzave[c("dolzina", "sirina")]), labels = drzave$drzava, col = "black", cex = 0.6)

dev.off()Kernel <- setRefClass("Kernel",
                fields = c("connection_info", "zmqctx", "sockets", "executor"),
                methods= list(

hb_reply = function() {
    data <- receive.socket(sockets$hb, unserialize = FALSE)
    send.socket(sockets$hb, data, serialize = FALSE)
},

#'<brief desc>
#'
#'<full description>
#' @param msg_lst <what param does>
#' @export
sign_msg = function(msg_lst) {
    concat <- unlist(msg_lst)
    return(hmac(connection_info$key, concat, "sha256"))
},
#'<brief desc>
#'
#'<full description>
#' @param parts <what param does>
#' @import rjson
#' @export
wire_to_msg = function(parts) {
    i <- 1
    #print(parts)
    while (any(parts[[i]] != charToRaw("<IDS|MSG>"))) {
        i <- i + 1
    }
    signature <- rawToChar(parts[[i + 1]])
    expected_signature <- sign_msg(parts[(i + 2):(i + 5)])
    stopifnot(identical(signature, expected_signature))
    header <- fromJSON(rawToChar(parts[[i + 2]]))
    parent_header <- fromJSON(rawToChar(parts[[i + 3]]))
    metadata <- fromJSON(rawToChar(parts[[i + 4]]))
    content <- fromJSON(rawToChar(parts[[i + 5]]))
    if (i > 1) {
        identities <- parts[1:(i - 1)]
    } else {
        identities <- NULL
    }
    return(list(header = header, parent_header = parent_header, metadata = metadata, 
        content = content, identities = identities))
},
#'<brief desc>
#'
#'<full description>
#' @param msg <what param does>
#' @export
msg_to_wire = function(msg) {
    #print(msg)
    bodyparts <- list(charToRaw(toJSON(msg$header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$parent_header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$metadata, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$content, auto_unbox=TRUE))
                     )
    signature <- sign_msg(bodyparts)
    return(c(msg$identities, list(charToRaw("<IDS|MSG>")), list(charToRaw(signature)), bodyparts))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @export
new_reply = function(msg_type, parent_msg) {
    header <- list(msg_id = UUIDgenerate(), username = parent_msg$header$username, 
        session = parent_msg$header$session, msg_type = msg_type)
    return(list(header = header, parent_header = parent_msg$header, identities = parent_msg$identities, 
        metadata = namedlist()  # Ensure this is {} in JSON, not []
        ))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @param  socket <what param does>
#' @param  content <what param does>
#' @export
send_response = function(msg_type, parent_msg, socket_name, content) {
    msg <- new_reply(msg_type, parent_msg)
    msg$content <- content
    socket <- sockets[socket_name][[1]]
    send.multipart(socket, msg_to_wire(msg))
},
#'<brief desc>
#'
#'<full description>
#' @param  <what param does>
#' @export
handle_shell = function() {
    parts <- receive.multipart(sockets$shell)
    msg <- wire_to_msg(parts)
    if (msg$header$msg_type == "execute_request") {
        executor$execute(msg)
    } else if (msg$header$msg_type == "kernel_info_request") {
        kernel_info(msg)
    } else if (msg$header$msg_type == "history_request") {
        history(msg)
    } else {
        print(c("Got unhandled msg_type:", msg$header$msg_type))
    }
},

history = function(request) {
  send_response("history_reply", request, 'shell', list(history=list()))
},

kernel_info = function(request) {
  send_response("kernel_info_reply", request, 'shell',
                list(protocol_version=c(4, 0), language="R",
                     language_info=list(name="R", codemirror_mode="r",
                                pygments_lexer="r", mimetype="text/x-r-source",
                                file_extension=".r"
                                )
                    )
                )
},

handle_control = function() {
  parts = receive.multipart(sockets$control)
  msg = wire_to_msg(parts)
  if (msg$header$msg_type == "shutdown_request") {
    shutdown(msg)
  } else {
    print(c("Unhandled control message, msg_type:", msg$header$msg_type))
  }
},

shutdown = function(request) {
  send_response('shutdown_reply', request, 'control',
                list(restart=request$content$restart))
  stop("Shut down by frontend.")
},

initialize = function(connection_file) {
    connection_info <<- fromJSON(connection_file)
    print(connection_info)
    url <- paste(connection_info$transport, "://", connection_info$ip, sep = "")
    url_with_port <- function(port_name) {
        return(paste(url, ":", connection_info[port_name], sep = ""))
    }

    # ZMQ Socket setup
    zmqctx <<- init.context()
    sockets <<- list(
        hb = init.socket(zmqctx, "ZMQ_REP"),
        iopub = init.socket(zmqctx, "ZMQ_PUB"),
        control = init.socket(zmqctx, "ZMQ_ROUTER"),
        stdin = init.socket(zmqctx, "ZMQ_ROUTER"),
        shell = init.socket(zmqctx, "ZMQ_ROUTER")
    )
    bind.socket(sockets$hb, url_with_port("hb_port"))
    bind.socket(sockets$iopub, url_with_port("iopub_port"))
    bind.socket(sockets$control, url_with_port("control_port"))
    bind.socket(sockets$stdin, url_with_port("stdin_port"))
    bind.socket(sockets$shell, url_with_port("shell_port"))

    executor <<- Executor$new(kernel=.self)
},

run = function() {
    while (1) {
        events <- poll.socket(list(sockets$hb, sockets$shell, sockets$control),
                              list("read", "read", "read"), timeout = -1L)
        if (events[[1]]$read) {
            # heartbeat
            hb_reply()
        }
        if (events[[2]]$read) {
            # Shell socket
            handle_shell()
        }

        if (events[[3]]$read) {  # Control socket
            handle_control()
        }
    }
})
)

#'Initialise and run the kernel
#'
#'@param connection_file The path to the IPython connection file, written by the frontend
#'@export 
main <- function(connection_file="") {
    if (connection_file == "") {
        # On Windows, passing the connection file in as a string literal fails,
        # because the \U in C:\Users looks like a unicode escape. So, we have to
        # pass it as a separate command line argument.
        connection_file = commandArgs(T)[1]
    }
    kernel <- Kernel$new(connection_file=connection_file)
    kernel$run()
}

#'Install the kernelspec to tell IPython (>= 3) about IRkernel
#'
#'@export
installspec <- function() {
    srcdir = system.file("kernelspec", package="IRkernel")
    cmd = paste("ipython kernelspec install --replace --name ir", srcdir, sep=" ")
    system(cmd, wait=TRUE)
}
# 2. faza: Obdelava, uvoz in čiščenje podatkov
source("uvoz/uvoz.r", encoding="UTF-8")
source("slike/grafi.R", encoding="UTF-8")

# 3. faza: Analiza in vizualizacija podatkov
#source("vizualizacija/vizualizacija.r")

# 4. faza: Napredna analiza podatkov
#source("analiza/analiza.r")

cat("Končano.\n")# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Enkrat prvak", "Dvakrat prvak", "Večkrat prvak")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
veckrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) > 2))
dvakrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) == 2))
enkrat.prvak <- svetovniprvaki$Driver %in% names(which(table(svetovniprvaki$Driver) < 2))
stevilo.naslovov.dirkaca[veckrat.prvak] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[dvakrat.prvak] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[enkrat.prvak] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)




source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# 3. faza: Izdelava zemljevida

# Uvozimo funkcijo za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r")

# Uvozimo zemljevid.
cat("Uvažam zemljevid...\n")
obcine <- uvozi.zemljevid("http://e-prostor.gov.si/fileadmin/BREZPLACNI_POD/RPE/OB.zip",
                          "obcine", "OB/OB.shp", mapa = "zemljevid",
                          encoding = "Windows-1250")

# Funkcija, ki podatke preuredi glede na vrstni red v zemljevidu
preuredi <- function(podatki, zemljevid) {
  nove.obcine <- c()
  manjkajo <- ! nove.obcine %in% rownames(podatki)
  M <- as.data.frame(matrix(nrow=sum(manjkajo), ncol=length(podatki)))
  names(M) <- names(podatki)
  row.names(M) <- nove.obcine[manjkajo]
  podatki <- rbind(podatki, M)
  
  out <- data.frame(podatki[order(rownames(podatki)), ])[rank(levels(zemljevid$OB_UIME)[rank(zemljevid$OB_UIME)]), ]
  if (ncol(podatki) == 1) {
    out <- data.frame(out)
    names(out) <- names(podatki)
    rownames(out) <- rownames(podatki)
  }
  return(out)
}

# Preuredimo podatke, da jih bomo lahko izrisali na zemljevid.
druzine <- preuredi(druzine, obcine)

# Izračunamo povprečno velikost družine.
druzine$povprecje <- apply(druzine[1:4], 1, function(x) sum(x*(1:4))/sum(x))
min.povprecje <- min(druzine$povprecje, na.rm=TRUE)
max.povprecje <- max(druzine$povprecje, na.rm=TRUE)

# Narišimo zemljevid v PDF.
cat("Rišem zemljevid...\n")
pdf("slike/povprecna_druzina.pdf", width=6, height=4)

n = 100
barve = topo.colors(n)[1+(n-1)*(druzine$povprecje-min.povprecje)/(max.povprecje-min.povprecje)]
plot(obcine, col = barve)

dev.off()REBOL [
	Title:   "Red/System compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/utils/profiler.r
profiler/active?: no

do-cache %system/utils/r2-forward.r
do-cache %system/utils/int-to-bin.r
do-cache %system/utils/IEEE-754.r
do-cache %system/utils/virtual-struct.r
do-cache %system/utils/secure-clean-path.r
do-cache %system/linker.r
do-cache %system/emitter.r

system-dialect: make-profilable context [
	verbose:  	  0										;-- logs verbosity level
	job: 		  none									;-- reference the current job object	
	runtime-path: pick [%system/runtime/ %runtime/] encap?
	nl: 		  newline
	
	loader: do bind load-cache %system/loader.r 'self
	
	options-class: context [
		config-name:		none						;-- Preconfigured compilation target ID
		OS:					none						;-- Operating System
		OS-version:			none						;-- OS version
		ABI:				none						;-- optional ABI flags (word! or block!)
		link?:				no							;-- yes = invoke the linker and finalize the job
		debug?:				no							;-- reserved for future use
		build-prefix:		%builds/					;-- prefix to use for output file name (none: no prefix)
		build-basename:		none						;-- base name to use for output file name (none: derive from input name)
		build-suffix:		none						;-- suffix to use for output file name (none: derive from output type)
		format:				none						;-- file format
		type:				'exe						;-- file type ('exe | 'dll | 'lib | 'obj | 'drv)
		target:				'IA-32						;-- CPU target
		cpu-version:		6.0							;-- CPU version (default: Pentium Pro)
		verbosity:			0							;-- logs verbosity level
		sub-system:			'console					;-- 'GUI | 'console
		runtime?:			yes							;-- include Red/System runtime
		use-natives?:		no							;-- force use of native functions instead of C bindings
		debug?:				no							;-- emit debug information into binary
		need-main?:			no							;-- yes => emit a function prolog/epilog around global code
		PIC?:				no							;-- generate Position Independent Code
		base-address:		none						;-- base image memory address
		dynamic-linker: 	none						;-- ELF dynamic linker ("interpreter")
		syscall:			'Linux						;-- syscalls convention: 'Linux | 'BSD
		stack-align-16?:	no							;-- yes => align stack to 16 bytes
		literal-pool?:		no							;-- yes => use pools to store literals, no => store them inlined (default: no)
		unicode?:			no							;-- yes => use Red Unicode API for printing on screen
		red-pass?:			no							;-- yes => Red compiler was invoked
		red-only?:			no							;-- yes => stop compilation at Red/System level and display output
		red-store-bodies?:	yes							;-- no => do not store function! value bodies (body-of will return none)
		red-strict-check?:	yes							;-- no => defers undefined word errors reporting at run-time
		red-tracing?:		yes							;-- no => do not compile tracing code
		red-help?:			no							;-- yes => keep doc-strings from boot.red
		legacy:				none						;-- block of optional OS legacy features flags
	]
	
	compiler: make-profilable context [
		job:		 	 none							;-- shortcut for job object
		pc:			 	 none							;-- source code input cursor
		script:		 	 none							;-- source script file name
		none-type:	 	 [#[none]]						;-- marker for "no value returned"
		last-type:	 	 none-type						;-- type of last value from an expression
		locals: 	 	 none							;-- currently compiled function specification block
		definitions:  	 make block! 100
		enumerations: 	 make hash! 10
		expr-call-stack: make block! 1					;-- simple stack of nested calls for a given expression
		locals-init: 	 []								;-- currently compiler function locals variable init list
		func-name:	 	 none							;-- currently compiled function name
		block-level: 	 0								;-- nesting level of input source block
		catch-level:	 0								;-- nesting level of CATCH body block
		verbose:  	 	 0								;-- logs verbosity level
	
		imports: 	   	 make block! 10					;-- list of imported functions
		exports: 	   	 make block! 10					;-- list of exported symbols
		natives:	   	 make hash!  40					;-- list of functions to compile [name [specs] [body]...]
		ns-path:		 none							;-- namespaces access path
		ns-stack:		 none							;-- namespaces resolution stack
		ns-list:		 make hash!  8					;-- namespaces definition list [name [word type...]...]
		sym-ctx-table:	 make hash!  100				;-- reverse lookup table for contexts
		globals:  	   	 make hash!  40					;-- list of globally defined symbols from scripts
		aliased-types: 	 make hash!  10					;-- list of aliased type definitions
		keywords-list:	 make block! 20
		
		resolve-alias?:  yes							;-- YES: instruct the type resolution function to reduce aliases
		decoration:		 slash							;-- decoration separator for namespaces
		shift-right-sym: to word! ">>>"					;-- workaround REBOL LOAD limitation
		
		debug-lines: reduce [							;-- runtime source line/file information storage
			'records make block!  1000					;-- [address line file] records
			'files	 make hash!   20					;-- filenames table
		]
		
		pos:		none								;-- validation rules cursor for error reporting
		return-def: to-set-word 'return					;-- return: keyword
		fail:		[end skip]							;-- fail rule
		rule: value: v: none							;-- global parsing rules helpers
		
		number!: 	  [byte! integer!]					;-- reserved for internal use only
		bit-set!: 	  [byte! integer! logic!]			;-- reserved for internal use only
		any-float!:	  [float! float32! float64!]		;-- reserved for internal use only
		any-number!:  union number! any-float!			;-- reserved for internal use only
		pointers!:	  [pointer! struct! c-string!] 		;-- reserved for internal use only
		any-pointer!: union pointers! [function!]		;-- reserved for internal use only
		poly!:		  union any-number! pointers!		;-- reserved for internal use only
		any-type!:	  union poly! [logic!]			  	;-- reserved for internal use only
		type-sets:	  [									;-- reserved for internal use only
			number! poly! any-type! any-pointer!
			any-number! bit-set!
		]
		
		comparison-op: [= <> < > <= >=]
		
		functions: to-hash compose [
		;--Name--Arity--Type----Cc--Specs--		   Cc = Calling convention
			+		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			-		[2	op		- [a [poly!]   b [poly!]   return: [poly!]]]
			*		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			/		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]
			and		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			or		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			xor		[2	op		- [a [bit-set!] b [bit-set!] return: [bit-set!]]]
			//		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- modulo
			(to-word "%")		[2	op		- [a [any-number!] b [any-number!] return: [any-number!]]]		;-- remainder (real syntax: %)
			>>		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right signed
			<<		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift left signed
			-**		[2	op		- [a [number!] b [number!] return: [number!]]]		;-- shift right unsigned
			=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			>=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			<=		[2	op		- [a [any-type!] b [any-type!]  return: [logic!]]]
			not		[1	inline	- [a [bit-set!] 		   return: [bit-set!]]]
			push	[1	inline	- [a [any-type!]]]
			pop		[0	inline	- [						   return: [integer!]]]
			throw	[1	inline	- [n [integer!]]]
		]
		
		repend functions [shift-right-sym copy functions/-**]
		
		user-functions: tail functions					;-- marker for user functions
		
		action-class: context [action: type: data: none]
		
		struct-syntax: [
			pos: opt [into ['align integer! opt ['big | 'little]]]	;-- struct's attributes
			pos: some [word! into [func-pointer | type-spec]]		;-- struct's members
		]
		
		pointer-syntax: ['integer! | 'byte! | 'float32! | 'float64! | 'float!]
		
		func-pointer: ['function! set value block! (check-specs '- value)]
		
		type-syntax: [
			'logic! | 'integer! | 'byte! | 'int16!		;-- int16! needed for AVR8 backend
			| 'float! | 'float32! | 'float64!
			| 'c-string!
			| 'pointer! into [pointer-syntax]
			| 'struct!  into [struct-syntax]
		]

		type-spec: [
			pos: some type-syntax | pos: set value word! (	;-- multiple types allowed for internal usage		
				unless any [
					all [v: find-aliased/prefix value v <> value find aliased-types v pos/1: v]			;-- rewrite the type to prefix it
					find aliased-types value
					all [v: resolve-ns value v <> value enum-type? v pos/1: v]	;-- rewrite the type to prefix it
					all [enum-type? value pos/1: 'integer!]
				][throw false]							;-- stop parsing if unresolved type			
			)
		]		
		
		keywords: make hash! [
			;&			 [throw-error "reserved for future use"]
			?? 			 [comp-print-debug]
			as			 [comp-as]
			assert		 [comp-assert]
			size? 		 [comp-size?]
			if			 [comp-if]
			either		 [comp-either]
			case		 [comp-case]
			switch		 [comp-switch]
			until		 [comp-until]
			while		 [comp-while]
			any			 [comp-expression-list]
			all			 [comp-expression-list/_all]
			exit		 [comp-exit]
			return		 [comp-exit/value]
			catch		 [comp-catch]
			declare		 [comp-declare]
			null		 [comp-null]
			context		 [comp-context]
			with		 [comp-with]
			comment 	 [comp-comment]
			
			true		 [also true pc: next pc]		  ;-- converts word! to logic!
			false		 [also false pc: next pc]		  ;-- converts word! to logic!
			
			func 		 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			function 	 [raise-level-error "a function"] ;-- func declaration not allowed at this level
			alias 		 [raise-level-error "an alias"]	  ;-- alias declaration not allowed at this level
		]
		
		calling-keywords: [								;-- keywords accepted in expr-call-stack
			?? as assert size? if either case switch until while any all
			return catch
		]
		
		foreach [word action] keywords [append keywords-list word]
		foreach [name spec] functions  [append keywords-list name]
		
		calc-line: has [idx head-end prev p header][
			header: head pc
			idx: (index? pc) - header/1  				;-- calculate real pc position (not counting hidden header)
			prev: 1

			parse header [								;-- search for closest line marker
				skip									;-- skip over header length
				some [
					set p pair! (
						if p/2 = idx [return p/1]		;-- exact value position match
						if p/2 > idx [return prev]		;-- closest value position match 
						prev: p/1
					)
				]
			]
			return p/1									;-- return last marker
		]
		
		store-dbg-lines: has [dbg pos][
			dbg: debug-lines
			unless pos: find dbg/files script [
				pos: tail dbg/files
				append dbg/files script
			]
			repend dbg/records [
				emitter/tail-ptr calc-line index? pos
			]
		]
		
		quit-on-error: does [
			clean-up
			if system/options/args [quit/return 1]
			halt
		]
		
		throw-error: func [err [word! string! block!]][
			print [
				"*** Compilation Error:"
				either word? err [
					join uppercase/part mold err 1 " error"
				][reform err]
				"^/*** in file:" mold script
				either locals [join "^/*** in function: " func-name][""]
			]
			if pc [
				print [
					"*** at line:" calc-line lf
					"*** near:" mold copy/part pc 8
				]
			]
			quit-on-error
		]
		
		throw-warning: func [msg [string! block!] /near][
			print [
				"*** Warning:" 	reform msg
				"^/*** in:" 	mold script
				"^/*** at:" 	mold copy/part any [all [near back pc] pc] 8
			]
		]
		
		raise-level-error: func [kind [string!]][
			pc: back pc
			throw-error reform ["declaring" kind "at this level is not allowed"]
		]
		
		raise-casting-error: does [
			backtrack 'as
			throw-error "multiple type casting not allowed"
		]
		
		;raise-paren-error: does [
		;	pc: back pc
		;	throw-error "parens are only allowed nested in an expression"
		;]
		
		raise-runtime-error: func [error [integer!]][
			emitter/target/emit-get-pc				;-- get current CPU program counter address
			last-type: [integer!]					;-- emit-get-pc returns an integer! (required for next line)
			compiler/comp-call '***-on-quit reduce [error <last>] ;-- raise a runtime error
		]
		
		undecorate: func [value [word! path! set-word! set-path!] /local v pos][
			unless find v: mold value decoration [return value]
			
			while [pos: find v decoration][
				unless find ns-list to path! copy/part v pos [
					pos: next pos
					v: append replace/all copy/part head v pos decoration slash pos
					return load v
				]
				v: at v pos + 1
			]
			value
		]
		
		backtrack: func [value /local res][
			if find [word! path! set-word! set-path!] type?/word value [
				value: undecorate value
			]
			pc: any [res: find/only/reverse pc value pc]
			to logic! res
		]
		
		blockify: func [value][either block? value [value][reduce [value]]]

		literal?: func [value][
			not any [word? value get-word? value path? value block? value value = <last>]
		]
		
		not-initialized?: func [name [word!] /local pos][
			all [
				locals
				pos: find locals /local
				pos: find next pos name
				not find locals-init name
			]
		]
		
		get-alias-id: func [pos [hash!]][
			1000 + divide 1 + index? pos 2
		]
		
		get-type-id: func [value /local type alias][
			with-alias-resolution off [type: resolve-expr-type value]
			
			either alias: find-aliased/position type/1 [		
				get-alias-id alias
			][
				type: resolve-aliased type
				type: switch/default type/1 [
					any-pointer! ['int-ptr!]
					pointer! [pick [int-ptr! byte-ptr!] type/2/1 = 'integer!]
				][type/1]
				select emitter/datatype-ID type
			]
		]
		
		system-reflexion?: func [path [path! set-path!] /local def][
			if path/1 = 'system [
				switch path/2 [
					alias [
						unless path/3 [
							backtrack path
							throw-error "invalid system/alias path access"
						]
						unless def: find-aliased/position path/3 [
							backtrack path
							throw-error ["undefined alias name:" path/3]
						]
						last-type: [integer!]
						return get-alias-id def			;-- special encoding for aliases
					]
					words [
						unless path/3 [
							backtrack path
							throw-error "invalid system/words path access"
						]
						path: remove/part copy path 2
						return either 1 = length? path [
							either set-path? path [to set-word! path/1][path/1]
						][
							path
						]
					]
					; add new special reflective system path here
				]
			]
			none
		]
		
		base-type?: func [value][
			if block? value [value: value/1]
			to logic! find/skip emitter/datatypes value 3
		]
		
		unbox: func [value][
			either object? value [value/data][value]
		]
		
		clear-docstrings: func [spec [block!]][
			remove-each s spec [string? s]
			spec
		]
		
		get-return-type: func [name [word!] /check /local type spec][
			unless all [
				spec: find-functions name
				any [
					type: select spec/2/4 return-def
					check
				]
			][
				backtrack name
				throw-error ["return type missing in function:" name]
			]
			any [type none-type]
		]
		
		set-last-type: func [spec [block!]][
			if spec: select spec return-def [last-type: spec]
		]
		
		local-variable?: func [name [word!]][
			all [locals find locals name]
		]
		
		exists-variable?: func [name [word! set-word!]][
			name: to word! name
			to logic! any [
				local-variable? name
				find globals name
			]
		]
		
		select-globals: func [name [word!] /local pos][
			all [
				pos: find globals name
				pos/2
			]
		]
		
		get-variable-spec: func [name [word!]][
			any [
				all [locals select locals name]
				select-globals name
			]
		]
		
		get-arity: func [spec [block!] /local count][
			count: 0
			parse spec [opt block! any [word! block! (count: count + 1)]]
			count
		]
		
		any-path?: func [value][
			find [path! set-path! lit-path!] type?/word value
		]
		
		any-float?: func [type [block!]][
			find any-float! type/1
		]
		
		any-pointer?: func [type [block!]][
			type: first resolve-aliased type
			
			either find type-sets type [
				not empty? intersect get type any-pointer!
			][
				to logic! find any-pointer! type
			]
		]

		equal-types?: func [type1 [word!] type2 [word!]][
			type1: either find type-sets type1 [get type1][reduce [type1]]
			type2: either find type-sets type2 [get type2][reduce [type2]]
			not empty? intersect type1 type2
		]
		
		equal-types-list?: func [types [block!]][
			forall types [							;-- check if all last expressions are of same type
				unless types/1/1 [return none-type]	;-- test if type is defined
				types/1: resolve-aliased types/1	;-- reduce aliases and pseudo-types
				if all [
					not head? types
					not equal-types? types/-1/1 types/1/1
				][
					return none-type
				]
			]
			first head types						;-- all types equal, return the first one
		]
						
		with-alias-resolution: func [mode [logic!] body [block!] /local saved][
			saved: resolve-alias?
			resolve-alias?: mode	
			do body
			resolve-alias?: saved
		]
		
		find-aliased: func [type [word!] /prefix /position /local ns pos][
			if all [ns: resolve-ns type find aliased-types ns][type: ns]
			if prefix [return ns]
			pos: find aliased-types type
			either position [pos][all [pos pos/2]]
		]
		
		resolve-aliased: func [type [block!] /local name][
			name: type/1
			all [
				type/1								;-- ensure it is not [none]
				not base-type? name
				not find type-sets name
				not all [
					enum-type? name
					type: [integer!]
				]
				not type: find-aliased name
				throw-error ["unknown type:" type]
			]
			type
		]
		
		resolve-type: func [name [word!] /with parent [block! none!] /local type local?][
			type: any [
				all [parent select parent name]
				local?: all [locals select locals name]
				select-globals name
			]
			if all [not type find functions name][
				return reduce ['function! functions/(decorate-fun name)/4]
			]
			if any [
				all [not local?	any [enum-type? name enum-id? name]]
				all [type enum-type? type/1]
			][
				return [integer!]
			]
			unless any [not resolve-alias? none? type base-type? type/1][
				type: find-aliased type/1
			]
			type
		]
		
		resolve-struct-member-type: func [spec [block!] name [word!] /local type][
			unless type: select spec name [
				while [not all [any-path? pc/1 find pc/1 name]][pc: back pc]
				throw-error [
					"invalid struct member" to lit-word! name "in:" mold to path! pc/1
				]
			]
			either resolve-alias? [resolve-aliased type][type]
		]
		
		resolve-path-type: func [path [path! set-path!] /short /parent prev /local type path-error saved][
			path-error: [
				pc: skip pc -2
				throw-error "invalid path value"
			]
			either word? path/1 [
				either parent [
					resolve-struct-member-type prev path/1	;-- just check for correct member name
					with-alias-resolution on [
						type: resolve-type/with path/1 prev
					]
				][
					with-alias-resolution on [
						type: resolve-type path/1
					]
				]
			][
				type: reduce [type?/word path/1]
			]
			
			unless type path-error
			
			either tail? skip path 2 [
				switch/default type/1 [
					c-string! [
						check-path-index path 'string
						[byte!]
					]
					pointer!  [
						check-path-index path 'pointer
						reduce [type/2/1]				;-- return pointed value type
					]
					struct!   [
						unless word? path/2 [
							backtrack path
							throw-error ["invalid struct member" path/2]
						]
						type: resolve-struct-member-type type/2 path/2
						
						if all [
							not short
							not set-path? path
							type/1 = 'function!
						][
							type: select type/2 return-def
						]
						type
					]
				] path-error
			][
				either short [
					resolve-path-type/parent/short next path second type
				][
					resolve-path-type/parent next path second type
				]
			]
		]
		
		get-type: func [value /local type][
			switch/default type?/word value [
				none!	 [none-type]					;-- no type case (func with no return value)
				tag!	 [either value = <last> [last-type][ [logic!] ]]
				logic!	 [[logic!]]
				word! 	 [resolve-type value]
				char!	 [[byte!]]
				integer! [[integer!]]
				decimal! [[float!]]
				string!	 [[c-string!]]
				path!	 [resolve-path-type value]
				object!  [value/type]
				block!	 [
					if value/1 = 'not [return get-type value/2]	;-- special case for NOT multitype native
					
					either 'op = second get-function-spec value/1 [
						either base-type? type: get-return-type value/1 [
							type						;-- unique returned type, stop here
						][
							get-type value/2			;-- recursively search for left operand base type
						]
					][
						get-return-type value/1
					]
				]
				paren!	 [
					switch/default value/1 [
						struct!  [reduce pick [[value/2][value/1 value/2]] word? value/2]
						pointer! [reduce [value/1 value/2]]
					][
						next next reduce ['array! length? value	'pointer! get-type value/1]	;-- hide array size
					]
				]
				get-word! [
					type: resolve-type to word! value
					switch/default type/1 [
						function! [type]
						integer! byte! float! float32! [compose/deep [pointer! [(type/1)]]]
					][
						throw-error ["invalid datatype for a get-word:" mold type]
					]
				]
			][
				throw-error ["not accepted datatype:" type? value]
			]
		]
		
		enum-type?: func [name [word!] /local type][
			all [
				type: find/skip enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				reduce [next type]
			]
		]
		
		enum-id?: func [name [word!] /local pos][
			all [
				pos: find/skip next enumerations name 3
				reduce [pos/-1]
			]
		]

		get-enumerator: func [name [word!] /value /local pos][
			all [
				pos: find/skip next enumerations name 3		;-- SELECT/SKIP on hash! unreliable!
				pos/2
			]
		]
		
		set-enumerator: func [
			identifier [word!] name [word! block!] value [integer! word!] /local list v
		][
			store-ns-symbol identifier
			if ns-path [
				add-ns-symbol to set-word! identifier
				identifier: ns-prefix identifier
			]
			
			if word? name [name: reduce [name]]
			forall name [
				store-ns-symbol name/1
				if ns-path [
					add-ns-symbol to set-word! name/1
					name/1: ns-prefix name/1
				]
				check-enum-word name/1
			]
			name: head name
			
			if all [
				word? value
				none? value: get-enumerator resolve-ns value
			][
				throw-error ["cannot resolve literal enum value for:" form name]
			]
			forall name [
				if verbose > 3 [print ["Enum:" identifier "[" name/1 "=" value "]"]]
				repend enumerations [identifier name/1 value]
			]
			value: value + 1
		]

		resolve-expr-type: func [expr /quiet /local type func? spec][
			if block? expr [
				switch type?/word expr/1 [
					set-word! [expr: expr/2]			;-- resolve assigned value type
					set-path! [expr: to path! expr/1]	;-- resolve path type
				]
			]			
			func?: all [
				block? expr word? expr/1
				not find comparison-op expr/1
				spec: find functions expr/1 		 ;-- works for unary & binary functions only!
				spec: spec/2
			]
			type: case [
				object? expr [
					expr/type						 ;-- type casting case
				]
				all [func? find [op inline] spec/2][ ;-- works for unary & binary functions only!
					any [
						all [
							expr/1 <> 'not			;-- @@ issue with 'not return type
							spec: select spec/4 return-def
							base-type? spec/1		;-- determined return type
							spec
						]
						get-type expr/2				;-- recursively search for return type
					]
				]
				all [func? quiet][
					any [
						select spec/4 return-def	;-- workaround error throwing in get-return-value
						none-type
					]
				]
				'else [
					expr: get-type expr
					if resolve-alias? [expr: resolve-aliased expr]
					expr
				]
			]
			type
		]
		
		check-throw: does [
			unless any [locals positive? catch-level][
				backtrack 'throw
				throw-error "THROW used without a wrapping CATCH"
			]
		]
		
		push-call: func [action [word! set-word! set-path!]][
			append/only expr-call-stack action
			if verbose >= 4 [
				new-line/all expr-call-stack off
				?? expr-call-stack
			]
		]
		
		pop-calls: does [clear expr-call-stack]
		
		cast: func [obj [object!] /local value ctype type][
			value: obj/data
			ctype: resolve-aliased obj/type
			type: get-type value

			if all [type = obj/type type/1 <> 'function!][
				throw-warning/near [
					"type casting from" type/1 
					"to" obj/type/1 "is not necessary"
				] 'as
			]
			if any [
				all [type/1 = 'function! not find [function! integer!] ctype/1]
				all [find [float! float64!] ctype/1 not find [float! float64! float32!] type/1]
				all [find [float! float64!] type/1  not find [float! float64! float32!] ctype/1]
				all [type/1 = 'float32! not find [float! float64! integer!] ctype/1]
				all [ctype/1 = 'byte! find [c-string! pointer! struct!] type/1]
				all [
					find [c-string! pointer! struct!] ctype/1
					find [byte! logic!] type/1
				]
			][
				backtrack value
				throw-error [
					"type casting from" type/1
					"to" ctype/1 "is not allowed"
				]
			]	
			unless literal? value [return value]	;-- shield the following literal conversions
			
			switch ctype/1 [
				byte! [
					switch type/1 [
						integer! [value: to char! value and 255]
						logic! 	 [value: pick [#"^(01)" #"^(00)"] value]
					]
				]
				integer! [
					if find [byte! logic!] type/1 [
						value: to integer! value
					]
				]
				logic! [
					switch type/1 [
						byte! 	 [value: value <> null]
						integer! [value: value <> 0]
					]
				]
			]
			value
		]
		
		decorate-function: func [name [word!]][
			to word! join "_local_" form name
		]
		
		find-functions: func [name [word!]][
			if all [
				locals
				type: select locals name
				type/1 = 'function!
			][
				name: decorate-function name
			]
			any [
				find functions name
				find functions resolve-ns name
			]
		]

		get-function-spec: func [name [word!] /local spec][
			all [
				spec: find-functions name
				spec/2
			]
		]

		decorate-fun: func [name [word!] /local type][
			either all [
				locals
				type: select locals name
				block? type
				type/1 = 'function!
			][
				decorate-function name
			][
				name
			]
		]

		remove-func-pointers: has [vars name][
			vars: any [find/tail locals /local []]
			forall vars [
				if all [
					word? vars/1
					block? vars/2
					vars/2/1 = 'function!
				][
					name: decorate-function vars/1
					remove/part find functions name 2
				]
			]
		]
		
		init-local: func [name [word!] expr casted [block! none!] /local pos type][
			append locals-init name					;-- mark as initialized
			pos: find locals name
			unless block? pos/2 [					;-- if not typed, infer type
				insert/only at pos 2 type: any [
					casted
					resolve-expr-type expr
				]
				if verbose > 2 [print ["inferred type" mold type "for variable:" pos/1]]
			]
		]
		
		order-ctx-candidates: func [a b][				;-- order by increasing path size,
			to logic! not all [							;-- and word! before path!.
				path? a
				any [
					word? b
					all [path? b greater? length? a length? b]
				]
			]
		]
		
		store-ns-symbol: func [name [word!] /local pos][
			if ns-path [
				either pos: find/skip sym-ctx-table name 2 [
					either block? pos/2 [
						if find/only pos/2 ns-path [exit]
					][
						if ns-path = pos/2 [exit]
						pos/2: reduce [pos/2]
					]
					append/only pos/2 copy ns-path
					sort/compare pos/2 :order-ctx-candidates
				][
					append sym-ctx-table name
					append/only sym-ctx-table copy ns-path
				]
			]
		]
		
		add-ns-symbol: func [name [set-word!] /local ctx ns][
			name: to word! name
			if find second find/only ns-list ns-path name [exit]
			if ns-stack [
				ctx: tail ns-stack
				until [
					ctx: back ctx
					if all [
						ns: find/only ns-list to path! ctx/1
						find second ns name 
					][exit]
					head? ctx
				]
			]
			append second find/only ns-list ns-path name
		]
		
		add-symbol: func [name [word!] value type][
			unless type [type: get-type value]
			unless 'array! = first head type [type: copy type]
			append globals reduce [name type]
			type
		]
		
		add-function: func [type [word!] spec [block!] cc [word!]][
			repend functions [
				to word! spec/1 reduce [get-arity spec/3 type cc new-line/all spec/3 off]
			]
			if find-attribute spec/3 'callback [
				append last functions 'callback
			]
		]
		
		compare-func-specs: func [
			f-type [block!] c-type [block!] /with fun [word!] cb [get-word!] /local spec pos idx
		][
			if with [
				cb: to word! cb
				if functions/:cb/3 <> functions/:fun/3 [
					throw-error [
						"incompatible calling conventions between"
						fun "and" cb
					]
				]
			]
			if pos: find f-type /local [f-type: head clear copy pos] ;-- remove locals
			if block? f-type/1 [f-type: next f-type]	;-- skip optional attributes block
			if block? c-type/1 [c-type: next c-type]	;-- skip optional attributes block
			idx: 2
			foreach [name type] f-type [
				if type <> c-type/:idx [return false]
				idx: idx + 2
			]
			true
		]
		
		ns-decorate: func [path [path!] /global /set][
			to get pick [set-word! word!] to logic! set mold path	;-- unless / use: replace/all mold path slash decoration
		]

		ns-join: func [ns [path! word!] name [word! path! set-word! set-path!]][
			join ns to word! mold/flat name
		]

		ns-prefix: func [name [word! path! set-word! set-path!] /set][
			if set-word? name [name: to word! name]
			name: ns-join ns-path name
			either set [ns-decorate/set name][ns-decorate name]
		]
		
		check-enum-word: func [name [word!] /local error][
			case [
				all [find keywords name name <> 'context][
					error: ["attempt to redefine a protected keyword:" name]
				]
				find functions name [
					error: ["attempt to redefine existing function name:" name]
				]
				find definitions name [
					error:  ["attempt to redefine existing definition:" name]
				]
				find-aliased name [
					error:  ["attempt to redefine existing alias definition:" name]
				]
				base-type? name [
					error:  ["redeclaration of base type:" name ]
				]
				any [
					exists-variable? name
					get-variable-spec name
				][										;-- it's a variable
					error:  ["redeclaration of variable:" name]
				]
				enum-type? name [
					error:  ["redeclaration of enum identifier:" name ]
				]
				enum-id? name [
					error:  ["redeclaration of enumerator:" name ]
				]
			]
			if error [throw-error error]
		]
		
		check-keywords: func [name [word!]][
			if find keywords name [
				throw-error ["attempt to redefine a protected keyword:" name]
			]
		]
		
		check-path-index: func [path [path! set-path!] type [word!] /local ending enum-value][
			ending: path/2
			case [
				all [type = 'pointer ending = 'value][]	;-- pass thru case
				word? ending [
					either all [
						not local-variable? ending
						enum-value: get-enumerator ending
					][
						path/2: ending: enum-value
					][
						unless any [
							local-variable? ending
							find globals ending: resolve-ns ending
							get-enumerator ending
						][
							backtrack path
							throw-error ["undefined" type "index variable"]
						]
						if 'integer! <> first resolve-type ending [
							backtrack path
							throw-error [
								"attempt to use" type
								"indexing with a non-integer! variable"
							]
						]
					]
				]
				not integer? ending [
					backtrack path
					throw-error [
						"attempt to use" type
						"indexing with a non-integer! value"
					]
				]
			]
		]
		
		check-func-name: func [name [word!] /only][
			if find functions name [
				pc: back pc
				throw-error ["attempt to redefine existing function name:" name]
			]
			if any [enum-type? name	enum-id? name][
				pc: back pc
				throw-error ["attempt to redefine existing enumerator:" name]
			]
			if all [not only find any [locals globals] name][
				pc: back pc
				throw-error ["a variable is already using the same name:" name]
			]
		]
		
		check-duplicates: func [
			name [word!] args [block! none!] locs [block! none!]
			/local dups
		][
			if args [remove-each item args: copy args [not word? item]]
			if locs [remove-each item locs: copy locs [not word? item]]
			
			if any [
				all [args (length? unique args) <> length? args]
				all [locs (length? unique locs) <> length? locs]
				all [args locs not empty? dups: intersect args locs]
			][
				throw-error [
					"duplicate variable definition in function" name
					either dups [reform ["for:" mold/only new-line/all dups no]][""]
				]
			]
		]
		
		check-specs: func [
			name specs /extend
			/local type type-def spec-type attribs value args locs cconv pos
		][
			unless block? specs [
				throw-error "function definition requires a specification block"
			]
			cconv: ['cdecl | 'stdcall]
			attribs: [
				[cconv ['variadic | 'typed | 'custom]]
				| [['variadic | 'typed | 'custom] cconv]
				| 'catch | 'infix | 'variadic | 'typed | 'custom | 'callback | cconv
			]
			type-def: pick [[func-pointer | type-spec] [type-spec]] to logic! extend

			unless catch [
				parse specs [
					opt [								;-- function's attribute and main doc-string
						string! opt [into attribs]		;-- can be specified in any order
						| into attribs opt string!
					]
					pos: copy args any [pos: word! into type-def opt string!]	;-- arguments definition
					pos: opt [							;-- return type definition				
						set value set-word! (					
							rule: pick reduce [[into type-spec] fail] value = return-def
						) rule
						opt string!
					]
					pos: opt [/local copy locs some [pos: word! opt [into type-spec]]] ;-- local variables definition
				]
			][
				throw-error rejoin ["invalid definition for function " name ": " mold pos]
			]
			if block? args [
				clear-docstrings args
				foreach [name type] args [
					if enum-id? name [
						throw-warning ["function's argument redeclares enumeration:" name]
					]
				]
			]
			check-duplicates name args locs
		]
		
		check-conditional: func [name [word!] expr][
			if last-type/1 <> 'logic! [check-expected-type/key name expr [logic!]]
		]
		
		check-expected-type: func [name [word!] expr expected [block!] /ret /key /local type alias][
			unless any [not none? expr key][return none]   ;-- expr == none for special keywords
			if all [
				not all [object? expr expr/action = 'null] ;-- avoid null type resolution here
				not none? expr							;-- expr can be false, so explicit check for none is required
				first type: resolve-expr-type expr		;-- first => deep check that it's not [none]
			][											;-- check if a type is returned or none
				type: resolve-aliased type
				if alias: find-aliased expected/1 [expected: alias]
			]
			if all [
				ret
				block? expr
				any [set-word? expr/1 set-path? expr/1]
			][
				type: none
			]
			unless any [
				all [
					object? expr
					expr/action = 'null
					type: either expected/1 = 'any-type! [expr/type][expected]	;-- morph null type to expected
					any-pointer? expected
				]
				all [
					type
					any [
						find type-sets expected/1
						find type-sets type/1
					]
					equal-types? type/1 expected/1		;-- internal polymorphic case
				]
				all [
					type
					type/1 = 'function!
					any [
						find [any-type! any-pointer!] expected/1
						all [
							expected/1 = 'function!
							compare-func-specs/with type/2 expected/2 name expr	 ;-- callback case
						]
					]
				]
				expected = type 						;-- normal single-type case
				all [
					type
					type/1 = 'integer!
					enum-type? expected/1				;-- TODO: add also a value check for enums
				]
			][
				if expected = type [type: 'null]		;-- make null error msg explicit
				any [
					backtrack any [all [block? expr expr/1] expr]
					backtrack name
				]
				throw-error [
					reform case [
						ret   [["wrong return type in function:" name]]
						key   [[
							uppercase form name "requires a conditional expression"
							either find [while until] name ["as last expression"][""]
						]]
						'else [["argument type mismatch on calling:" name]]
					]
					"^/*** expected:" join mold expected #","
					"found:" mold new-line/all any [type [none]] no
				]
			]
			type
		]
		
		check-arguments-type: func [name args /local entry spec list type][
			if find [set-word! set-path!] type?/word name [exit]
			
			entry: find functions name
			if all [
				not empty? spec: entry/2/4 
				block? spec/1
			][
				spec: next spec							;-- jump over attributes block
			]
			list: clear []
			forall args [
				either all [decimal? args/1 spec/2/1 = 'float32!][
					args/1:	make action-class [			;-- inject type casting to float32!
						action: 'type-cast
						type: [float32!]
						data: args/1					;-- literal float!
					]
					append/only list spec/2				;-- pass-thru for float! values used as float32! arguments
				][
					append/only list check-expected-type name args/1 spec/2
				]
				spec: skip spec	2
			]
			if all [
				any [
					find emitter/target/comparison-op name
					find emitter/target/bitwise-op name
				]
				not equal-types? list/1/1 list/2/1		;-- allow implicit casting for math ops only
			][
				backtrack name
				throw-error [
					"left and right argument must be of same type for:" name
					"^/*** left:" join list/1/1 #"," "right:" list/2/1
				]
			]
			if find emitter/target/math-op name	[
				case [
					any [
						all [list/1/1 = 'byte! any-pointer? list/2]
						all [list/2/1 = 'byte! any-pointer? list/1]
					][
						backtrack name
						throw-error [
							"arguments must be of same size for:" name
							"^/*** left:" join list/1/1 #"," "right:" list/2/1
						]
					]
					any [string? unbox args/1 string? unbox args/2][
						backtrack name
						throw-error "a literal string cannot be used with a math operator"
					]
				]
			]
		]
		
		check-variable-arity?: func [spec [block!] /local attribs][
			all [
				attribs: get-attributes spec
				any [
					all [find attribs 'variadic 'variadic]
					all [find attribs 'typed 'typed]
					all [find attribs 'custom 'custom]
				]
			]
		]
		
		check-body: func [body][
			case/all [
				not block? :body [throw-error "expected a block of code"]
				empty? body  	 [throw-error "expected a non-empty block of code"]
			]
		]
		
		fetch-into: func [								;-- compile sub-block
			code [block! paren!] body [block!] /root
			/local save-pc level
		][
			if root [
				level: block-level						;-- save block level from parent context
				clear expr-call-stack
			]
			save-pc: pc
			pc: code
			do body
			if root [block-level: level]
			next pc: save-pc
		]
		
		get-attributes: func [spec [block!]][
			any [
				all [block? spec/1 spec/1]
				all [string? spec/1 block? spec/2 spec/2]
			]
		]
		
		find-attribute: func [spec [block!] name [word!]][
			either list: get-attributes spec [
				to logic! find list name
			][
				false
			]
		]
		
		get-cconv: func [specs [block!]][
			pick [cdecl stdcall] to logic! all [
				not empty? specs
				find-attribute specs 'cdecl
			]
		]
		
		fetch-func: func [name /local specs type cc attribs][
			name: to word! name
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			if ns-path [name: ns-prefix name]
			check-func-name name
			check-specs name specs: pc/2
			specs: copy specs
			clear-docstrings specs
			
			type: 'native
			cc:   'stdcall								;-- default calling convention
			
			if all [
				not empty? specs
				attribs: get-attributes specs
			][
				case [
					find attribs 'infix [
						if 2 <> get-arity specs [
							throw-error [
								"infix function requires 2 arguments, found"
								get-arity specs "for" name
							]
						]
						type: 'infix
					]
					find attribs 'cdecl   [cc: 'cdecl]
					find attribs 'stdcall [cc: 'stdcall]	;-- get ready when fastcall will be the default cc
				]
			]
			add-function type reduce [name none specs] cc
			emitter/add-native name
			repend natives [
				name specs pc/3 script
				all [ns-path copy ns-path]
				all [ns-stack copy/deep ns-stack]		;@@ /deep doesn't work on paths
			]
			pc: skip pc 3
		]
		
		reduce-logic-tests: func [expr /local test value][
			test: [logic? expr/2 logic? expr/3]
			
			if all [
				block? expr
				find [= <>] expr/1
				any test
			][
				expr: either all test [
					do expr								;-- let REBOL reduce the expression
				][
					expr: copy expr
					if any [
						all [expr/1 = '= not all [expr/2 expr/3]]
						all [expr/1 = first [<>] any [expr/2 = true expr/3 = true]]
					][
						insert expr 'not
					]
					remove-each v expr [any [find [= <>] v logic? v]]
					if any [
						all [
							word? expr/1
							any [
								get-variable-spec expr/1
								enum-id? expr/1
							]
						]
						paren? expr/1
						block? expr/1
						object? expr/1
					][
						expr: expr/1					;-- remove outer brackets if variable
					]
					expr
				]
			]
			expr
		]
		
		process-export: has [defs cc ns func? spec][
			if word? pc/2 [
				unless find [stdcall cdecl] cc: pc/2 [
					throw-error ["invalid calling convention specifier:" cc]
				]
				pc: next pc
			]
			foreach name pc/2 [
				func?: no
				unless any [word? name path? name][
					throw-error ["invalid exported symbol:" mold name]
				]
				if path? name [name: resolve-ns-path name]
				unless any [
					find globals name
					func?: find-functions name
				][
					throw-error ["undefined exported symbol:" mold name]
				]
				append exports name
				
				if func? [
					spec: select functions name
					spec/3: any [cc 'cdecl]
					unless spec/5 = 'callback [append spec 'callback]
				]
			]
		]
		
		process-import: func [defs [block!] /local lib list cc name specs spec id reloc pos][
			unless block? defs [throw-error "#import expects a block! as argument"]
			
			unless parse defs [
				some [
					pos: set lib string! (
						unless list: select imports lib [
							repend imports [lib list: make block! 10]
						]
					)
					pos: set cc ['cdecl | 'stdcall]		;-- calling convention	
					pos: into [
						some [
							specs:						;-- new function mapping marker
							pos: set name set-word! (
								name: to word! name
								store-ns-symbol name
								if ns-path [
									add-ns-symbol to set-word! name
									name: ns-prefix name
								]
								check-func-name name
							)
							pos: set id   string!   (repend list [id reloc: make block! 1])
							pos: set spec block!    (
								check-specs/extend name spec
								clear-docstrings spec
								specs: copy specs
								specs/1: name
								add-function 'import specs cc
								emitter/import-function name reloc
							)
						]
					]
				]
			][
				throw-error ["invalid import specification at:" pos]
			]		
		]
		
		process-syscall: func [defs [block!] /local name id spec pos][
			unless block? defs [throw-error "#syscall expects a block! as argument"]
			unless parse defs [
				some [
					pos: set name set-word! (check-func-name name: to word! name)
					pos: set id   integer!
					pos: set spec block!    (
						check-specs/extend name spec
						spec: copy spec
						clear-docstrings spec
						add-function 'syscall reduce [name none spec] 'syscall
						append last functions id		;-- extend definition with syscode
					)
				]
			][
				throw-error ["invalid syscall specification at:" pos]
			]
		]
		
		process-enum: func [name value /local enum-value enum-names][
			unless word? name [throw-error "enumeration expected a word as name"]
			
			either block? value [
				check-enum-word name 					;-- first checking enumeration identifier possible conflicts
				parse value [
					(enum-value: 0)
					any [
						[
							copy enum-names word!
							| (enum-names: make block! 10) some [
								set enum-name set-word!
								(append enum-names to word! enum-name)
							]	set enum-value [integer! | word!]
						] 
						(enum-value: set-enumerator name enum-names enum-value)
						| set enum-name 1 skip (
							throw-error ["invalid enumeration:" to word! enum-name]
						)
					]
				]
			][
				throw-error ["invalid enumeration (block required!):" mold value]
			]
		]
		
		process-call: func [code [block!] /local mark][
			unless job/red-pass? [						;-- when Red runtime is included in a R/S app
				pc: skip pc 2							;-- just ignore #call directive
				return none
			]
			mark: tail red/output
			red/process-call-directive code/2 yes
			remove/part pc 2
			insert pc mark
			clear mark
			none										;-- do not return an expression to compile
		]
		
		comp-chunked: func [body [block!]][
			emitter/chunks/start
			do body
			emitter/chunks/stop
		]

		comp-directive: has [body][
			switch/default pc/1 [
				#import  [process-import  pc/2  pc: skip pc 2]
				#export  [process-export  pc/2  pc: skip pc 2]
				#syscall [process-syscall pc/2	pc: skip pc 2]
				#call	 [process-call	  pc]
				#enum	 [process-enum pc/2 pc/3 pc: skip pc 3]
				#verbose [set-verbose-level pc/2 pc: skip pc 2]
				#script	 [								;-- internal compiler directive
					unless pc/2 = 'in-memory [
						compiler/script: secure-clean-path pc/2	;-- set the origin of following code
					]
					pc: skip pc 2
				]
			][
				throw-error ["unknown directive" pc/1]
			]
		]
		
		comp-print-debug: has [out][
			unless word? name: pc/2 [
				throw-error "?? needs a word as argument"
			]
			out: next next compose/deep [
				2 (to pair! reduce [calc-line 1])		;-- hidden line offset header
				print-line [
					2 (to pair! reduce [calc-line 1])	;-- hidden line offset header
					(join name ": ") (name)
				]
			]
			out/2: next next out/2
			change/part pc out 2
			none
		]
		
		comp-comment: does [
			pc: next pc
			either block? pc/1 [pc: next pc][fetch-expression]
			none
		]
		
		comp-with: has [ns list with-ns words res ctx][
			ns: pc/2
			unless all [any [word? ns block? ns] block? pc/3][
				throw-error "WITH invalid argument"
			]
			unless block? ns [ns: reduce [ns]]
			
			forall ns [
				ns/1: either path? ctx: resolve-ns/path ns/1 [ctx][to path! ctx]
				unless find/only ns-list ns/1 [throw-error ["undefined context" ns/1]]
			]
			with-ns: unique copy ns
			
			list: clear []
			foreach ns with-ns [
				either empty? res: intersect list words: to block! second find/only ns-list ns [
					append list words
				][
					throw-warning rejoin [
						"contexts are using identical word"
						pick ["s: " ": "] 1 < length? res
						res
					]
				]
			]

			list: copy with-ns
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack list
			
			fetch-into/root pc/3 [comp-dialect]
			
			pc: skip pc 3
			clear skip tail ns-stack negate length? list
			if empty? ns-stack [ns-stack: none]
			
			none
		]
		
		comp-context: has [name level][
			unless block? pc/2 [throw-error "context specification block is missing"]
			unless set-word? pc/-1 [throw-error "context's name setting is missing"]
			unless zero? block-level [
				pc: back pc
				throw-error "context has to be declared at root level"
			]
			
			check-keywords name: to word! pc/-1
			if any [										;@@ factorize this out
				all [locals find locals name]
				find globals name
				find functions name
				find aliased-types name
				find definitions name
				find enumerations name
			][
				pc: back pc
				throw-error "context name is already taken"
			]
			pc: next pc
			
			unless ns-stack [ns-stack: make block! 1]
			append ns-stack to word! mold/flat name
			
			either ns-path [
				append ns-path to word! mold/flat name
			][
				ns-path: to lit-path! mold/flat name		;-- workaround newline flag remanence issue
			]
			either find/only ns-list ns-path [
				throw-error ["context" name "already defined"]
			][
				repend ns-list [copy ns-path make hash! 32]
			]

			fetch-into/root pc/1 [comp-dialect]
			
			remove back tail ns-path
			if empty? ns-path [ns-path: none]
			remove back tail ns-stack
			if empty? ns-stack [ns-stack: none]
			
			pc: next pc
			none
		]
		
		comp-declare: has [rule value pos offset ns][
			unless find [set-word! set-path!] type?/word pc/-1 [
				throw-error "assignment expected before literal declaration"
			]
			value: to paren! reduce either find [pointer! struct!] pc/2 [
				rule: get pick [struct-syntax pointer-syntax] pc/2 = 'struct!
				unless catch [parse pos: pc/3 rule][
					throw-error ["invalid literal syntax:" mold pos]
				]
				if all [
					pc/2 = 'struct!
					(length? pc/3) <> (length? unique/skip pc/3 2)
				][
					throw-error ["duplicate member name in struct:" mold pc/3]
				]
				if pc/3/1 = 'float64! [pc/3/1: 'float!]
				offset: 3
				[pc/2 pc/3]
			][
				unless all [word? pc/2 resolve-aliased reduce [pc/2]][
					throw-error ["declaring literal for type" pc/2 "not supported"]
				]
				value: pc/2
				if all [ns-path ns: find-aliased/prefix value][value: ns]
				offset: 2
				['struct! value]
			]
			pc: skip pc offset
			value
		]
		
		comp-null: does [
			pc: next pc
			make action-class [action: 'null type: [any-pointer!] data: 0]
		]
		
		comp-as: has [ctype ptr? expr type][
			ctype: pc/2
			if ptr?: find [pointer! struct! function!] ctype [ctype: reduce [pc/2 pc/3]]
			
			unless any [
				parse blockify ctype [func-pointer | type-syntax]
				find-aliased ctype
			][
				throw-error ["invalid target type casting:" ctype]
			]
			pc: skip pc pick [3 2] to logic! ptr?
			expr: fetch-expression

			if all [
				block? ctype
				ctype/1 = 'function!
				type: get-type expr
				type/1 = 'function!
			][
				unless compare-func-specs ctype/2 copy type/2 [
					throw-error "invalid functions casting: specifications not matching"
				]
			]
			if all [object? expr expr/action = 'null][
				pc: back pc
				throw-error "type casting on null value is not allowed"
			]
			make action-class [
				action: 'type-cast
				type: blockify ctype
				data: expr
			]
		]
		
		comp-assert: has [expr line][
			either job/debug? [
				line: calc-line
				pc: next pc
				expr: fetch-expression/final
				check-conditional 'assert expr			;-- verify conditional expression
				expr: process-logic-encoding expr yes

				insert/only pc next next compose [
					2 (to pair! reduce [line 1])			;-- hidden line offset header
					***-on-quit 98 as integer! system/pc
				]
				set [unused chunk] comp-block-chunked		;-- compile TRUE block
				emitter/set-signed-state expr				;-- properly set signed/unsigned state
				emitter/branch/over/on chunk reduce [expr/1] ;-- branch over if expr is true
				emitter/merge chunk
				last-type: none-type
				<last>
			][
				pc: next pc
				fetch-expression							;-- consume next expression
				none
			]
		]
		
		comp-alias: has [name pos][
			unless set-word? pc/-1 [
				throw-error "assignment expected for ALIAS"
			]
			unless find [struct! function!] pc/2 [
				throw-error "ALIAS only allowed for struct! and function!"
			]
			name: to word! pc/-1
			store-ns-symbol name
			if ns-path [add-ns-symbol pc/-1]
			all [
				not base-type? name
				ns-path
				name: ns-prefix name
			]
			if find aliased-types name [
				pc: back pc
				throw-error reform [
					"alias name already defined as:"
					mold aliased-types/:name
				]
			]
			if base-type? name [
				pc: back pc
				throw-error "a base type name cannot be defined as an alias name"
			]
			repend aliased-types [name reduce [pc/2 pc/3]]
			switch pc/2 [
				struct! [
					unless catch [parse pos: pc/3 struct-syntax][
						throw-error ["invalid struct syntax:" mold pos]
					]
				]
				function! [check-specs 'pointer pc/3]
			]
			pc: skip pc 3
			none
		]
		
		comp-size?: has [type expr][
			pc: next pc
			unless all [
				word? expr: pc/1
				type: any [
					all [base-type? expr expr]
					all [enum-type? expr [integer!]]
					find-aliased expr
				]
				pc: next pc
			][
				expr: fetch-expression/final	
				type: resolve-expr-type expr
			]
			emitter/get-size type expr
		]
		
		comp-exit: func [/value /local expr type ret][
			unless locals [
				throw-error [pc/1 "is not allowed outside of a function"]
			]
			pc: next pc
			ret: select locals return-def
			
			either value [				
				unless ret [							;-- check if return: declared
					throw-error [
						"RETURN keyword used without return: declaration in"
						func-name
					]
				]
				expr: fetch-expression/final/keep		;-- compile expression to return
				type: check-expected-type/ret func-name expr ret
				ret: either type [last-type: type <last>][none]
			][
				if ret [throw-error "EXIT keyword is not compatible with declaring a return value"]
			]
			emitter/target/emit-exit
			ret
		]
		
		comp-catch: has [offset][
			pc: next pc
			fetch-expression/keep/final
			unless block? pc/1 [throw-error "CATCH keyword requires a body block as 2nd argument"]
			
			catch-level: catch-level + 1
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			catch-level: catch-level - 1
			
			offset: emitter/target/emit-open-catch length? chunk/1
			foreach ptr chunk/2 [ptr/1: ptr/1 + offset]	;-- account for (catch-frame + push) opcodes
			emitter/merge chunk
			emitter/target/emit-close-catch
			last-type: none-type
			none
		]

		comp-block-chunked: func [/only /test name [word!] /local expr][
			emitter/chunks/start
			expr: either only [
				fetch-expression/final					;-- returns first expression
			][
				comp-block/final						;-- returns last expression
			]
			if test [
				check-conditional name expr				;-- verify conditional expression
				expr: process-logic-encoding expr no
			]
			reduce [
				expr 
				emitter/chunks/stop						;-- returns a chunk block!
			]
		]
		
		process-logic-encoding: func [expr invert? [logic!]][	;-- preprocess logic values
			case [
				logic? expr [ [#[true]] ]
				find [word! path!] type?/word expr  [
					emitter/target/emit-integer-operation '= [<last> 0]
					reduce [not invert?]
				]
				object? expr [
					expr: cast expr
					unless find [word! path!] type?/word any [
						all [block? expr expr/1] expr 
					][
						emitter/target/emit-integer-operation '= [<last> 0]
					]
					process-logic-encoding expr invert?
				]
				block? expr [
					case [
						find comparison-op expr/1 [expr]
						'else [process-logic-encoding expr/1 invert?]
					]
				]
				tag? expr [
					either last-type/1 = 'logic! [
						emitter/target/emit-integer-operation '= [<last> 0]
						reduce [not invert?]
					][expr] 
				]
				'else [expr]
			]
		]
		
		comp-if: has [expr unused chunk][		
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'if expr					;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
	
			set [unused chunk] comp-block-chunked		;-- compile TRUE block
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/on chunk expr/1			;-- insert IF branching			
			emitter/merge chunk
			last-type: none-type
			<last>
		]
		
		comp-either: has [expr e-true e-false c-true c-false offset t-true t-false ret][
			pc: next pc
			expr: fetch-expression/final				;-- compile expression
			check-conditional 'either expr				;-- verify conditional expression
			expr: process-logic-encoding expr no
			check-body pc/1								;-- check TRUE block
			check-body pc/2								;-- check FALSE block
			
			set [e-true c-true]   comp-block-chunked	;-- compile TRUE block
			set [e-false c-false] comp-block-chunked	;-- compile FALSE block

			t-true:  resolve-expr-type/quiet e-true
			t-false: resolve-expr-type/quiet e-false

			last-type: either all [
				t-true/1 t-false/1
				t-true:  resolve-aliased t-true			;-- alias resolution is safe here
				t-false: resolve-aliased t-false
				equal-types? t-true/1 t-false/1
			][t-true][none-type]						;-- allow nesting if both blocks return same type

			if any [
				all [
					locals								;-- if in function body
					tail? pc							;-- and if at tail of body
					ret: select locals return-def		;-- and if function returns something
					ret/1 = 'logic!						;-- and if it returns a logic! value
				]
				all [
					not empty? expr-call-stack
					last-type/1 = 'logic!				;-- and if EITHER returns a logic! too
				]
			][
				if block? e-true  [emitter/logic-to-integer/with e-true  c-true]
				if block? e-false [emitter/logic-to-integer/with e-false c-false]
			]
		
			offset: emitter/branch/over c-false
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/over/adjust/on c-true negate offset expr/1	;-- skip over JMP-exit
			emitter/merge emitter/chunks/join c-true c-false
			<last>
		]
		
		comp-case: has [cases list test body op bodies offset types][
			pc: next pc
			cases: pc/1
			list:  make block! 8
			types: make block! 8
			
			until [										;-- collect and pre-compile all cases
				append expr-call-stack #test			;-- marker for disabling expression post-processing
				fetch-into cases [						;-- compile case test
					append/only list comp-block-chunked/only/test 'case
					cases: pc							;-- set cursor after the expression
				]
				clear find expr-call-stack #test
				
				append expr-call-stack #body			;-- marker for enabling expression post-processing
				fetch-into cases [						;-- compile case body
					append/only list body: comp-block-chunked
					append/only types resolve-expr-type/quiet body/1
				]
				clear find expr-call-stack #body
				tail? cases: next cases
			]
			
			bodies: comp-chunked [raise-runtime-error 100] ;-- raise a runtime error if unmatched value
			
			list: tail list								;-- point to last case test
			until [										;-- left join all cases in reverse order			
				list: skip list -2
				set [test body] list					;-- retrieve case-test and case-body chunks

				emitter/set-signed-state test/1			;-- properly set signed/unsigned state
				offset: negate emitter/branch/over bodies		;-- insert case exit branching
				emitter/branch/over/on/adjust body/2 test/1/1 offset	;-- insert case test branching
				
				body: emitter/chunks/join test/2 body/2	;-- join case test with case body
				bodies: emitter/chunks/join body bodies	;-- left join case with other cases
				head? list		
			]	
			emitter/merge bodies						;-- commit all to main code buffer
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-switch: has [expr save-type spec value values body bodies list types default pos][
			pc: next pc
			expr: fetch-expression/keep/final			;-- compile argument
			if any [none? expr last-type = none-type][
				throw-error "SWITCH argument has no return value"
			]
			save-type: last-type			
			check-body spec: pc/1
			foreach w [values list types][set w make block! 8]
			forall spec [								;-- resolve possible enumeration symbols
				if all [word? spec/1 spec/1 <> 'default][
					check-enum-symbol spec
				]
			]
			
			;-- check syntax and store parts in different lists
			unless parse spec [
				some [
					pos: copy value some [integer! | char!] 
					(repend values [value none])		;-- [value body-offset ...]
					pos: block! (
						fetch-into pos [				;-- compile action body
							body: comp-block-chunked
							append/only list body/2		
							append/only types resolve-expr-type/quiet body/1
						]
					)
				]
				opt [
					'default pos: block! (
						fetch-into pos [				;-- compile default body
							default: comp-block-chunked
							append/only types resolve-expr-type/quiet default/1
						]
					)
				]
			][
				throw-error ["wrong syntax in SWITCH block at:" copy/part pos 4]
			]

			;-- assemble all actions together, with exit at end for each one
			bodies: emitter/chunks/empty
			list: tail list								;-- point to last action
			until [										;-- left join all actions in reverse order		
				body: first list: back list
				unless empty? bodies/1 [
					emitter/branch/over bodies			;-- insert case exit branching
				]
				bodies: emitter/chunks/join body bodies	;-- left join action with other actions		
				change at values 2 * index? list length? bodies/1
				head? list		
			]
			
			;-- insert default clause or jump to runtime error
			either default [
				emitter/branch/over bodies          	;-- insert default exit branching
				bodies: emitter/chunks/join default/2 bodies ;-- insert default action
			][
				body: comp-chunked [raise-runtime-error 101] ;-- raise a runtime error if unmatched value
				bodies: emitter/chunks/join body bodies
			]

			;-- construct tests + branching and insert them at head
			last-type: save-type
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			values: tail values
			until [
				values: skip values -2
				foreach v values/1 [					;-- process multiple values per action
					body: comp-chunked [
						emitter/target/emit-integer-operation '= reduce [<last> v]
					]
					emitter/branch/over/on/adjust bodies [=] values/2	;-- insert action branching			
					bodies: emitter/chunks/join body bodies
				]
				head? values
			]
			emitter/merge bodies						;-- commit all to main code buffer	
			
			pc: next pc
			last-type: equal-types-list? types			;-- test if usage in expression allowed
			<last>
		]
		
		comp-until: has [expr chunk][
			pc: next pc
			check-body pc/1
			set [expr chunk] comp-block-chunked/test 'until
			emitter/branch/back/on chunk expr/1	
			emitter/merge chunk	
			last-type: none-type
			<last>
		]
		
		comp-while: has [expr unused cond body offset bodies][
			pc: next pc
			check-body pc/1								;-- check condition block
			check-body pc/2								;-- check body block
			
			set [expr cond]   comp-block-chunked/test 'while	;-- Condition block
			set [unused body] comp-block-chunked		;-- Body block
			
			if logic? expr/1 [expr: [<>]]				;-- re-encode test op
			offset: emitter/branch/over body			;-- Jump to condition
			bodies: emitter/chunks/join body cond
			emitter/set-signed-state expr				;-- properly set signed/unsigned state
			emitter/branch/back/on/adjust bodies reduce [expr/1] offset ;-- Test condition, exit if FALSE
			emitter/merge bodies
			last-type: none-type
			<last>
		]
		
		comp-expression-list: func [/_all /local list offset bodies op][
			pc: next pc
			check-body pc/1								;-- check body block
			
			list: make block! 8
			pc: fetch-into pc/1 [
				while [not tail? pc][					;-- comp all expressions in chunks
					append/only list comp-block-chunked/only/test pick [all any] to logic! _all
				]
			]
			list: back tail list
			set [offset bodies] emitter/chunks/make-boolean			;-- emit ending FALSE/TRUE block
			if _all [emitter/branch/over/adjust bodies offset/1]	;-- conclude by a branch on TRUE
			offset: pick offset not _all				;-- branch to TRUE or FALSE 
			
			until [										;-- left join all expr in reverse order			
				op: either logic? list/1/1/1 [first [<>]][list/1/1/1]
				unless _all [op: reduce [op]]			;-- do not invert the test if ANY
				emitter/set-signed-state list/1/1		;-- properly set signed/unsigned state
				emitter/branch/over/on/adjust bodies op offset		;-- first emit branch				
				bodies: emitter/chunks/join list/1/2 bodies			;-- then left join expr
				also head? list	list: back list
			]	
			emitter/merge bodies
			last-type: [logic!]
			<last>
		]
		
		comp-assignment: has [name value n enum ns][
			push-call name: pc/1
			pc: next pc
			if set-word? name [
				n: to word! name
				unless any [locals local-variable? n][store-ns-symbol n]
				
				unless all [
					local-variable? n
					n = 'context						;-- explicitly allow 'context name for local variables
				][
					check-keywords n					;-- forbid keywords redefinition
				]
				if find definitions n [
					backtrack name
					throw-error ["redeclaration of definition" name]
				]
				if all [
					not local-variable? n
					enum: enum-id? n
				][
					backtrack name
					throw-error ["redeclaration of enumerator" name "from" enum]
				]
				if all [
					get-word? pc/1
					find functions to word! pc/1
				][
					throw-error "storing a function! requires a type casting"
				]
				unless local-variable? n [
					if all [ns-path none? locals][add-ns-symbol pc/-1]
					if all [ns: resolve-ns n ns <> n][name: to set-word! ns]
					check-func-name/only to word! name	;-- avoid clashing with an existing function name		
				]
			]
			if set-path? name [
				unless any [name/1 = 'system local-variable? name/1][
					name: resolve-ns-path name
				]
				if all [series? name value: system-reflexion? name][name: value]
			]
			
			either none? value: fetch-expression [		;-- explicitly test for none!
				none
			][
				new-line/all reduce [name value] no
			]
		]
		
		comp-func-args: func [name [word!] entry [hash!] /local attribute fetch expr args n pos][
			push-call name
			pc: next pc							;-- it's a function
			either attribute: check-variable-arity? entry/2/4 [
				fetch: [
					pos: pc
					expr: fetch-expression
					either attribute = 'typed [
						if all [expr = <last> none? last-type/1][
							pc: pos
							throw-error "expression has no defined return type"
						]
						append args id: get-type-id expr
						append/only args expr
						append args pick [#_ 0] id = emitter/datatype-ID/float! ;-- 32-bit padding
					][
						append/only args expr
					]
				]
				args: make block! 1
				either block? pc/1 [
					fetch-into pc/1 [until [do fetch tail? pc]]
					pc: next pc					;-- jump over arguments block
				][
					do fetch
				]
				reduce [name to-issue attribute args]
			][									;-- fixed arity case
				args: make block! n: entry/2/1
				loop n [append/only args fetch-expression]	;-- fetch n arguments
				new-line/all head insert/only args name no
			]
		]
		
		resolve-ns-path: func [path [path! set-path!] /local new pos][
			new: resolve-ns/path path/1					;-- try to prefix path/1

			either find/only ns-list to path! new [		;-- check if (prefixed) path/1 is a namespace
				new: to path! new
				until [									;-- collect all ns prefixes from head
					path: next path
					append new path/1					;-- move each path value to new one
					not find/only ns-list new			;-- while the new path is still a namespace
				]
				new: ns-decorate new					;-- prefix and convert to word 
				unless tail? next path [				;-- if non-ns remains in path
					new: append to path! new next path	;-- convert back to path by adding non-ns remain 
				]
				if set-path? path [
					new: to either word? new [set-word!][set-path!] new
				]
				new
			][
				unless word? new [path/1: ns-decorate new]	;-- only prefix+convert path/1 if required
				path
			]
		]
		
		comp-path: has [path value ns type name][
			path: pc/1
			if #":" = first mold path/1 [
				throw-error "get-path! syntax is not supported"
			]
			either all [
				not local-variable? path/1
				path: resolve-ns-path path
				word? path
			][
				if value: get-enumerator path [
					last-type: [integer!]
					pc: next pc
					return value
				]
				comp-word/with path
			][
				case [
					value: system-reflexion? path [
						either path/2 = 'words [
							return comp-word/with/root value ;-- re-route to global word resolution
						][
							pc: next pc
						]
					]
					'function! = first type: resolve-path-type/short path [
						name: to word! form path
						check-specs name type/2
						clear-docstrings type/2
						add-function 'routine reduce [name none type/2] get-cconv type/2
						append last functions reduce [path 'local]
						return comp-func-args name skip tail functions -2
					]
					'else [
						comp-word/path path/1				;-- check if root word is defined
						last-type: resolve-path-type path
					]
				]
				any [value path]
			]
		]
		
		comp-get-word: has [spec name ns symbol][
			name: resolve-ns to word! pc/1
			comp-word/with/check name
			
			if all [
				spec: find functions name
				spec: spec/2
			][
				unless find [native routine] spec/2 [
					throw-error "get-word syntax only reserved for native functions for now"
				]
				if all [
					symbol: last expr-call-stack
					spec: find functions symbol
					spec/2/2 = 'import					;-- only flag it when passed to external calls
					spec/2/5 <> 'callback
				][
					append spec/2 'callback				;@@ force cdecl ????
				]
			]
			also to get-word! name pc: next pc
		]
		
		direct-match-ns: func [ctx [path!] name [word!] path /local ns][
			if all [
				any [
					all [ns-stack find/only ns-stack ctx]
					all [ns-path find/only ns-path ctx]
				]
				ns: find/only ns-list ctx
				find ns/2 name
			][
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join ctx name
			]
		]
		
		match-ns: func [name [word!] ctx [word! path!] path /local pos][
			either pos: find ns-stack either path? ctx [ctx/1][ctx][ ;-- match (1st) context with stack
				if path? ctx [							;-- context hierarchy to match with stack
					foreach level ctx [					;-- match each context with next one on stack
						if pos/1 <> level [return none]	;-- if doesn't match, prefix doesn't apply
						pos: next pos					;-- next stack entry
					]
				]
				if path [return ns-join to path! ctx name] ;-- if /path, defer word conversion
				ns-decorate ns-join to path! ctx name	;-- prefix and convert back to word
			][
				none									;-- no match on stack
			]
		]
		
		resolve-ns: func [name [word!] /path /local ctx pos][
			unless ns-stack [return name]				;-- no current ns, pass-thru

			if ctx: find/skip sym-ctx-table name 2 [	;-- fetch context candidates
				ctx: ctx/2								;-- SELECT/SKIP on hash! unreliable!
				either block? ctx [						;-- more than one candidate
					all [								;-- try direct matching first
						pos: find/only ctx to path! load mold ns-stack	;-- safer to-path conversion
						return either path [
							ns-join to path! first pos name
						][
							ns-decorate ns-join first pos name
						]
					]
					ctx: tail ctx						;-- start from last defined context
					until [
						ctx: back ctx
						if value: any [
							match-ns name ctx/1 path 
							direct-match-ns ctx/1 name path
						][
							return value				;-- prefix name if context on stack
						]
						head? ctx
					]									;-- no match found, pass-thru
				][										;-- one parent context only
					name: any [
						match-ns name ctx path		 	;-- prefix name if context is on stack
						direct-match-ns ctx name path
						name
					]
				]
			]
			name
		]
	
		comp-word: func [
			/path symbol [word!]
			/with word [word!]
			/root										;-- system/words/* pass-thru
			/check										;-- check word validity, do not consume input
			/local entry name local? spec type
		][
			name: pc/1
			if name = shift-right-sym [name: '-**]		;-- replace '>>> words produced by Red layer

			name: any [
				word
				symbol
				all [local-variable? name name]			;-- pass-thru for locals
				all [not root resolve-ns name]
				name
			]
			local?: local-variable? name
			case [
				all [
					not all [local? name = 'context]
					entry: select keywords name			;-- it's a reserved word
				][
					if find calling-keywords name [push-call pc/1]
					unless check [do entry]
				]
				any [
					all [
						local?
						any [
							all [						;-- block local function pointers
								block? type: select locals name
								'function! <> type/1
							]
							not block? type				;-- pass-thru
						]
					]
					all [
						find globals name
						'function! <> first get-type name	;-- block function pointers
					]
				][										;-- it's a variable
					if not-initialized? name [
						throw-error ["local variable" name "used before being initialized!"]
					]
					last-type: resolve-type name
					unless check [also name pc: next pc]
				]
				type: enum-type? name [
					last-type: type
					if verbose >= 3 [print ["ENUMERATOR" name "=" last-type]]
					unless check [also name pc: next pc]
				]
				all [
					not path
					entry: find-functions name
				][
					spec: entry/2/4
					if all [
						find-attribute spec 'infix
						path? pc/1
					][
						throw-error "infix functions cannot be called using a path"
					]
					unless check [comp-func-args name entry]
				]
				'else [throw-error ["undefined symbol:" mold name]]
			]
		]
		
		cast-null: func [variable [set-word! set-path!] /local casting][
			unless all [
				attempt [
					casting: get-type any [
						all [set-word? variable	to word! variable]
						to path! variable
					]
				]
				any-pointer? casting
			][
				backtrack variable
				throw-error "Invalid null assignment"
			]			
			casting
		]
		
		order-args: func [name [word!] args [block!]][
			if any [
				all [
					find [import native infix routine] functions/:name/2
					find [stdcall cdecl] functions/:name/3
				]
				all [
					functions/:name/2 = 'syscall
					job/syscall = 'BSD
				]
				all [
					functions/:name/2 = 'syscall		
					job/target = 'ARM					;-- odd, but required for Linux/ARM syscalls
					job/syscall = 'Linux
				]
			][		
				reverse args
			]
		]
		
		external-call?: func [spec [block!] /local attribs][
			to logic! any [
				spec/5 = 'callback
				all [
					attribs: get-attributes spec/4
					any [find attribs 'cdecl find attribs 'stdcall]
				]
			]
		]

		comp-call: func [
			name [word!] args [block!] /sub
			/local list type res align? left right dup var-arity? saved? arg expr spec
		][
			name: decorate-fun name
			list: either issue? args/1 [				;-- bypass type-checking for variable arity calls
				args/2
			][
				check-arguments-type name args
				args
			]
			order-args name list						;-- reorder argument according to cconv

			spec: functions/:name
			align?: all [
				args/1 <> #custom
				any [
					spec/2 = 'import					;@@ syscalls don't seem to need special alignment??
					all [spec/2 = 'routine external-call? spec]
				]
			]
			if align? [emitter/target/emit-stack-align-prolog args]
			
			if args/1 <> #custom [
				type: functions/:name/2
				either type <> 'op [
					forall list [						;-- push function's arguments on stack
						expr: list/1
						if block? unbox expr [comp-expression expr yes]	;-- nested call
						if object? expr [cast expr]
						if type <> 'inline [
							emitter/target/emit-argument expr functions/:name ;-- let target define how arguments are passed
						]
					]
				][										;-- nested calls as op argument require special handling
					if block? unbox list/1 [comp-expression list/1 yes]	;-- nested call
					left:  unbox list/1
					right: unbox list/2
					if saved?: all [block? left any [block? right path? right]][
						emitter/target/emit-save-last	;-- optionally save left argument result
					]
					if block? unbox list/2 [comp-expression list/2 yes]	;-- nested call
					if saved? [emitter/target/emit-restore-last]
				]
			]
			res: emitter/target/emit-call name args to logic! sub

			either res [
				last-type: res
			][
				set-last-type functions/:name/4			;-- catch nested calls return type
			]
			if align? [emitter/target/emit-stack-align-epilog args]
			res
		]
				
		comp-path-assign: func [
			set-path [set-path!] expr casted [block! none!]
			/local type new value
		][
			value: unbox expr
			if find [block! path! tag!] type?/word value [
				emitter/target/emit-move-path-alt		;-- save assigned value
			]
			if all [
				not local-variable? set-path/1
				enum-id? set-path/1
			][
				backtrack set-path
				throw-error ["enumeration cannot be used as path root:" set-path/1]
			]
			unless get-variable-spec set-path/1 [
				backtrack set-path
				throw-error ["unknown path root variable:" set-path/1]
			]
			type: resolve-path-type set-path			;-- check path validity
			new: resolve-aliased get-type expr		

			if type <> any [casted new][
				backtrack set-path
				throw-error [
					"type mismatch on setting path:" to path! set-path
					"^/*** expected:" mold type
					"^/*** found:" mold any [casted new]
				]
			]		
			emitter/access-path set-path either any [block? value path? value][
				 <last>
			][
				expr
			]
		]
		
		comp-variable-assign: func [
			set-word [set-word!] expr casted [block! none!]
			/local name type new value fun-name
		][
			name: to word! set-word		
			if find aliased-types name [
				backtrack set-word
				throw-error "name already used for as an alias definition"
			]
			if not-initialized? name [
				init-local name expr casted				;-- mark as initialized and infer type if required
			]

			if all [
				casted
				casted/1 = 'function!
				local-variable? name
			][
				fun-name: decorate-function name
				add-function 'routine reduce [fun-name none casted/2] get-cconv casted/2
				append last functions reduce [name 'local]
			]
			
			either type: any [
				get-variable-spec name					;-- test if known variable (local or global)	
				enum-id? name
			][
				type: resolve-aliased type
				value: get-type expr
				if block? expr [parse value [type-spec]] ;-- prefix return type if required	
				new: resolve-aliased value
				
				if type <> any [casted new][
					backtrack set-word
					throw-error [
						"attempt to change type of variable:" name
						"^/*** from:" mold type
						"^/***   to:" mold any [casted new]
					]
				]
			][
				unless zero? block-level [
					backtrack set-word
					throw-error "variable not declared"
				]
				if any [
					all [casted casted/1 = 'function!]
					all [expr = <last> casted: last-type last-type/1 = 'function!]
				][
					add-function 'routine reduce [name none casted/2] get-cconv casted/2
				]
				type: add-symbol name unbox expr casted  ;-- if unknown add it to global context	
			]
			if none? type/1 [
				backtrack set-word
				throw-error ["unable to determine a type for:" name]
			]
			value: unbox expr
			if any [block? value path? value][value: <last>]
			emitter/store name value type
		]
		
		comp-expression: func [expr keep? [logic!] /local variable boxed casting new? type][
			;-- preprocessing expression
			if all [block? expr find [set-word! set-path!] type?/word expr/1][
				variable: expr/1
				expr: expr/2							;-- switch to assigned expression
				if set-word? variable [
					new?: not exists-variable? variable
				]
			]			
			if object? expr [							;-- unbox type-casting object
				if all [variable expr/action = 'null][
					casting: cast-null variable
				]
				boxed: expr
				expr: cast expr
			]
			
			;-- dead expressions elimination
			if all [
				not keep?
				not any [tail? pc variable]				;-- not last expression nor assignment value
				1 >= length? expr-call-stack			;-- one (for math op) or no parent call
				'switch <> pick tail expr-call-stack -1
				any [
					all [
						any [
							word? expr 					;-- variable alone
							literal? expr				;-- literal, but not logic value
						]
						'logic! <> first get-type expr
					]
					all [
						block? expr
						functions/(decorate-fun expr/1)/2 = 'op	;-- math expression
						any [							;-- no return value, or return value type <> logic!
							not type: find functions/(expr/1)/4 return-def
							type/2/1 <> 'logic!
						]
					]
				]
			][exit]

			;-- emitting expression code
			either block? expr [
				type: comp-call expr/1 next expr 		;-- function call case (recursive)
				if type [last-type: type]				;-- set last-type if not already set
				if all [
					variable boxed						;-- process casting if result assigned to variable
					last-type/1 = 'logic!
					boxed/type  = 'integer!				;-- fixes #967
				][
					emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
					last-type: boxed/type
				]
			][
				last-type: either not any [
					all [new? literal? unbox expr]		;-- if new variable, value will be store in data segment
					all [set-path? variable not path? expr]	;-- value loaded at lower level
					tag? unbox expr
				][
					emitter/target/emit-load either boxed [boxed][expr]	;-- emit code for single value
					either all [boxed not decimal? unbox expr][
						emitter/target/emit-casting boxed no	;-- insert runtime type casting if required
						boxed/type
					][
						resolve-expr-type expr
					]
				][
					resolve-expr-type expr
				]
			]
			
			;-- postprocessing result
			if all [
				any [
					keep?
					variable							;-- result needs to be stored
					all [
						'case = pick tail expr-call-stack -3
						#test <> pick tail expr-call-stack -2
						4 <= length? expr-call-stack
					]
				]
				block? expr								;-- and if expr is a function call		
				last-type/1 = 'logic!					;-- which return type is logic!
			][
				emitter/logic-to-integer expr/1			;-- runtime logic! conversion before storing
			]
			
			if all [									;-- clean FPU stack when required
				not any [keep? variable]
				block? expr
				word? expr/1
				any-float? get-return-type/check expr/1
				any [
					not find functions/(expr/1)/4 return-def	;-- clean if no return value
					1 = length? expr-call-stack					;-- or if return value not used
				]
			][
				emitter/target/emit-float-trash-last	;-- avoid leaving a x86 FPU slot occupied,
			]											;-- if return value is not used.
			
			;-- storing result if assignement required
			if variable [
				if all [boxed not casting][
					casting: resolve-aliased boxed/type
				]
				unless boxed [boxed: expr]
				switch type?/word variable [
					set-word! [comp-variable-assign variable expr casting]
					set-path! [comp-path-assign		variable boxed casting]
				]
			]
		]
		
		check-enum-symbol: func [code [any-block!] /local value][
			if all [									;-- if enum, replace it with its integer value
				word? code/1
				not local-variable? code/1
				value: get-enumerator resolve-ns code/1
			][
				change code value
			]
		]
		
		infix?: func [pos [block! paren!] /local specs][
			all [
				not tail? pos
				word? pos/1
				specs: find functions resolve-ns pos/1
				specs: specs/2
				find [op infix] specs/2
			]
		]
		
		check-infix-operators: has [pos][
			if infix? pc [
				either infix? back tail expr-call-stack [
					exit								;-- infix op already processed
				][
					throw-error "invalid use of infix operator"
				]
			]
			if infix? next pc [
				either find [set-word! set-path! struct!] type?/word pc/1 [
					throw-error "can't use infix operator here"
				][
					pos: 0								;-- relative index of next infix op
					until [								;-- search for all dependent infix op
						pos: pos + 2					;-- target next infix possible position
						insert pc pc/:pos				;-- transform to prefix notation
						remove at pc pos + 1
						not infix? at pc pos + 2		;-- exit when no more infix op found
					]
				]
			]
		]
		
		fetch-expression: func [/final /keep /local expr pass value][
			check-infix-operators
			
			if verbose >= 4 [print ["<<<" mold pc/1]]
			pass: [also pc/1 pc: next pc]
			
			if tail? pc [
				pc: back pc
				throw-error "missing argument"
			]
			if job/debug? [store-dbg-lines]
			
			check-enum-symbol pc

			expr: switch/default type?/word pc/1 [
				set-word!	[comp-assignment]
				word!		[comp-word]
				get-word!	[comp-get-word]
				path! 		[comp-path]
				set-path!	[comp-assignment]
				paren!		[comp-block/only]
				char!		[do pass]
				integer!	[do pass]
				string!		[do pass]
				decimal!	[do pass]
				block!		[also to paren! pc/1 pc: next pc]
				issue!		[comp-directive]
			][
				throw-error "datatype not allowed"
			]
			expr: reduce-logic-tests expr

			if final [
				if verbose >= 3 [?? expr]
				unless find [none! tag!] type?/word expr [
					comp-expression expr to logic! keep
				]
			]
			expr
		]
		
		comp-block: func [/final /only /local expr save-pc][
			block-level: block-level + 1
			save-pc: pc
			pc: pc/1

			either only [
				expr: either final [fetch-expression/final][fetch-expression]
				unless tail? pc [
					throw-error "more than one expression found in parentheses"
				]
			][
				while [not tail? pc][
					;if all [paren? pc/1 not infix? at pc 2][raise-paren-error]
					expr: either final [fetch-expression/final][fetch-expression]
					unless tail? pc [pop-calls]
				]
			]
			pc: next save-pc
			
			block-level: block-level - 1
			expr
		]
		
		comp-dialect: has [expr][
			block-level: 0
			while [not tail? pc][
				case [
					issue? pc/1 [comp-directive]
					all [
						set-word? pc/1
						find [func function] pc/2
					][
						pc: next pc
						fetch-func pc/-1				;-- allow function declaration at root level only
					]
					all [set-word? pc/1 pc/2 = 'alias][
						pc: next pc
						comp-alias						;-- allow alias declaration at root level only
					]
					paren? pc/1 [
						;unless infix? at pc 2 [raise-paren-error]
						expr: fetch-expression/final/keep
					]
					'else [expr: fetch-expression/final/keep]
				]
				pop-calls
				emitter/target/on-root-level-entry
			]
			expr
		]
		
		comp-func-body: func [
			name [word!] spec [block!] body [block!]
			/local args-sz local-sz expr ret
		][
			locals: spec
			func-name: name
			set [args-sz local-sz] emitter/enter name locals ;-- build function prolog
			pc: body
			
			expr: comp-dialect							;-- compile function's body
			
			if ret: select spec return-def [
				check-expected-type/ret name expr ret	;-- validate return value type
				if all [
					object? expr 
					find [block! tag!] type?/word expr/data
				][
					emitter/target/emit-casting expr no	;-- insert runtime type casting when required
					last-type: expr/type
				]
			]
			emitter/leave name locals args-sz local-sz	;-- build function epilog
			remove-func-pointers
			clear locals-init
			locals: func-name: none
		]
		
		comp-natives: does [			
			foreach [name spec body origin ns nss] natives [
				if verbose >= 2 [
					print [
						"---------------------------------------^/"
						"function:" name newline
						"---------------------------------------"
					]
				]
				script: origin
				ns-path: ns
				ns-stack: nss
				comp-func-body name spec body
			]
		]
		
		comp-header: has [pos][
			unless pc/1 = 'Red/System [
				throw-error "source is not a Red/System program"
			]
			pc: next pc
			unless block? pc/1 [
				throw-error "missing Red/System program header"
			]
			unless parse pc/1 [any [pos: set-word! skip]][
				throw-error ["invalid program header at:" mold pos]
			]
			pc: next pc
		]
		
		get-proto: func [name [word!]][
			switch/default job/OS [
				Windows [
					[handle [integer!]]
				]
				MacOSX [
					pick [
						[
							argc	[integer!]
							argv	[struct! [s [c-string!]]]
							envp	[struct! [s [c-string!]]]
							apple	[struct! [s [c-string!]]]
							pvars	[program-vars!]
						]
						[[cdecl]]
					] name = 'on-load
				]
			][											;-- Linux
				[[cdecl]]
			]
		]
		
		add-dll-callbacks: has [list code exp][			;-- add missing callbacks
			list: copy [on-load on-unload]
			if job/OS = 'Windows [
				append list [on-new-thread on-exit-thread]
			]
			code: make block! 1
			exp:  make block! 1
			
			foreach fun list [
				unless find/skip natives fun 6 [
					repend code [
						to set-word! fun 'func get-proto fun []	;-- stdcall
					]
				]
			]
			unless empty? code [
				pc: code
				comp-dialect
			]
		]

		run: func [obj [object!] src [block!] file [file!] /no-header /runtime /no-events][
			runtime: to logic! runtime
			job: obj
			pc: src
			script: secure-clean-path file
			unless no-header [comp-header]
			unless no-events [emitter/target/on-global-prolog runtime job/type]
			comp-dialect
			unless no-events [
				case [
					runtime [
						emitter/target/on-global-epilog yes	job/type ;-- postpone epilog event after comp-runtime-epilog
					]
					not job/runtime? [
						emitter/target/on-global-epilog no job/type
					]
				]
			]
		]
		
		finalize: does [
			if verbose >= 2 [print "^/---^/Compiling native functions^/---"]
			if job/type = 'dll [
				if empty? exports [
					throw-error "missing #export directive for library production"
				]
				add-dll-callbacks 						;-- make sure they are defined
			]
			comp-natives
			emitter/target/on-finalize
			if verbose >= 2 [print ""]
			emitter/reloc-native-calls
		]
	]
	
	set-verbose-level: func [level [integer!]][
		foreach ctx reduce [
			self
			loader
			compiler
			emitter
			emitter/target
			linker
		][
			ctx/verbose: level
		]
	]
	
	output-logs: does [
		case/all [
			verbose >= 1 [
				print [
					nl
					"-- compiler/globals --" nl mold new-line/all/skip to-block compiler/globals yes 2 nl
					"-- emitter/symbols --"  nl mold new-line/all/skip to-block emitter/symbols yes 2 nl
				]
			]
			verbose >= 2 [
				print [
					"-- compiler/functions --" nl mold new-line/all/skip to-block compiler/functions yes 2 nl
				]
			]
			verbose >= 6 [
				print [
					"-- emitter/code-buf --" nl mold emitter/code-buf nl
					"-- emitter/data-buf --" nl mold emitter/data-buf nl
					"as-string:"        	 nl mold as-string emitter/data-buf nl
				]
			]
		]
	]
	
	emit-main-prolog: has [name spec][
		either job/type = 'exe [
			emitter/target/on-init
		][												;-- wrap global code in a function
			name: '***-main
			compiler/add-function 'native reduce [name none []] 'stdcall
			spec: emitter/add-native name
			spec/2: 1
			emitter/target/emit-prolog name [] 0
		]
	]

	comp-start: has [script][
		emitter/libc-init?: yes
		emitter/start-prolog
		script:	either encap? [
			set-cache-base %system/runtime/
			%start.reds
		][
			secure-clean-path runtime-path/start.reds
		]
 		compiler/run/no-events job loader/process/own script script
 		emitter/start-epilog
 
		;-- selective clean-up of compiler's internals
 		remove/part find compiler/globals 'system 2		;-- avoid 'system redefinition clash
 		remove/part find emitter/symbols 'system 4
		clear compiler/definitions
		clear compiler/aliased-types
		emitter/libc-init?: no
	]
	
	comp-runtime-prolog: func [red? [logic!] /local script][
		script: either encap? [
			set-cache-base %system/runtime/
			%common.reds
		][
			secure-clean-path runtime-path/common.reds
		]
 		compiler/run/runtime job loader/process/own script script
 		
 		if red? [
 			unless empty? red/sys-global [
				set-cache-base %./
				compiler/run job loader/process red/sys-global %***sys-global.reds
 			]
 			set-cache-base %runtime/
 			script: pick [%red.reds %../runtime/red.reds] encap?
 			compiler/run job loader/process/own script script
 		]
 		set-cache-base none
	]
	
	comp-runtime-epilog: does [
		either job/need-main? [
			emitter/target/on-global-epilog no job/type	;-- emit main() epilog
		][
			switch job/type [
				exe [compiler/comp-call '***-on-quit [0 0]]	;-- call runtime exit handler
				dll [emitter/target/emit-epilog '***-main [] 0 0]
				drv [emitter/target/emit-epilog '***-main [] 0 0]
			]
		]
	]
	
	clean-up: does [
		compiler/ns-path: 
		compiler/ns-stack: 
		compiler/locals: none
		compiler/resolve-alias?:  yes
		
		clear compiler/imports
		clear compiler/exports
		clear compiler/natives
		clear compiler/ns-list
		clear compiler/sym-ctx-table
		clear compiler/globals
		clear compiler/definitions
		clear compiler/enumerations
		clear compiler/aliased-types
		clear compiler/user-functions
		clear compiler/debug-lines/records
		clear compiler/debug-lines/files
		clear emitter/symbols
	]
	
	make-job: func [opts [object!] file [file!] /local job][
		job: construct/with third opts linker/job-class	
		file: last split-path file					;-- remove path
		file: to-file first parse file "."			;-- remove extension
		case [
			none? job/build-basename [
				job/build-basename: file
			]
			slash = last job/build-basename [
				append job/build-basename file
			]
		]
		job
	]
	
	set 'dt func [code [block!] /local t0][
		t0: now/time/precise
		do code
		now/time/precise - t0
	]
	
	compile: func [
		files [file! block!]							;-- source file or block of source files
		/options
			opts [object!]
		/loaded 										;-- source code is already in LOADed format
			src	[block!]
		/local
			comp-time link-time err output
	][
		comp-time: dt [
			unless block? files [files: reduce [files]]
			
			unless opts [opts: make options-class []]
			job: make-job opts last files				;-- last input filename is retained for output name
			emitter/init opts/link? job
			if opts/verbosity >= 10 [set-verbose-level opts/verbosity]
			
			clean-up
			loader/init
			emit-main-prolog
			
			job/need-main?: to logic! any [
				job/need-main?							;-- pass-thru if set in config file
				all [
					job/type = 'exe
					not find [Windows MacOSX] job/OS
				]
			]
			
			if all [
				job/need-main?
				not opts/use-natives?
				opts/runtime?
			][
				comp-start								;-- init libC properly
			]
			
			if opts/runtime? [comp-runtime-prolog to logic! loaded]
			
			set-verbose-level opts/verbosity
			foreach file files [
				src: either loaded [
					loader/process/with src file
				][
					loader/process file
				]
				compiler/run job src file
			]
			set-verbose-level 0
			if opts/runtime? [comp-runtime-epilog]
			
			set-verbose-level opts/verbosity
			compiler/finalize							;-- compile all functions
			set-verbose-level 0
		]
		if verbose >= 5 [
			print [
				"-- emitter/code-buf (empty addresses):"
				nl mold emitter/code-buf nl
			]
		]

		if opts/link? [
			link-time: dt [
				job/symbols: emitter/symbols
				job/sections: compose/deep/only [
					code   [- 	(emitter/code-buf)]
					data   [- 	(emitter/data-buf)]
					import [- - (compiler/imports)]
				]
				if not empty? compiler/exports [
					append job/sections compose/deep/only [
						export [- - (compiler/exports)]
					]
				]
				if opts/debug? [
					job/debug-info: reduce ['lines compiler/debug-lines]
				]
				output: linker/build job
			]
		]
		
		set-verbose-level opts/verbosity
		output-logs
		if opts/link? [clean-up]

		reduce [
			comp-time
			link-time
			any [all [job/buffer length? job/buffer] 0]
			output
		]
	]
]
library('ForeCA')

args <- commandArgs(trailingOnly = TRUE)
arg_id <- args[1]
arg_dim <- as.numeric(args[2])

X <- read.csv(sprintf('foreca_node_train_%s.csv', arg_id), header=FALSE)
ff <- foreca(X, n.comp=arg_dim)
summary(ff)
print(ff$loadings)
W <- matrix(ff$loadings, ncol=arg_dim)

write.matrix(W, sprintf('foreca_node_result_%s.csv', arg_id))
#' Default theme for EnvReportBC graphs and plots
#'
#' 
#' 
#' @import ggplot2
#' @param  base_size base font size (default = 12)
#' @param  base_family base font family (default = Verdana)
#' @param  use_sizes use relative font sizes (?)
#' @param  facet facetting? (advise to not use directly, is set by \code{theme_soe_facet})
#' @export
#' @keywords plotting theme
#' @return returns a plot theme
#' @examples \dontrun{
#' 
#'}
theme_soe <- function(base_size=12, base_family="Verdana", use_sizes=TRUE, facet = FALSE) {
  thm <- theme_foundation_null(base_size = base_size, 
                               base_family = base_family) +
    theme(
      text = element_text(color="black"),
      axis.line = element_line(colour="black"),
      axis.text = element_text(color = 'black'),
      axis.text.y = element_text(hjust = 1),
      axis.ticks = element_blank(),
      plot.title = element_text(vjust=2),
      legend.title = element_text(face="plain"),
      panel.background = element_rect(fill="white"),
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "grey80",size=0.5),
      axis.title.y = element_text(vjust=1, angle = 90),
      axis.title.x = element_text(vjust=0),
      panel.margin.x = unit(0, "lines"),
      panel.margin.y = unit(0, "lines"),
      plot.background = element_blank(),
      panel.border = element_blank(),
      legend.key = element_blank())
  
  if (use_sizes) {
    thm <- thm + theme_foundation_sizes(facet = facet)
  }
  
  thm
}  

#' Soe plot theme for facetted graphs
#' 
#' @import ggplot2
#' @param  base_size base font size (default = 12)
#' @param  base_family base font family (default = Verdana)
#' @param  use_sizes use relative font sizes (?)
#' @export
#' @keywords plotting theme
#' @return a ggplot2 theme
#' @examples \dontrun{
#' 
#'}
theme_soe_facet <- function(base_size=12, base_family="Verdana", use_sizes=TRUE) {
  theme_soe(facet = TRUE) + 
    theme(
      panel.margin.x = unit(.6,"lines"),
      panel.margin.y = unit(.6,"lines"),
      panel.border = element_rect(colour = "black", fill = NA),
      strip.background = element_rect(colour = "black", fill = "grey85"))
}

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
    geneName = geneNames[i]
    geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]

    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient != 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneNames), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=10)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])


if("data.table" %in% rownames(installed.packages()) == FALSE) install.packages("data.table")
if("plyr" %in% rownames(installed.packages()) == FALSE) install.packages("plyr")
if("reshape2" %in% rownames(installed.packages()) == FALSE) install.packages("reshape2")
if("glmnet" %in% rownames(installed.packages()) == FALSE) install.packages("glmnet")
if("GenomicRanges" %in% rownames(installed.packages()) == FALSE) { source("http://bioconductor.org/biocLite.R"); biocLite("GenomicRanges"); }
if("preprocessCore" %in% rownames(installed.packages()) == FALSE) { source("http://bioconductor.org/biocLite.R"); biocLite("preprocessCore"); }


suppressMessages(require(data.table)    )
suppressMessages(require(plyr)          )
suppressMessages(require(reshape2)      )
suppressMessages(require(glmnet)        )
suppressMessages(require(preprocessCore))
suppressMessages(require(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient != 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneDataList), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=10)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA.bak <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

modelRNA <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id)]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}


# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient != 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

results = parallel::mclapply(1:length(geneDataList), function(xx){
    tryCatch({
      modelRNA(xx, geneNames, geneData2)
    }, error=function(e){
        print(e)
        print(xx)
    })
}, mc.cores=10)

args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA <- function(i, geneNames, geneDataAll)
{
	geneName = geneNames[i]
	geneData = geneDataAll[geneDataAll$gene == geneName, ]
    #geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),
						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

#geneData2 = read.tsv(outputSummaryFile)
geneNames = unique(geneData2$gene)
#geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneNames), modelRNA, geneNames, geneData2, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/test_data/bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=T)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)
write.tsv(rangesGenesEnh, "ranges_GenesAndProximalEnhancers.txt")

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){


    geneData = geneDataList[[i]]


    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene)[1],
						   variable=c("(Intercept)", colnames(covari)),

						   coefficient=rep.int(0, 1+ncol(covari)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) != 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)", colnames(covari)),

                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}
better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (length(unique(xx) == 1)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneDataList), modelRNA,  geneDataList, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





### Lastest load into a package.

.First.lib <- function(lib, pkg){
  if(! is.loaded("spmd_initialize", PACKAGE = "pbdMPI")){
    library.dynam("pbdMPI", "pbdMPI", lib)
    if(pbdMPI::comm.is.null(0L) == -1){
      pbdMPI::init()
    }
  }

  library.dynam("pbdADIOS", pkg, lib)
} # End of .First.lib().

.Last.lib <- function(libpath){
  pbdADIOS::adios.finalize(pbdMPI:::comm.rank())
  library.dynam.unload("pbdADIOS", libpath)
} # End of .Last.lib().
args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/final_dataset/final_bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		#file.remove(tempOut, showWarnings=F)
	}
	#file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=F)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
            if (length(enh.id) == 0){ covari <- cbind(covari, enh) }
		return(data.frame(gene=unique(geneData$gene),
                                  variable=c("(Intercept)",
                                      colnames(covari)),
                                  coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    tryCatch({
        step1 <- cv.glmnet(covari, rna, standardize=TRUE)
        s1.c <- predict(step1, type="coefficients", s="lambda.1se")
        rnames.s.c <- rownames(s1.c)
        c.s.c <- s1.c[,1]
        s1.fit <- predict(step1, newx=covari, s="lambda.1se")
        residual <- rna - s1.fit
        if (length(enh.id) != 0){
            step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
            s2.c <- predict(step2, type="coefficients", s="lambda.1se")
            rnames.s.c <- c(rnames.s.c, rownames(s2.c)[-1])
            c.s.c <- c(c.s.c, s2.c[-1,1])
        }
        coefs = data.frame(gene=unique(geneData$gene), variable=rnames.s.c, coefficient=c.s.c, row.names=NULL)
        return(coefs)
    }, error=function(e){
                if (length(enh.id) == 0){ covari <- cbind(covari, enh) }
	    	    return(data.frame(gene=unique(geneData$gene),
                                      variable=c("(Intercept)",
                                          colnames(covari)),
                                      coefficient=rep.int(0, ncol(covari)+1), row.names=NULL))
    })## end tryCatch
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == unique(xx))){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")

results = parallel::mclapply(1:length(geneDataList), modelRNA,  geneDataList, mc.cores=numCores)

results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/final_dataset/final_bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		#file.remove(tempOut, showWarnings=F)
	}
	#file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=F)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene),
                                  variable=c("(Intercept)",
                                      colnames(covari)),
                                  coefficient=rep.int(0, ncol(covari)+1+length(enh.id)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    s1.fit <- predict(step1, newx=covari, s="lambda.1se")
    residual <- rna - s1.fit
    step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
    s2.c <- predict(step2, type="coefficients", s="lambda.1se")
    coefs = data.frame(gene=unique(geneData$gene), variable=c(rownames(s1.c), rownames(s2.c)[-1]), coefficient=c(s1.c[,1],s2.c[-1,1]), row.names=NULL)
    return(coefs)
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")
results = parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)
results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





args = commandArgs(trailingOnly = TRUE)
if(length(args) < 3)
{
	cat("Usage: \nRscript featurizeModel.r geneRangeFile enhancerRangeFile inputBigWigFile [signalOutput] [coefficientOutput] [numCores] [maxDistanceFromEnhancer]\n\n")
	cat("Defaults:\nsignalOutput = ./outputSignal.txt\ncoefficientOutput = ./outputCoefficient.txt & ./outputCoefficient.txt.filtered \nnumCores = 8 \nmaxDistanceFromEnhancer = 100000\n")
	stop("Error: Need at least 3 inputs\n\n")
}
rangeGeneFile = args[1]
rangeEnhancerFile = args[2]
inputListFile = args[3]
outputSummaryFile = "outputSignal.txt"
outputCoefsFile = "outputCoefficient.txt"
numCores = 8
enhancerProximity = 1e+05

if(length(args) >= 4) outputSummaryFile = args[4]
if(length(args) >= 5) outputCoefsFile = args[5]
if(length(args) >= 6) numCores = as.integer(args[6])
if(length(args) >= 7) enhancerProximity = as.integer(args[7])

suppressMessages(library(data.table)    )
suppressMessages(library(plyr)          )
suppressMessages(library(reshape2)      )
suppressMessages(library(glmnet)        )
suppressMessages(library(preprocessCore))
suppressMessages(library(GenomicRanges) )



#rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
#rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
#inputListFile = "/epigenomes/teamdata/final_dataset/final_bigwig_files.txt"
#outputSummaryFile = "allBigWigFiles.txt"
#outputCoefsFile = "allBigWigFiles_coefs.txt"
#numCores = 10
#enhancerProximity = 1e+05





read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		#file.remove(tempOut, showWarnings=F)
	}
	#file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}



print("Reading inputs...")

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

## process gene ranges
inputList = read.tsv(inputListFile, header=F)
colnames(inputList) = c("Patient", "DataType", "DataFile", "Aggregation")
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

## process enhancer ranges
rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

## find enhancers within {enhancerProximity} distance to each gene
rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, ranges = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, ranges = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@ranges@start[overlapGeneEnh@queryHits], end=grEnhancer@ranges@start[overlapGeneEnh@queryHits]+grEnhancer@ranges@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

## Calculate the signal for the genic and enhancer regions

print("Calculating signal for the inputs...")

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputSummaryFile)


return (cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))

############------ Modeling Start ------############
modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    enh.id <- grep("enhancer", colnames(geneData))
    covari <- better.scale(as.matrix(geneData[,-c(metaData.id, rna.id, enh.id)]))
    enh <- better.scale(as.matrix(geneData[,enh.id]))
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0))
	{
		return(data.frame(gene=unique(geneData$gene),
                                  variable=c("(Intercept)",
                                      colnames(covari)),
                                  coefficient=rep.int(0, ncol(covari)+1+length(enh.id)), row.names=NULL))
	}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    s1.fit <- predict(step1, newx=covari, s="lambda.1se")
    residual <- rna - s1.fit
    step2 <- cv.glmnet(enh, residual, standardize=TRUE, intercept=FALSE)
    s2.c <- predict(step2, type="coefficients", s="lambda.1se")

    coefs <- c(unique(geneData$gene), unlist(s1.c[,1]), unlist(s2.c[-1,1]))
    return(coefs)
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputSummaryFile)
geneDataList = split(geneData2, f = geneData2$gene )

print("Building the model...")
results = parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)
results2 = rbindlist(results)
write.tsv(results2, outputCoefsFile)
results3 = results2[results2$variable != "(Intercept)" & results2$coefficient = 0, ]
write.tsv(results3, paste0(outputCoefsFile, ".filtered"))

print("Done!")

#res = rbindlist(parallel::mclapply(1:100, modelRNA, geneDataList, mc.cores=numCores))

# res = t(parallel::mclapply(500:600, function(ii){
# #    print(ii)
#     modelRNA(ii, geneDataList)
# }, mc.cores=4))
# 





require(ggplot2)

## README
# Change the following two paths to the input path of where ScalaMeter stored the *dsv result files...
inputPath <- "~/Dropbox/TUD/Thesis/code/join/tmp/"
# ... and where you would like the script to output the graphs:
outputPath <- "/Users/ayedo/Dropbox/TUD/Thesis/document/img/evaluation/"

# Drops columns which are not required
processed_import <- function(path, name) {
  dt <- read.csv(path, stringsAsFactors=FALSE)
  cropped <- subset(dt, select=-c(units, success))
  cropped$Approach = name
  return(cropped)
}

rxj <- processed_import(paste0(inputPath, "twoCasesIndependend.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "twoCasesIndependend.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "twoCasesIndependend.Deterministic Choice.dsv"), "DCT")

rxj <- rxj[1:4, ]
nct <- nct[1:4, ]
dct <- dct[1:4, ]

all = rbind(rxj, nct, dct)

# Rename the param.Observables column
names(all)[names(all)=="param.Observables"] <- "observables"
all$observables <- factor(all$observables)

# The number of events sent per observable
sentEvents = 32768

# 1. Two Cases Independent: twice number of events sent per observable. Constant.
patternMatches = 2 * sentEvents

valuet = as.numeric(lapply(all$value, function(x) patternMatches / (x / 1000)))
fprime = as.numeric(lapply(all$value, function(m) (-patternMatches * 1000) / (m ** 2)))
diff = all$cihi - all$value
variance = as.numeric(lapply(diff, function(d) (d / 6.361) ** 2))
variancet = variance * as.numeric(lapply(fprime, function(x) x ** 2))
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=observables, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Observables") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Compositions") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black")) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(file=paste0(outputPath, "TwoChoiceNObservables.eps"))

# 2. N Case Independent: number of events sent per observable * number of cases

rxj <- processed_import(paste0(inputPath, "NCaseTwoIndependent.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "NCaseTwoIndependent.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "NCaseTwoIndependent.Deterministic Choice.dsv"), "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = all$choices * sentEvents
all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Number of Choices") +
    theme_bw() + 
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0))  +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) +
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(paste0(outputPath, "NChoiceTwoObservables.eps"))

# 3. 16 Case N Dependent: 16 * number of events sent per observable
rxj <- processed_import(paste0(inputPath, "NDependentCases.ReactiveX.dsv"), "RXJ")
nct <- processed_import(paste0(inputPath, "NDependentCases.Non-Deterministic Choice.dsv"), "NCT")
dct <- processed_import(paste0(inputPath, "NDependentCases.Deterministic Choice.dsv"), "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = rep(16 * sentEvents, length(all$choices))

all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Interdependentness") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(paste0(outputPath, "32ChoiceNInterdependent.eps"))
require(ggplot2)

# Drops columns which are not required
processed_import <- function(path, name) {
  dt <- read.csv(path, stringsAsFactors=FALSE)
  cropped <- subset(dt, select=-c(units, success))
  cropped$Approach = name
  return(cropped)
}

rxj <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/twoCasesIndependend.ReactiveX.dsv", "RXJ")
nct <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/twoCasesIndependend.Non-Deterministic Choice.dsv", "NCT")
dct <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/twoCasesIndependend.Deterministic Choice.dsv", "DCT")

rxj <- rxj[1:4, ]
nct <- nct[1:4, ]
dct <- dct[1:4, ]

all = rbind(rxj, nct, dct)

# Rename the param.Observables column
names(all)[names(all)=="param.Observables"] <- "observables"
all$observables <- factor(all$observables)

# The number of events sent per observable
sentEvents = 32768

# 1. Two Cases Independent: twice number of events sent per observable. Constant.
patternMatches = 2 * sentEvents

valuet = as.numeric(lapply(all$value, function(x) patternMatches / (x / 1000)))
fprime = as.numeric(lapply(all$value, function(m) (-patternMatches * 1000) / (m ** 2)))
diff = all$cihi - all$value
variance = as.numeric(lapply(diff, function(d) (d / 6.361) ** 2))
variancet = variance * as.numeric(lapply(fprime, function(x) x ** 2))
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=observables, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Observables") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Compositions") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black")) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave(file="/Users/ayedo/Dropbox/TUD/Thesis/document/img/evaluation/TwoChoiceNObservables.eps")

# 2. N Case Independent: number of events sent per observable * number of cases

rxj <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/NCaseTwoIndependent.ReactiveX.dsv", "RXJ")
nct <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/NCaseTwoIndependent.Non-Deterministic Choice.dsv", "NCT")
dct <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/NCaseTwoIndependent.Deterministic Choice.dsv", "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = all$choices * sentEvents
all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Number of Choices") +
    theme_bw() + 
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0))  +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) +
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave("/Users/ayedo/Dropbox/TUD/Thesis/document/img/evaluation/NChoiceTwoObservables.eps")

# 3. 16 Case N Dependent: 16 * number of events sent per observable
rxj <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/NDependentCases.ReactiveX.dsv", "RXJ")
nct <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/NDependentCases.Non-Deterministic Choice.dsv", "NCT")
dct <- processed_import("~/Dropbox/TUD/Thesis/code/join/tmp/NDependentCases.Deterministic Choice.dsv", "DCT")

all = rbind(rxj, nct, dct)

names(all)[names(all)=="param.Choices"] <- "choices"

patternMatches = rep(16 * sentEvents, length(all$choices))

all$choices <- factor(all$choices)
valuet = patternMatches / (all$value / 1000)
fprime = (-patternMatches * 1000) / (all$value ** 2)
diff = all$cihi - all$value
variance = (diff / 6.361) ** 2
variancet = variance * (fprime ** 2)
all$value = valuet
all$cilo = valuet - 6.361 * sqrt(variancet)
all$cihi = valuet + 6.361 * sqrt(variancet)

rxjValues = all[which(all$Approach=='RXJ'), ]$value
nctValues = all[which(all$Approach=='NCT'), ]$value

1-mean(rxjValues / nctValues)

ggplot(all, aes(x=choices, y=value, fill=Approach)) + 
    geom_bar(position=position_dodge(), stat="identity",
            colour="black") +
    geom_errorbar(aes(ymin=cilo, ymax=cihi),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9)) +
    xlab("Choices") +
    ylab("Throughput (matches/s)") + 
    scale_fill_hue(name="Approach", # Legend label, use darker colors
                   breaks=c("DCT", "NCT", "RXJ"),
                   labels=c("Deterministic Choice Transform", 
                    "Non-Deterministic Choice Transform", 
                    "Reactive Extensions")) +
    ggtitle("Throughput with Increasing Size of Interdependentness") +
    theme_bw() +
    theme(plot.title = element_text(size=32, face="bold", vjust=2)) +
    theme(axis.title.y=element_text(face="bold", vjust=1)) + 
    theme(axis.title.x=element_text(face="bold", vjust=0)) +
    theme(legend.position="bottom",  panel.grid.major.x = element_blank() ,
           panel.grid.major.y = element_line( size=.1, color="black" )) + 
    scale_fill_manual(values=c("#CC6666", "#9999CC", "#66CC99"))
ggsave("/Users/ayedo/Dropbox/TUD/Thesis/document/img/evaluation/32ChoiceNInterdependent.eps")
##' Fetches the chromosomal locations for all genes and sorts them within each chromosome. 
##' @params tcgaResults the list with TCGA results
##' @params ccleResults the list with CCLE results
##' @return a data.frame with locations for all genes
##' @author Andreas Schlicker (a.schlicker@nki.nl)
sortGenesByLocation = function(tcgaResults, ccleResults) {
	# Genes in all cancer types
	genes = rownames(tcgaResults[[1]]$prioritize.combined)
	for (n in 2:length(tcgaResults)) {
		genes = intersect(genes, rownames(tcgaResults[[n]]$prioritize.combined))
	}
	for (n in 1:length(ccleResults)) {
		genes = intersect(genes, rownames(ccleResults[[n]]$prioritize.combined))
	}

	# Find all gene locations
	mart = useMart(host="ensembl.org", path="/biomart/martservice", biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
	geneLoc = getBM(attributes=c("hgnc_symbol", "chromosome_name", "start_position", "end_position", "strand", "band"), filters=c("hgnc_symbol"), values=genes, mart=mart)
	# Remove all non-standard chromosome names and make everything numeric
	geneLoc = geneLoc[which(geneLoc[, "chromosome_name"] %in% c("1", "2", "3", "4", "5", "6", "7", "8", 
																															"9", "10", "11", "12", "13", "14", "15", 
																															"16", "17", "18", "19", "20", "21", "22", 
																															"X", "Y")), ]
	geneLoc[which(geneLoc[, "chromosome_name"] == "X"), "chromosome_name"] = "23"
	geneLoc[which(geneLoc[, "chromosome_name"] == "Y"), "chromosome_name"] = "24"
	geneLoc[, "chromosome_name"] = as.integer(geneLoc[, "chromosome_name"])
	
	geneLoc[which(geneLoc[, "strand"] == 1), "strand"] = "+"
	geneLoc[which(geneLoc[, "strand"] == -1), "strand"] = "-"
	
	# Return the sorted gene information
	geneLoc[order(geneLoc$chromosome_name, geneLoc$start_position), ]
}


##' Generates a chromosome plot for the selected score or the number of affected samples.
##' @params geneLocs the data.frame returned by sortGenesByLocation()
##' @params results either tcgaResults or ccleResults
##' @params cancType the selected four letter cancer code
##' @params chrom the selected chromosome; X is coded as 23 and Y as 24
##' @params scoreType which score was selected; one of "OG", "TS", "CO"
##' @return a list with two plotting objects, "score" the actual score and "affected" the percentage of affected samples
##' @author Andreas Schlicker (a.schlicker@nki.nl) 
getScorePlot = function(geneLocs, results, cancType, chrom, scoreType) {
	scoreType = match.arg(scoreType, c("TS", "OG" "CO"))
	
	# Get the genes for the selected chromosome
	genes = subset(geneLocs, chromosome_name==chrom)
	
	# Get the score vector
	score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "og.score"]
  # And the percentage of affected samples
	affected = results[[canc]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"]
	if (scoreType == "TS") {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.score"] * -1
		affected = results[[canc]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	} else {
		score = results[[cancType]]$prioritize.combined[genes[, "hgnc_symbol"], "combined.score"]
		affected = results[[canc]]$prioritize.combined[genes[, "hgnc_symbol"], "og.affected.rel"] - 
							 results[[canc]]$prioritize.combined[genes[, "hgnc_symbol"], "ts.affected.rel"]
	}
	
	# Get two tracks, one for scores and the other one for percent affected samples 
	tracks = list(DataTrack(GRanges(seqnames=as.character(chrom),
																	ranges=IRanges(start=genes[, "start_position"],
																								 end=genes[, "end_position"]),
																	score,
																	strand="*"),
																	name="", 
																	background.title="white",
																	background.panel="white"),
			
								DataTrack(GRanges(seqnames=as.character(chrom),
																	ranges=IRanges(start=genes[, "start_position"],
																								 end=genes[, "end_position"]),
																	affected,
																	strand="*"),
																	name="",
																	background.title="white",
																	background.panel="white"))
			
	list(score=plotTracks(tracks[1], type=c("h", "g"),
						 ylim=c(min(unlist(lapply(tracks, function(x) { min(x@data) }))), 
										max(unlist(lapply(tracks, function(x) { max(x@data) })))),
						 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
						 main=""),
			 affected=plotTracks(tracks[2], type=c("h", "g"),
						 ylim=c(min(unlist(lapply(tracks, function(x) { min(x@data) }))), 
										max(unlist(lapply(tracks, function(x) { max(x@data) })))),
						 col.title="black", col.axis="black", cex.axis=0.75, fontface="bold", 
						 main=""))
}

library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)
library(GenomicRanges)

rangeGeneFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData3.txt"
numCores = 10
enhancerProximity = 1e+05


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}

############------ Featurization Start ------############

## GetRegionSignal: Summarizes a list of signal for a list of given intervals
## Input: 
## ranges = data.frame, giving the regions the signals will be summarized over (gene bodies, introns, enhancers...). MUST contain the fields chr/start/end and a unique field named id
## inputList = data.frame, list of *bigWig* files that contains the signal (histone peaks, TFBS, DNA methylation, RNAseq). 
##            	Row format is of (Patient, DataType, DataFile, Aggregation) where each field is as described below. Each unique patient MUST contain a row with DataType of "RNA".
##					Patient: A patient id
##					DataType: A text describing the signal. 
##					DataFile: Path to the bigWig file
##					Aggregation: how to summarize the data over the peak. can take values (mean, min, max, sum, mean0). mean will give the mean value in only the covered bases whereas mean0 will average over zeroes as well
## Output: data.frame containing tuples of (gene, region, patient, DataType, Summarized value)
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeGeneFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
rangesGene = read.tsv(rangeGeneFile, header=F)
colnames(rangesGene) = c("id","gene","region","chr","start","end")
rangesGene$id = paste(rangesGene$chr, rangesGene$start, rangesGene$end, sep=".")

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")
rangesEnhancers$region = paste0("enhancer.", rangesEnhancers$id)

rangesGenebody = unique(rangesGene[rangesGene$region == "body",c("gene","chr","start","end")])
grGeneFlanking = GRanges(seqnames=rangesGenebody$chr, rangesGene = IRanges(start=rangesGenebody$start-enhancerProximity, end=rangesGenebody$end+enhancerProximity), gene=rangesGenebody$gene)
grEnhancer = GRanges(seqnames=rangesEnhancers$chr, rangesGene = IRanges(start=rangesEnhancers$start, end=rangesEnhancers$end), id=rangesEnhancers$id, region=rangesEnhancers$region)
overlapGeneEnh = findOverlaps(grEnhancer, grGeneFlanking)
overlapGeneEnh2 = data.frame(id=grEnhancer$id[overlapGeneEnh@queryHits], gene=grGeneFlanking$gene[ overlapGeneEnh@subjectHits], region=grEnhancer$region[overlapGeneEnh@queryHits], chr=grEnhancer@seqnames[overlapGeneEnh@queryHits], start=grEnhancer@rangesGene@start[overlapGeneEnh@queryHits], end=grEnhancer@rangesGene@start[overlapGeneEnh@queryHits]+grEnhancer@rangesGene@width[overlapGeneEnh@queryHits]-1)

rangesGenesEnh = rbind(rangesGene, overlapGeneEnh2)

summaryData = GetRegionSignal(rangesGenesEnh, inputList)
geneData = merge(rangesGenesEnh, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]

write.tsv(geneData2, outputFile)




############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
    colnames(rnaData)[3] = "RNA"
    geneData = geneData[geneData$variable != "RNA", ]
    geneData = dcast(geneData, gene+patient~region+variable, fun.aggregate=mean)
    geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    if (all(rna == 0)){return(cbind(unique(geneData$gene), rep.int(0, ncol(covari)+1)))}
    rna <- log2((rna+0.5)/sum(rna+1)*1e6)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    coefs = data.frame(gene=unique(geneData$gene), variable=rownames(s1.c), coefficient=s1.c[,1], row.names=NULL)
	return(coefs)
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))

res = t(parallel::mclapply(500:600, function(ii){
#    print(ii)
    modelRNA(ii, geneDataList)
}, mc.cores=4))






library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData2.txt"
numCores = 10


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]
#geneData3 = dcast(geneData2, id+gene+patient~regionvariable)
write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
	rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
	colnames(rnaData)[3] = "RNA"
	geneData = geneData[geneData$variable != "RNA", ]
	geneData = dcast(geneData, gene+patient~region+variable)
	geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 4


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(1:4, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData2.txt"
numCores = 10


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:3,7:ncol(geneData))]
geneData2 = melt(geneData2, c("id", "gene", "region", "patient"))
geneData2 = geneData2[ ! (geneData2$variable == "RNA" & geneData2$region != "body"), ]
#geneData3 = dcast(geneData2, id+gene+patient~regionvariable)
write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
	rnaData = geneData[ geneData$variable=="RNA", c("gene","patient","value")]
	colnames(rnaData)[3] = "RNA"
	geneData = geneData[geneData$variable != "RNA", ]
	geneData = dcast(geneData, gene+patient~region+variable)
	geneData = merge(rnaData, geneData, by=c("gene","patient"))
	
	
    metaData.id <- grep("gene|patient", colnames(geneData))
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(metaData.id, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 4


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(1:4, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 4


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############

modelRNA <- function(i, geneDataList){
    geneData = geneDataList[[i]]
    rna.id <- which(colnames(geneData) == "RNA")
    covari <- as.matrix(geneData[,-c(1:4, rna.id)])
    rna <- as.matrix(geneData[,rna.id])
    rna <- log2(rna/sum(rna) + 0.5)
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(cbind(unique(geneData$gene), s1.c[,1]))
}

# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





library(data.table)
library(plyr)
library(reshape2)
library(glmnet)
library(preprocessCore)

rangeFile = "/epigenomes/teamdata/regions_typed.tab"
rangeEnhancerFile = "/epigenomes/teamdata/sandelin_enh_expanded.bed"
inputListFile = "/home/cemmeydan/inputTest3.txt"
outputFile = "/epigenomes/teamdata/H1_dummyData.txt"
numCores = 10


read.tsv = function(file, sep="\t", header=T)
{
	return(read.table(file, sep=sep, header=header, stringsAsFactors=F,  na.strings = c("NA","#N/A","N/A")))
}

write.tsv = function(object, file, sep="\t", header=T)
{
	write.table(object, file, sep=sep, col.names=header, quote=F, row.names=F)
}


############------ Featurization Start ------############

## Summarizes a list of signal from a list of files
## Input: 
GetRegionSignal = function(ranges, inputList)
{
	rangesUniq = unique(data.frame(ranges[,c("chr","start","end","id")]))
	write.tsv(rangesUniq, rangeFileTmpOut, header=F)

	summaryData = data.frame()
	for(i in 1:nrow(inputList))
	{
		inputRow = inputList[i,]
		inFile = inputRow$DataFile
		tempOut = paste0( basename(inFile), ".summary.bed")
		command = paste0("/home/cemmeydan/bigWigAverageOverBed ", inFile, " ", rangeFileTmpOut, " ", tempOut, " -minMax")
		system(command)
		curSummary = read.table(tempOut, sep="\t", header=F, stringsAsFactors=F)
		colnames(curSummary) = c("id","size","covered","sum","mean0","mean","min","max")
		curSummary$patient = inputRow$Patient
			
		if( ! inputRow$Aggregation %in% c("min","max","mean","mean0","sum")) inputRow$Aggregation = "mean"
									   
		curSummary = curSummary[, c("id","patient",inputRow$Aggregation)]
		colnames(curSummary)[3] = inputRow$DataType
		curSummary = melt(curSummary, c("id","patient"))
		
		summaryData = rbind(summaryData, curSummary)
		file.remove(tempOut, showWarnings=F)
	}
	file.remove(rangeFileTmpOut, showWarnings=F)
	summaryData2 = dcast(summaryData, id+patient ~ variable, fun.aggregate=mean) ## If everything is correct we shouldn't need fun.aggregate now
	return(summaryData2)
}

rangeFileTmpOut = paste0(basename(rangeFile), ".uniq.bed")

inputList = read.tsv(inputListFile)
ranges = read.tsv(rangeFile, header=F)
colnames(ranges) = c("id","gene","region","chr","start","end")
ranges$id = paste(ranges$chr, ranges$start, ranges$end, sep=".")

###
#ranges = ranges[1:600,]

rangesEnhancers = read.tsv(rangeEnhancerFile, header=T, sep=" ")
rangesEnhancers = rangesEnhancers[,1:3]
rownames(rangesEnhancers) = NULL
colnames(rangesEnhancers) = c("chr","start","end")
rangesEnhancers$id = paste(rangesEnhancers$chr, rangesEnhancers$start, rangesEnhancers$end, sep=".")

summaryData = GetRegionSignal(ranges, inputList)
#summaryDataEnh = GetRegionSignal(rangesEnhancers, inputList)

geneData = merge(ranges, summaryData, by="id")
geneData2 = geneData[,c(1:2,6:ncol(geneData))]

write.tsv(geneData2, outputFile)

############------ Modeling Start ------############


modelRNA = function(i, geneDataList, rna)
{
    geneData = geneDataList[[i]]
    geneData = dcast(data = geneData, formula = gene + patient ~ id + variable)
    covari <- as.matrix(geneData[,-c(1:3)])
    # first local cpg model
    step1 <- cv.glmnet(covari, rna, standardize=TRUE)
    s1.c <- predict(step1, type="coefficients", s="lambda.1se")
    return(s1.c)
}



# possible normalization strategy for at least histones
aqn <- function(dF)
{
    cn <- colnames(dF)
    rn <- rownames(dF)
    varstab <- cbind(apply(dF, 2, asinh))
    dF.scale <- normalize.quantile(varstab)
    colnames(dF.scale) <- cn
    rownames(dF.scale) <- rn
    dF.scale
}

better.scale <- function(mat)
{
    nmat <- apply(mat, 2, function(xx){
        if (all(xx == 0)){ return(xx) }
        else{ return(scale(xx)) } })
    return(nmat)
}

geneData2 = read.tsv(outputFile)
geneDataList = split(geneData2, f = geneData2$gene )

#res = t(simplify2array(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList, mc.cores=numCores)))
res = t(parallel::mclapply(1:length(geneDataList), modelRNA, geneDataList,  mc.cores=4))





##' Filtering of result frame according to user criteria
##' @param results data.frame with all results
##' @param scoreCutoff threshold that was selected by the user
##' @param cancerType cancer type selected by the user
##' @return a subset of the data.frame that fits the user's selection
##' @author Andreas Schlicker
page1DataFrame = function(results, scoreCutoff, cancerType) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == "combined" & score >= as.integer(scoreCutoff))$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	# gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order = subset(results, score.type=="combined" & gene %in% genes)
  gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	result.df
}

##' Get the heatmap for view 1 of page 1.
##' @params results a subsetted data.frame as returned by page1DataFrame()
##' @params colorLow "#034b87" if selected score was TS or combined, else "gray98"
##' @params colorHigh "#880000" if selected score was OG or combined, else "gray98"
##' @return the heatmap object
##' @author Andreas Schlicker
plotHeatmapPage1 = function(results, scoreType=c("combined.score", "ts.score", "og.score")) {
	result.df = results
	colorLow = list(combined.score="#034b87", ts.score="#034b87", og.score="gray98") 
	colorMid = list(combined.score="gray98")#,
	colorHigh = list(combined.score="#880000", ts.score="gray98", og.score="#880000")

	getHeatmap(dataFrame=result.df, yaxis.theme=theme(axis.text.y=element_blank()), 
	   	   color.low=colorLow[[scoreType]], color.mid=colorMid[[scoreType]], color.high=colorHigh[[scoreType]])
}

##' Plots view 2 of page 1
##' @param results a subsetted data.frame as returned by page1DataFrame()
##' @return the ggplot2 object with the plot for view 2 of page 1
##' @author Andreas Schlicker
plotCategoryOverview = function(results) {
	result.df = results
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	#ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	ggplot(subset(result.df, score.type != "combined"), aes(x=score.type, y=gene)) + 
  geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=16, face="bold"),
	      axis.title.x=element_text(color="gray30", size=16, face="bold"),
	      strip.text.x=element_text(color="gray30", size=16, face="bold"),
	      legend.text=element_text(color="gray30", size=16, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	#)
}

##' main call to comp1 plots
##' view 1
comp1view1Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotHeatmapPage1(resultsSub, score)
    }
  }
}
##' view 2
comp1view2Plot = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)     
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)     
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer)      
      ## call plot function
      plotCategoryOverview(resultsSub)
    }
  }
}

##' main call to page1 gene data frame
geneDataFrameResultSet = function(cutoff,cancer,score,sample){
  if (sample == 'tumors'){
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapOG, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapTS, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(tcgaResultsHeatmapCombined, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }
  }else{
    if(score == 'og.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapOG, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else if(score == 'ts.score'){
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapTS, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }else{
      ## subset data frame based on user input
      resultsSub <- page1DataFrame(ccleResultsHeatmapCombined, cutoff, cancer)
      gc <- paste('<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=',resultsSub$gene,'">','Gene Card','</a>',sep='')
      dfgenes <- data.frame(resultsSub$gene,gc)
      colnames(dfgenes) <- c("Genes","External links")
      dfgenes
    }
  }
}
## see: http://stackoverflow.com/questions/9298765/print-latex-table-directly-to-an-image-png-or-other
## also maybe useful: http://tex.stackexchange.com/questions/11866/compile-a-latex-document-into-a-png-image-thats-as-short-as-possible
make.png <- function(obj, resolution=NULL) {
  name <- tempfile('x')
  texFile <- paste(name,".tex",sep="")
  pngFile <- paste(name,".png",sep="")
  sink(file=texFile)
  cat('
      \\documentclass[12pt]{report}
      \\usepackage[paperwidth=11in,paperheight=8in,noheadfoot,margin=0in]{geometry}
      \\usepackage[T1]{fontenc}
      \\usepackage{booktabs}
      \\begin{document}\\pagestyle{empty}
      {\\Large
      ')
  save <- booktabs(); on.exit(table_options(save))
  latex(obj)
  table_options(save)
  cat('
      }\\end{document}
      ')
  sink()
  wd <- setwd(tempdir()); on.exit(setwd(wd))
  texi2dvi(file=texFile, index=FALSE)

  cmd <- paste("dvipng -T tight -o",
               shQuote(pngFile),
               if(!is.null(resolution)) paste("-D",resolution) else "",
               shQuote(paste(name,".dvi",sep="")))
  invisible(sys(cmd))
  cleaner <- c(".tex",".aux",".log",".dvi")
  invisible(file.remove(paste(name,cleaner,sep="")))
  pngFile
}

newGuid <- function(){
  gsub("-", "_", UUIDgenerate(), fixed=TRUE)

  #paste(sample(c(letters[1:6],0:9),30,replace=TRUE),collapse="")
}

## preserve names of x
setdiff.c <<- function(x, y){
  z <- setdiff(x, y)
  x1 <- names(x)
  if(!is.null(x1)){
    names(x1) <- x
    names(z) <- x1[z]
    z
  } else z
}
isEmpty <<- function(x){
  is.null(x) || length(x)==0 || all(is.na(x)) || all(x=='')
}

ifnull <- function(x, d){
  if(is.null(x)) d else x
}
ifempty <- function(x, d){
  if(isEmpty(x)) d else x
}

null2String <- function(x){
  ifnull(x,"")
}
empty2NULL <- function(x){
  ifempty(x,NULL)
}

getDefaultMeasures <- function(dat){
  names(dat)[sapply(dat, function(x) typeof(x)=="double")]
}

getDefaultFieldsList <- function(dat){
  x <- lapply(names(dat), function(n) reactiveValues('name'=n, 'type'=typeof(dat[[n]])))
  names(x) <- names(dat)
  x
}

convertSheetNameToDatName <- function(sheetName){
  paste(sheetName, '(Aggregated Data)', sep=' ')
}

names2formula <- function(nms){
  if(!isEmpty(nms)){
    paste(nms, collapse=" + ")
  } else " . "
}

isFieldUninitialized <- function(obj, field){
  class(obj[[field]])=="uninitializedField"
}

are.vectors.different <- function(x, y){
  if(isEmpty(x)){
    !isEmpty(y)
  } else {
    isEmpty(y) || any(x!=y)
  }
}

## convert d so that the specified columns of d are measures and the rest are dims
## measures: can be either logical or charecter vector
forceMeasures <<- function(d, measures){
  if(!is.logical(measures)) measures <- names(d) %in% measures
  for(n in seq_along(measures)){
    if(measures[n]){
      if(!is.numeric(d[[n]])) d[[n]] <- as.numeric(d[[n]])
    } else {
      if(!is.factor(d[[n]])) d[[n]] <- as.factor(d[[n]])
    }
  }
  d
}

## list with reference semantics
## for later use (challenge: how to delete a field dynamically similarly to deleting a list item by setting it to NULL)
refList <- setRefClass("refList")
names.refList <- function(x) ls(x)[-1] # get rid of "getClass"

DatClass <- setRefClass("DatClass", fields=c("staticProperties","dynamicProperties","datR","fieldNames","moltenDat","moltenNames"),
                        methods=list(setDatDependencies=function(){
                          fieldNames <<- reactive({
                            if(length(dynamicProperties[['fieldsList']])){
                              x <- names(dynamicProperties[['fieldsList']])
                              names(x) <- make.unique(sapply(dynamicProperties[['fieldsList']],
                                                             function(y) y[['name']]), sep='_')
                              x
                            } else c()
                          })
                          datR <<- reactive({
                            if(is.null(dynamicProperties[['dat']])){
                              ## fetch from database etc.

                            } else {
                              dat <- forceMeasures(dynamicProperties[['dat']],
                                             dynamicProperties[['measures']])
                              label(dat, self=FALSE) <- names(fieldNames())
                              dat
                            }
                          })

                          measureName <- 'MeasureNames'
                          moltenDat <<- reactive({
                            if(!isEmpty(dynamicProperties[['measures']])){
                              melt(datR(), measure.vars=dynamicProperties[['measures']],
                                   variable_name=measureName)
                            }
                          })
                          moltenNames <<- reactive({
                            x <- setdiff.c(fieldNames(), dynamicProperties[['measures']])
                            x[measureName] <- measureName
                            x['MeasureValues'] <- MoltenMeasuresName
                            x
                          })
                        },
                        removeDatDependencies=function(){
                          datR <<- NULL; fieldNames <<- NULL; moltenDat <<- NULL; moltenNames <<- NULL
                        }))

createNewDatClassObj <- function(dat=NULL, name='Data', nameOriginal=NULL, type='file'){
  x <- DatClass$new('staticProperties'=list('type'=type, 'nameOriginal'=nameOriginal))
  if(is.null(dat)){
    x[['dynamicProperties']] <- reactiveValues('fieldsList'=list())
  } else {
    activeField <- if(length(names(dat))) names(dat)[1] else ''
    x[['dynamicProperties']] <- reactiveValues('dat'=dat, 'name'=name,
                                               'fieldsList'=getDefaultFieldsList(dat),
                                               'activeField'=activeField,
                                               'measures'=getDefaultMeasures(dat))
  }
  x$setDatDependencies()
  x
}


SheetClass <- setRefClass("SheetClass",
                          fields=c("dynamicProperties","datR",
                                   "fieldNames","measuresR","plotCore","plotR",
                                   "tableR","layerNames"))
createNewLayer <- function(){
  reactiveValues('geom'='point', 'statType'='identity', 'yFun'='sum', 'layerPositionType'='identity',
                 'activeAes'='aesX',
                 'aesList'=sapply(AesChoicesSimpleList,
                                  function(x) reactiveValues('aesAggregate'=FALSE,'aesDiscrete'=TRUE,'aesMapOrSet'='map'), simplify=FALSE))
}
createNewSheetObj <- function(name='Sheet'){
  SheetClass$new(
    'dynamicProperties'=reactiveValues(
      'name'=name,
      'datId'='', 'combineMeasures'=FALSE, 'outputType'='plot',
      'columns'='', 'colChoices'='',
      'rows'='', 'rowChoices'='',
      'outputTable'=NULL,
      'outputDataframe'=NULL,
      'layerList'=list(
        'Plot'=createNewLayer()),
      'activeLayer'='Plot'))
}



require(stringr)

#Rotor 1
I     <- list("EKMFLGDQVZNTOWYHXUSPAIBRCJ","Q")
names(I) <- c("Enc","Step")

#Rotor 2
II    <- list("AJDKSIRUXBLHWTMCQGZNPYFVOE","E")
names(II) <- c("Enc","Step")

#Rotor 3
III   <- list("BDFHJLCPRTXVZNYEIWGAKMUSQO","V")
names(III) <- c("Enc","Step")

#Rotor 4
IV    <- list("ESOVPZJAYQUIRHXLNFTGKDCMWB","J")
names(IV) <- c("Enc","Step")

#Rotor 5
V     <- list("VZBRGITYUPSDNHLXAWMJQOFECK","Z")
names(V) <- c("Enc","Step")

#Rotor 6
VI    <- list("JPGVOUMFYQBENHZRDKASXLICTW",c("Z","M"))
names(V) <- c("Enc","Step")

#Rotor 7
VII   <- list("NZJHGRCXMYSWBOUFAIVLPEKQDT",c("Z","M"))
names(VII) <- c("Enc","Step")

#Rotor 8
VIII  <- list("FKQHTLXOCBJSPDZRAMEWNIUYGV",c("Z","M"))
names(VIII) <- c("Enc","Step")

#Rotor Beta
Beta  <- list("LEYJVCNIXWPBQMDRTAKZGFUHOS",NULL)
names(Beta) <- c("Enc","Step")

#Rotor Gamma
Gamma <- list("FSOKANUERHMBTIYCWLQPZXVGJD",NULL)
names(Gamma) <- c("Enc","Step")

RefB  <- "YRUHQSLDPXNGOKMIEBFZCWVJAT"
RefC  <- "FVPJIAOYEDRZXWGCTKUQSBNMHL"

RefBt <- "ENKQAUYWJICOPBLMDXZVFTHRGS"
RefCt <- "RDOBJNTKVEHMLFCWZAXGYIPSUQ"

C26 <- function(x){
  if(x < 1) x <- 26 + x
  if(x >26) x <- x - 26
  return(x)
}

Enigma <- function(Rotors = list(III,II,I), RingSetting = c(1,1,1),Reflector = RefB, Text = "HENK"){
  
  Rotor1 <- strsplit(Rotors[[length(Rotors)]]$Enc, "")[[1]]
  Rotor1 <- cbind(Rotor1,LETTERS)
  Rotor1T<- Rotors[[length(Rotors)]]$Step
  
  Rotor2 <- strsplit(Rotors[[length(Rotors) - 1]]$Enc, "")[[1]]
  Rotor2 <- cbind(Rotor2,LETTERS)
  Rotor2T<- Rotors[[length(Rotors) - 1]]$Step
  
  Rotor3 <- strsplit(Rotors[[length(Rotors) - 2]]$Enc, "")[[1]]
  Rotor3 <- cbind(Rotor3,LETTERS)
  Rotor3T<- Rotors[[length(Rotors) - 2]]$Step
  
  
  if(length(Rotors) == 4){
    Rotor4 <- strsplit(Rotors[length(Rotors) - 3]$Enc, "")[[1]]
    Rotor4 <- cbind(Rotor4,LETTERS)
  }
  
  RingSetting1 <- RingSetting[length(RingSetting)]
  RingSetting2 <- RingSetting[length(RingSetting)-1]
  RingSetting3 <- RingSetting[length(RingSetting)-2]
  if(length(RingSetting) == 4) RingSetting4 <- RingSetting[length(RingSetting)-3]
  
  Reflec <- strsplit(Reflector, "")[[1]]
  Reflec <- cbind(Reflec,LETTERS)
  
  TextIn <- strsplit(Text, "")[[1]]
  
  for(i in 1:length(TextIn)){
    
    RingSetting1 <- C26(RingSetting1 + 1)
    
    if(any(LETTERS[C26(RingSetting1 - 1)] == Rotor1T)) RingSetting2 <- C26(RingSetting2 + 1)
    
    if(any(LETTERS[C26(RingSetting1 - 2)] == Rotor1T) & 
         any(LETTERS[C26(RingSetting2)] == Rotor2T)){
      RingSetting3 <- C26(RingSetting3 + 1)
      RingSetting2 <- C26(RingSetting2 + 1)
    }	
    
    if(length(RingSetting) == 4) c(RingSetting4,RingSetting3,RingSetting2,RingSetting1)
    if(length(RingSetting) == 3) c(RingSetting3,RingSetting2,RingSetting1)
    
    inpL <- TextIn[i]
    
    inp1 <- C26(which(LETTERS == inpL) + (RingSetting1 - 1))
    out1 <- Rotor1[Rotor1[,2] == LETTERS[inp1], 1]
    out1 <- C26(which(LETTERS == out1) - (RingSetting1 - 1))
    
    inp2 <- LETTERS[C26(out1 + (RingSetting2 - 1))]
    out2 <- Rotor2[Rotor2[,2] == inp2, 1]
    out2 <- C26(which(LETTERS == out2) - (RingSetting2 - 1))
    
    inp3 <- LETTERS[C26(out2 + (RingSetting3 - 1))]
    out3 <- Rotor3[Rotor3[,2] == inp3, 1]
    out3 <- C26(which(LETTERS == out3) - (RingSetting3 - 1))
    
    if(length(RingSetting) == 4){
    inp4 <- LETTERS[C26(out3 + (RingSetting4 - 1))]
    out4 <- Rotor4[Rotor4[,2] == inp4, 1]
    out4 <- C26(which(LETTERS == out4) - (RingSetting4 - 1))
    
    outR <- Reflec[Reflec[,2] == LETTERS[out4], 1]
    outR <- which(LETTERS == outR)
    
    inp4 <- LETTERS[C26(outR + (RingSetting4 - 1))]
    out4 <- Rotor4[Rotor4[,1] == inp4, 2]
    outR <- C26(which(LETTERS == out4) - (RingSetting4 - 1))
    } else {
    outR <- Reflec[Reflec[,2] == LETTERS[out3], 1]
    outR <- which(LETTERS == outR)
    }
    
    inp3 <- LETTERS[C26(outR + (RingSetting3 - 1))]
    out3 <- Rotor3[Rotor3[,1] == inp3, 2]
    out3 <- C26(which(LETTERS == out3) - (RingSetting3 - 1))
    
    inp2 <- LETTERS[C26(out3 + (RingSetting2 - 1))]
    out2 <- Rotor2[Rotor2[,1] == inp2, 2]
    out2 <- C26(which(LETTERS == out2) - (RingSetting2 - 1))
    
    inp1 <- LETTERS[C26(out2 + (RingSetting1 - 1))]
    out1 <- Rotor1[Rotor1[,1] == inp1, 2]
    out1 <- C26(which(LETTERS == out1) - (RingSetting1 - 1))
    outL <- LETTERS[out1]
 
    if(length(RingSetting) == 4) c(RingSetting4,RingSetting3,RingSetting2,RingSetting1)
    if(length(RingSetting) == 3) c(RingSetting3,RingSetting2,RingSetting1)   
  
    print(outL)
  }
}

setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args, list(...))
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args, args = list()) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        list(value = do.call(base::source, source_args)$value,
             preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$args            <- args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
library(pbdMPI, quiet = TRUE)
library(pbdDMAT, quiet = TRUE)
library(pbdADIOS, quiet = TRUE)
library(raster, quiet=TRUE)
library(ggplot2, quiet=TRUE)
library(grid, quiet=TRUE)

## begin function definitions

raster_plot <- function(x, nrow, ncol, basename="raster", sequence=1, swidth=3)
{
    x <- data.frame(rasterToPoints(raster(matrix(x, nrow, ncol),
                                          xmn=0, xmx=ncol, ymn=0, ymx=nrow)))
    names(x) <- c("x", "y", basename)
    png(paste(basename, "_", formatC(sequence, width=swidth, flag=0), "_",
              comm.rank(), ".png", sep=""))
    print(ggplot(x, aes_string(x="x", y="y", fill=basename)) + geom_raster() +
          theme_minimal() + theme(axis.text.x=element_blank(),
                                  axis.ticks.x=element_blank(),
                                  axis.title.x=element_blank(),
                                  legend.position="none",
                                  plot.margin=unit(c(0,0,0,0),"cm")
                                  )
          )
    dev.off()
}
## end function definitions


## Initialize MPI and ADIOS 

init.grid() ## MPI/DMAT intializer
adios.init.noxml() ## Write without using XML ## WR
adios.read.init.method("ADIOS_READ_METHOD_BP", params="verbose=3") ## Initialize reading method

adios.allocate.buffer(300) ## allocating size for ADIOS application in MB ## WR

groupname <- "restart" ## WR
adios_group_ptr <-  adios.declare.group(groupname,"") ## WR

adios.select.method(adios_group_ptr, "MPI", "", "") ## WR
filename <- "/Users/pragnesh/5.1.1/SGN_pbdADIOS/SGN_23_dec/pbdADIOS/demo/test_heat_w.bp" ## WR


## specify and open file for reading
dir.data <- "/Users/pragnesh/5.1.1/SGN_pbdADIOS/dataset" 
file <- paste(dir.data, "heat.bp", sep="/")

timeout.read <- 1 ## in sec
read.file.ptr <- adios.read.open(file, adios.timeout=timeout.read, "ADIOS_READ_METHOD_BP",
                          adios.lockmode="ADIOS_LOCKMODE_NONE") ## Calling adios read function

## select variable to read
variable <- "T"

## get variable dimensions
varinfo = adios.inq.var(read.file.ptr, variable)
block <- adios.inq.var.blockinfo(read.file.ptr, varinfo)

#comm.print("Before custom.inq.var.ndim")


ndim <- custom.inq.var.ndim(varinfo)
dims <- custom.inq.var.dims(varinfo)

## get dimensions and split
#source("pbdADIOS/tests/partition.r")
source("/Users/pragnesh/5.1.1/SGN_pbdADIOS/SGN_23_dec/pbdADIOS/demo/partition.r")

g.dim <- dims # global.dim on write
split <- c(TRUE, FALSE)
my.data.partition <- data.partition(seq(0, 0, along.with=g.dim), g.dim, split)
my.dim <- my.count <- my.data.partition$my.dim # local.dim on write
my.start <- my.data.partition$my.start # local.offset on write
my.grid <- my.data.partition$my.grid

adios.define.var(adios_group_ptr, "T", "", toString(my.dim), toString(g.dim), toString(my.start))  ## WR

errno <- 0 # Default value 0
steps <- 0
retval <- 0
bufsize <- 10
buffer <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a0 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a1 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a2 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
rhs <- cbind(rep(1, bufsize), poly(1:bufsize, degree=2))

while(errno != -21) { ## This is hard-coded for now. -21=err_end_of_stream
    steps = steps + 1 ## Double check with Norbert. Should it start with 1 or 2

    ## set reading bounding box
    adios.selection  <- adios.selection.boundingbox(ndim, my.start, my.count)
    comm.print("Selection.boundingbox complete ...")
    
    ## schedule the read
    adios.data <- adios.schedule.read(varinfo, my.start, my.count, read.file.ptr,
                                      adios.selection, variable, 0, 1)
    comm.print("Schedule read complete ...")
    
    ## perform the read
    adios.perform.reads(read.file.ptr, 1)
    comm.print("Perform read complete ...")

    data_chunk <- custom.data.access(adios.data, adios.selection, varinfo)
    comm.print("Data access complete ...")

    ## print a few to verify
    comm.cat("first 5:", head(data_chunk, 5),"\n")
    comm.cat("last 5:", tail(data_chunk, 5),"\n")

    ## shape into matrix with first dim as rows
    ## local reshape dimensions
    my.ncol <- prod(my.dim[2])
    my.nrow <- my.dim[1]
    ldim <- c(my.nrow, my.ncol)

    ## global reshape dimensions
    g.ncol <- prod(g.dim[2])
    g.nrow <- g.dim[1]
    gdim <- c(g.nrow, g.ncol)
    
    ## now glue into a ddmatrix
    ##  x <- matrix(data_chunk, nrow=my.nrow, ncol=my.ncol, byrow=FALSE)
    ##  X <- new("ddmatrix", Data=x, dim=gdim, ldim=ldim, bldim=ldim, ICTXT=2)

    ## Fit a quadratic to a moving window of 10 steps
    ## Actually don't need the ddmatrix for this and can go straight
    ## from data_chunk into buffer matrix
    buffer <- rbind(buffer[-1, ], data_chunk)

    ## plot the original local matrix (swapping row to col - C to R)
    raster_plot(data_chunk, my.ncol, my.nrow, "T", steps)
    
    ## fit data and plot three coefficient raster plots
    if(steps >= bufsize)
        {
            fit <- lm.fit(rhs, buffer)$coefficients
    ##         raster_plot(fit[1, ], my.ncol, my.nrow, "a0", steps)
    ##         raster_plot(fit[2, ], my.ncol, my.nrow, "a1", steps)
    ##         raster_plot(fit[3, ], my.ncol, my.nrow, "a2", steps)
      
    ## All these work fine!
    ##    X <- as.blockcyclic(X, bldim=c(4, 4))
    ##    X.pc <- prcomp(X)
    ##    comm.print(X.pc)
    
    ##
    ## Here, write out the results of the analysis
    a0 <- fit[1, ]
    a1 <- fit[2, ]
    a2 <- fit[3, ]
    ## now use adios to write (T, a0, a1, a2). All are with dimensions:
    ##       global.dim = g.dim
    ##       local.dim = my.dim = my.count
    ##       local.offset = my.start
  
     adios_file_ptr <- adios.open(groupname, filename, "a") ## WR

     groupsize <- object.size(data_chunk) ## Ask george       ## WR

     adios.group.size(adios_file_ptr, groupsize) ## WR
     adios.write(adios_file_ptr, "T", data_chunk) ## WR
     adios.close(adios_file_ptr) ## WR
     barrier() ## WR

    ## insert adios writing code here  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
     }
    
    ## try to get more data
    adios.advance.step(read.file.ptr, 0, adios.timeout.sec=1)
    comm.print(paste("Done advance.step", steps, "..."))
     
    ## check errors
    errno <- adios.errno()
    #comm.cat("Error Num",errno, "\n")

    ## if error is timeout (or EOF)
    if(errno == -22){ #-22 = err_step_notready
        comm.cat(comm.rank(), "Timeout waiting for more data. Quitting ...\n")
        break
    }
if(steps > 20) break
} # While end 

comm.print("Broke out of loop ...")
adios.read.close(read.file.ptr)
comm.print("File closed")
adios.read.finalize.method("ADIOS_READ_METHOD_BP")
comm.print("Finalized adios ...")

adios.finalize(pbdMPI:::comm.rank()) # ADIOS finalize ## WR

finalize() # pbdMPI finalize

file <- commandArgs(trailingOnly=T)[1]
print( file )
t <- read.table(
        file, 
        sep="\t",
        header=T,
        fill=T
        )

base <- sub( "(^[^.]+).*", "\\1", file )
image <- paste( base, "png", sep="." )
png( image )

p <- list(
        boxwex = 0.1,
        ylab   = "Times, s"
        )
boxplot( t, pars=p )

#'@title arrange_ggplot2
#'@description
#'Arranges ggplot2 plot objects in a grid using code from Stephen Turner's website.
#'from http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html
#'use pdf(); arrange(p1,p2,ncol=1); dev.off() to save the plot to a file
#'@param list list of plot objects
#'@param ncol number of columns, can be null
#'@param nrow number of rows, can be null
#'@param as.table boolean, determines order in grid
#'@export

arrange_ggplot2 <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
  library(ggplot2)
  library(grid)
  vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
  
  dots <- list(...)
  n <- length(dots)
  if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
  if(is.null(nrow)) { nrow = ceiling(n/ncol)}
  if(is.null(ncol)) { ncol = ceiling(n/nrow)}
  ## NOTE see n2mfrow in grDevices for possible alternative
  grid.newpage()
  pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
  ii.p <- 1
  for(ii.row in seq(1, nrow)){
    ii.table.row <- ii.row	
    if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
    for(ii.col in seq(1, ncol)){
      ii.table <- ii.p
      if(ii.p > n) break
      print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
      ii.p <- ii.p + 1
    }
  }
}

#'@title vertical_dotchart
#'@description
#'Produces a vertical dot chart, with a metric variable giving the length of a horizontal 
#'line segment and a dot colored by a grouping variable.  Each row in the data frame becomes a 
#'row in the dotchart.  The y variable is a label for each row, and rows can be grouped
#'by a grouping variable.  The plot can be sorted in descending order of the x metric variable,
#'or grouped by the grouping variable and then sorted.   
#'
#'@param df Data frame to be plotted
#'@param x_var Name of the metric variable to be plotted, as a string
#'@param x_label Name of the metric variable as a plot legend string
#'@param y_var Name of the categorical variable labeling each row in the data frame
#'@param y_label Name of the categorical variable, as a plot legend string
#'@param y_group_var Name of a categorical variable which groups the rows
#'@param legend_title Title of the legend for groups, defaults to "Experiment Group"
#'@param sort.by.xvar Boolean flag to sort rows by the metric variable, defaults to TRUE
#'@param group.by.ygroup Boolean flag to sort groups of rows by the grouping variable, defaults to TRUE
#'@return ggplot2 object
#'@export

vertical_dotchart <- function(df, 
                              x_var = xvar, 
                              x_label = xlabel, 
                              y_var = yvar, 
                              y_label = "Experiment", 
                              y_group_var = NULL, 
                              legend_title = "Experiment Group",
                              sort.by.xvar = TRUE, 
                              group.by.ygroup = TRUE) {
  
  require(ggplot2)
  require(ggthemes)

  # prevent a conflict if the user doesn't set the flag but leaves off a grouping variable
  if(is.null(y_group_var)) {
    group.by.ygroup = FALSE
  }
  
  if(sort.by.xvar == TRUE) {
      df$yvar_sorted <- reorder(df[[y_var]], df[[x_var]])
      plt <- ggplot(df, aes_string(x = x_var, y = "yvar_sorted")) 
    } else {
      plt <- ggplot(df, aes_string(x = x_var, y = y_var))
    }

  plt <- plt + ylab(y_label)
  plt <- plt + xlab(x_label)
  
  if(!is.null(y_group_var)) {
    plt <- plt + geom_segment(aes_string(yend = "yvar_sorted"), xend = 0, color = "grey50")
    plt <- plt + geom_point(size = 3, aes_string(color = y_group_var)) + labs(color = legend_title)
  } else {
    plt <- plt + geom_segment(aes_string(yend = y_var), xend = 0, color = "grey50")
    plt <- plt + geom_point(size = 3)
  }

  plt <- plt + theme_pander()
  plt <- plt + theme(panel.grid.major.x = element_blank(),
                     panel.grid.minor.x = element_blank(),
                     strip.background = element_blank(), strip.text = element_blank())
  if(group.by.ygroup == TRUE) {
    form <- as.formula(paste(y_group_var, "~", ".", sep = " "))
    plt <- plt + facet_grid(form, scales = "free_y", space = "free_y")
  }
  
  plt
}



require(proto)

StatEllipse <- proto(ggplot2:::Stat,
{
  required_aes <- c("x", "y")
  default_geom <- function(.) GeomPath
  objname <- "ellipse"
  
  calculate_groups <- function(., data, scales, ...){
    .super$calculate_groups(., data, scales,...)
  }
  calculate <- function(., data, scales, level = 0.75, segments = 51,...){
    dfn <- 2
    dfd <- length(data$x) - 1
    if (dfd < 3){
      ellipse <- rbind(c(NA,NA))	
    } else {
      require(MASS)
      v <- cov.trob(cbind(data$x, data$y))
      shape <- v$cov
      center <- v$center
      radius <- sqrt(dfn * qf(level, dfn, dfd))
      angles <- (0:segments) * 2 * pi/segments
      unit.circle <- cbind(cos(angles), sin(angles))
      ellipse <- t(center + radius * t(unit.circle %*% chol(shape)))
    }
    
    ellipse <- as.data.frame(ellipse)
    colnames(ellipse) <- c("x","y")
    return(ellipse)
  }
}
)

#' @title stat_ellipse
#' @description 
#' ggplot2 confidence ellipse from https://raw.github.com/JoFrhwld/FAAV/master/r/stat-ellipse.R
#' @export

stat_ellipse <- function(mapping=NULL, data=NULL, geom="path", position="identity", ...) {
  StatEllipse$new(mapping=mapping, data=data, geom=geom, position=position, ...)
}



# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context = NULL, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (remember) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()

    # Set the first cache environment
    if (length(stages) > 0) {
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage))
          function(...) stage$run(verbose = verbose, .depth = .depth + 1, ...)
        else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) stage$run(...)
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]]))
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        function(...)
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message)
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      before_env <-
        if (nested_run) run_stage(..., remember_flag = TRUE)$before
        else { # a leaf / terminal node
          if (is.null(env <- stages[[stage_index]]$cached_env))
            stop("Cannot run this stage yet because some previous stages have ",
                 "not been executed.")

          # Restart execution from cache, so set context to the cached environment.
          copy_env(context, env)
          env
        }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) run_stage(...) 
    }
    else if (remember) run_stage(..., remember_flag = FALSE)
    else run_stage(...)

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      node <- treeSkeleton$new(stages[[stage_index]])$successor()
      if (!is.null(node)) # Prepare a cache for the future!
        copy_env(node$object$cached_env <- new.env(parent = parent.env(context)), context)
      # TODO: Remove this hack used for printing
      else {
        root <- .self$.root()
        root$.finished <- TRUE
      }
    }

    if (display_message)
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
  }

  if (remember && remember_flag) list(before = before_env, after = context)
  else invisible(TRUE)
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    # TODO: Match by name *OR* index
    if (stagenames[[stage_index]] %in% names(stages)) {
      # If both are stageRunners, try to coalesce our sub-stages.
      if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          is.stagerunner(other_runner$stages[[stage_index]])) {
          stages[[names(stages)[stage_index]]]$coalesce(
            other_runner$stages[[stage_index]])
      # If both are not stageRunners, copy the cached_env if and only if
      # the stored function and its environment are identical
      } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          !is.stagerunner(other_runner$stages[[stage_index]]) &&
          !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
          #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
          #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
          # This is way too tricky and far beyond my abilities..
          #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
          #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
          ) {
        stages[[names(stages)[stage_index]]]$cached_env <<-
          new.env(parent = parent.env(context))
        if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
            is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
          copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                   other_runner$stages[[stage_index]]$cached_env)
          stages[[names(stages)[stage_index]]]$executed <<- 
            other_runner$stages[[stage_index]]$executed
        }
      }
    }
  })
  .set_parents()
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'environment', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#stageRunnerNode <- function(fn, parent_obj, parent_env = parent.frame()) {
#  env <- new.env(parent = parent_env)
#  class(env) <- c('stageRunnerNode', class(env))
#  env$fn <- fn
#
#  # Make a stageRunnerNode commensurate with treeSkeleton
#  # parent will be set later
#  if (!missing(parent_obj)) attr(env, 'parent') <- parent_obj
#  attr(env, 'children') <- list()
#
#  env
#}

#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        on.exit(environment(.callable) <- parent.env(environment(.callable)))
        .callable(.context, ...)
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

# Dynamically create an accessor method for reference classes.
accessor_method <- function(attr) {
  fn <- eval(bquote(
    function(`*VALUE*` = NULL)
      if (missing(`*VALUE*`)) .(substitute(attr))
      else .(substitute(attr)) <<- `*VALUE*`
  ))
  environment(fn) <- parent.frame()
  fn
}

#' Initialize a stageRunner object.
#'
#' stageRunner objects are used for executing a linear sequence of
#' actions on a context (an environment). For example, if we have an
#' environment \code{e} containing \code{x = 1, y = 2}, then using
#' \code{stages = list(function(e) e$x <- e$x + 1, function(e) e$y <- e$y - e$x)}
#' will cause \code{x = 2, y = 0} after running the stages.
#'
#' @name stageRunner__initialize
#' @param context an environment. The initial environment that is getting
#'    modified during the execution of the stages. 
#' @param .stages a list. The functions to execute on the \code{context}.
#' @param remember a logical. Whether to keep a copy of the context and its
#'    contents throughout each stage for debugging purposes--this makes it
#'    easy to go back and investigate a stage. This could be optimized by
#'    developing a package for "diffing" two environments. The default is
#'    \code{FALSE}. When set to \code{TRUE}, the return value of the
#'    \code{run} method will be a list of two environments: one of what
#'    the context looked like before the \code{run} call, and another
#'    of the aftermath.
#' @param mode character. Controls the default behavior of calling the
#'    \code{run} method for this stageRunner. The two supported options are
#'    "head" and "next". The former gives a stageRunner which always begins
#'    from the first stage if the \code{from} parameter to the \code{run}
#'    method is blank. Otherwise, it will begin from the previous unexecuted
#'    stage.  The default is "head". This argument has no effect if
#'    \code{remember = FALSE}.
stageRunner__initialize <- function(context = NULL, .stages, remember = FALSE,
                                    mode = getOption("stagerunner.mode") %||% 'head') {
  .finished <<- FALSE # TODO: Remove this hack for printing
  context <<- context

  if (identical(remember, TRUE) && !(is.character(mode) &&
      any((.mode <<- tolower(mode)) == c('head', 'next')))) {
    stop("The mode parameter to the stageRunner constructor must be ",
         "either 'head' or 'next'.")
  }

  legal_types <- function(x) is.function(x) || all(vapply(x,
    function(s) is.function(s) || is.stagerunner(s) || is.null(s) ||
      (is.list(s) && legal_types(s)), logical(1)))
  stopifnot(legal_types(.stages))
  if (is.function(.stages)) .stages <- list(.stages)
  stages <<- .stages

  # Construct recursive stagerunners out of a list of lists.
  for (i in seq_along(stages))
    if (is.list(stages[[i]]))
      stages[[i]] <<- stageRunner$new(context, stages[[i]], remember = remember)
    else if (is.function(stages[[i]]) || is.null(stages[[i]]))
      stages[[i]] <<- stageRunnerNode$new(stages[[i]], context)

  # Do not allow the '/' character in stage names, as it's reserved for
  # referencing nested stages.
  if (any(violators <- grepl('/', names(stages), fixed = TRUE))) {
    msg <- paste0("Stage names may not have a '/' character. The following do not ",
      "satisfy this constraint: '",
      paste0(names(stages)[violators], collapse = "', '"), "'")
    stop(msg)
  }

  remember <<- remember
  if (remember) {
    # Set up parents for treeSkeleton.
    .self$.clear_cache()
    .self$.set_parents()

    # Set the first cache environment
    if (length(stages) > 0) {
      first_env <- treeSkeleton$new(stages[[1]])$first_leaf()$object
      first_env$cached_env <- new.env(parent = parent.env(context))
      copy_env(first_env$cached_env, context)
    }
  }
}

#' Run the stages in a stageRunner object.
#'
#' @name stageRunner__run
#' @param from an indexing parameter. Many forms are accepted, but the
#'   easiest is the name of the stage. For example, if we have
#'   \code{stageRunner$new(context, list(stage_one = some_fn, stage_two = some_other_fn))}
#'   then using \code{run('stage_one')} will execute \code{some_fn}.
#'   Additional indexing forms are logical (which stages to execute),
#'   numeric (which stages to execute by indices), negative (all but the
#'   given stages), character (as above), and nested forms of these.
#'   The latter refers to instances of the following:
#'   \code{stageRunner$new(context, list(stage_one =
#'     stageRunner$new(context, substage_one = some_fn, substage_two = other_fn),
#'     stage_two = another_fn))}.
#'   Here, the following all execute only substage_two:
#'   \code{run(list(list(FALSE, TRUE), FALSE))},
#'   \code{run(list(list(1, 2)))},
#'   \code{run('stage_one/substage_two')},
#'   \code{run('one/two')},
#'   \code{run(list(list('one', 'two')))},
#'   \code{run(list(list('one', 2)))}
#'   Notice that regular expressions are allowed for characters.
#'   The default is \code{NULL}, which runs the whole sequences of stages.
#' @param to an indexing parameter. If \code{stage_key} refers to a single stage,
#'   attempt to run from that stage to this stage (or, if this one comes first,
#'   this stage to that stage). For example, if we have
#'      \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#'   where the numbers are some functions, and we call \code{run} with
#'   \code{stage_key = 'a/c'} and \code{to = 'e/f'}, then we would execute
#'   stages \code{"a/c", "d", "e/f"}.
#' @param normalized logical. A convenience recursion performance helper. If
#'   \code{TRUE}, stageRunner will assume the \code{stage_key} argument is a
#' @param verbose logical. Whether or not to display pretty colored text
#'   informing about stage progress.
#'   nested list of logicals.
#' @param remember_flag logical. An internal argument used by \code{run}
#'   recursively if the \code{stageRunner} object has the \code{remember}
#'   field set to \code{TRUE}. If \code{remember_flag} is FALSE, \code{run}
#'   will not attempt to restore the context from cache (e.g., if we are
#'   executing five stages simultaneously with \code{remember = TRUE},
#'   the first stage's context should be restored from cache but none
#'   of the remaining stages should).
#' @param mode character. If \code{mode = 'head'}, then by default the
#'   \code{from} parameter will be used to execute that stage and that
#'   stage only. If \code{mode = 'next'}, then the \code{from} parameter
#'   will be used to run (by default, if \code{to} is left missing)
#'   from the last successfully executed stage to the stage given by
#'   \code{from}. If \code{from} occurs before the last successfully
#'   executed stage (say S), the stages will be run from \code{from} to S.
#' @param .depth integer. Internal parameter for keeping track of nested running level.
#' @param ... Any additional arguments to delegate to the \code{stageRunnerNode}
#'   object that will execute its own \code{run} method.
#'   (See \code{stageRunnerNode$run})
#' @return TRUE or FALSE according as running the stages specified by the
#'   \code{stage_key} succeeded or failed.  If \code{remember = TRUE},
#'   this will instead be a list of the environment before and after
#'   executing the aforementioned stages. (This allows comparing what
#'   changes were made to the \code{context} during the execution of
#'   the stageRunner.
stageRunner__run <- function(from = NULL, to = NULL,
                             normalized = FALSE, verbose = FALSE,
                             remember_flag = TRUE, mode = .mode, .depth = 1, ...) {
  if (identical(normalized, FALSE)) {
    if (missing(from) && identical(remember, TRUE) && identical(mode, 'next')) {
      from <- next_stage()
      if (missing(to)) to <- TRUE
    }
    stage_key <- normalize_stage_keys(from, stages, to = to)
  } else stage_key <- from

  # Now that we have determined which stages to run, cycle through them all.
  # It is up to the user to determine that context changes make sense.
  # We also implicitly sort the stages to ensure linearity is preserved.
  # Stagerunner enforces the linearity and directionality set in the stage definitions.
  
  # If we are remembering changes, recall what the environment looked like
  # *before* we ran anything.
  before_env <- NULL

  for (stage_index in seq_along(stage_key)) {
    nested_run <- TRUE
    
    # Determine how to run this stage, depending on whether it is an
    # terminal node or nested stagerunner. We compute this first
    # in case we run into referencing errors (e.g., the requested
    # stage does not exist).
    run_stage <-
      if (identical(stage_key[[stage_index]], TRUE)) {
        stage <- stages[[stage_index]]
        if (is.stagerunner(stage))
          function(...) stage$run(verbose = verbose, .depth = .depth + 1, ...)
        else {
         nested_run <- FALSE
         # Intercept the remember_flag argument to calls to the stageRunnerNode
         # (since it doesn't know how to use it).
         function(..., remember_flag = TRUE) stage$run(...)
        }
      } else if (is.list(stage_key[[stage_index]])) {
        if (!is.stagerunner(stages[[stage_index]]))
          stop("Invalid stage key: attempted to make a nested stage reference ",
               "to a non-existent stage")
        function(...)
          stages[[stage_index]]$run(stage_key[[stage_index]], normalized = TRUE,
                                    verbose = verbose, .depth = .depth + 1, ...)
      } else next 

    display_message <- verbose && contains_true(stage_key[[stage_index]])
    if (display_message)
      show_message(names(stages), stage_index, begin = TRUE,
                   nested = nested_run, depth = .depth)

    # Now handle when remember = TRUE, i.e., we have to cache the
    # progress along each stage.

    if (remember && remember_flag && is.null(before_env)) {
      # If remember = remember_flag = TRUE and before_env has not been set
      # this is the first stage of a $run() call, so use the cached
      # environment.
      before_env <-
        if (nested_run) run_stage(..., remember_flag = TRUE)$before
        else { # a leaf / terminal node
          if (is.null(env <- stages[[stage_index]]$cached_env))
            stop("Cannot run this stage yet because some previous stages have ",
                 "not been executed.")

          # Restart execution from cache, so set context to the cached environment.
          copy_env(context, env)
          env
        }
      
      # If terminal node, execute the stage (if it was nested,  it's already been
      # executed in order to recursively fetch the before_env).
      if (!nested_run) run_stage(...) 
    }
    else if (remember) run_stage(..., remember_flag = FALSE)
    else run_stage(...)

    if (remember && !nested_run) {
      # When we're done running a stage (i.e., processing a terminal node),
      # set the cache on the successor node to be the current context
      # (since that node will execute starting with what's in the context now --
      # this also ensures that running that node with a separate call to
      # $run will not bump into a "you haven't executed this stage yet" error).
      node <- treeSkeleton$new(stages[[stage_index]])$successor()
      if (!is.null(node)) # Prepare a cache for the future!
        copy_env(node$object$cached_env <- new.env(parent = parent.env(context)), context)
      # TODO: Remove this hack used for printing
      else {
        root <- .self$.root()
        root$.finished <- TRUE
      }
    }

    if (display_message)
      show_message(names(stages), stage_index, begin = FALSE,
                   nested = nested_run, depth = .depth)
  }

  if (remember && remember_flag) list(before = before_env, after = context)
  else invisible(TRUE)
}

#' Wrap a function around a stageRunner's terminal nodes
#'
#' If we want to execute some behavior just before and just after executing
#' terminal nodes in a stageRunner, a solution without this method would be
#' to overlay two runners -- one before and one after. However, this is messy,
#' so this function is intended to replace this approach with just one function.
#'
#' Consider the runner
#'   \code{sr <- stageRunner$new(some_env, list(a = function(e) print('2'))}
#' If we run 
#'   \code{sr2 <- stageRunner$new(some_env, list(a = function(e) {
#'     print('1'); yield(); print('3') }))
#'    sr1$around(sr2)
#'    sr1$run()
#'  }
#' then we will see 1, 2, and 3 printed in succession. The \code{yield()}
#' keyword is used to specify when to execute the terminal node that
#' is sandwiched in the "around" runner.
#'
#' @name stageRunner__around
#' @param other_runner stageRunner. Another stageRunner from which to create
#'   an around procedure. Alternatively, we could give a function or a list
#'   of functions.
stageRunner__around <- function(other_runner) {
  if (is.null(other_runner)) return(.self)
  if (!is.stagerunner(other_runner)) other_runner <- stageRunner$new(context, other_runner)
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    name <- stagenames[stage_index]
    this_index <- 
      if (identical(name, "")) stage_index
      else if (is.element(name, names(stages))) name
      else return()

    if (is.stagerunner(stages[[this_index]]) &&
        is.stagerunner(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else if (is.stageRunnerNode(stages[[this_index]]) &&
               is.stageRunnerNode(other_runner$stages[[stage_index]])) {
      stages[[this_index]]$around(other_runner$stages[[stage_index]])
    } else {
      warning("Cannot apply around stageRunner because ",
              this_index, " is not a terminal node.")
    }
  })
  .self
}

#' Coalescing a stageRunner object is taking another stageRunner object
#' with similar stage names and replacing the latter's cached environments
#' with the former's.
#'
#' @name stageRunner__coalesce
#' @param other_runner stageRunner. Another stageRunner from which to coalesce.
stageRunner__coalesce <- function(other_runner) {
  # TODO: Should we care about insertion of new stages causing cache wipes?
  # For now it seems like this would just be an annoyance.
  # stopifnot(remember)
  if (!isTRUE(remember)) return()
  stagenames <- names(other_runner$stages) %||% rep("", length(other_runner$stages))
  lapply(seq_along(other_runner$stages), function(stage_index) {
    # TODO: Match by name *OR* index
    if (stagenames[[stage_index]] %in% names(stages)) {
      # If both are stageRunners, try to coalesce our sub-stages.
      if (is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          is.stagerunner(other_runner$stages[[stage_index]])) {
          stages[[names(stages)[stage_index]]]$coalesce(
            other_runner$stages[[stage_index]])
      # If both are not stageRunners, copy the cached_env if and only if
      # the stored function and its environment are identical
      } else if (!is.stagerunner(stages[[names(stages)[stage_index]]]) &&
          !is.stagerunner(other_runner$stages[[stage_index]]) &&
          !is.null(other_runner$stages[[stage_index]]$cached_env) #&&
          #identical(deparse(stages[[names(stages)[stage_index]]]$fn),
          #          deparse(other_runner$stages[[stage_index]]$fn)) # &&
          # This is way too tricky and far beyond my abilities..
          #identical(stagerunner:::as.list.environment(environment(stages[[names(stages)[stage_index]]]$fn)),
          #          stagerunner:::as.list.environment(environment(other_runner$stages[[stage_index]]$fn)))
          ) {
        stages[[names(stages)[stage_index]]]$cached_env <<-
          new.env(parent = parent.env(context))
        if (is.environment(other_runner$stages[[stage_index]]$cached_env) &&
            is.environment(stages[[names(stages)[stage_index]]]$cached_env)) {
          copy_env(stages[[names(stages)[stage_index]]]$cached_env,
                   other_runner$stages[[stage_index]]$cached_env)
          stages[[names(stages)[stage_index]]]$executed <<- 
            other_runner$stages[[stage_index]]$executed
        }
      }
    }
  })
  .set_parents()
  .self
}

#' Overlaying a stageRunner object is taking another stageRunner object
#' with similar stage names and adding the latter's stages as terminal stages
#' to the former (for example, to support tests).
#'
#' @name stageRunner__overlay
#' @param other_runner stageRunner. Another stageRunner from which to overlay.
#' @param label character. The label for the overlayed stageRunner. This refers
#'    to the name the former will get wrapped with when appended to the
#'    stages of the current stageRunner. For example, if \code{label = 'test'},
#'    and a current terminal node is unnamed, it will becomes
#'    \code{list(current_node, test = other_runner_node)}.
#' @param flat logical. Whether to use the \code{stageRunner$append} method to
#'    overlay, or simply overwrite the given \code{label}. If \code{flat = TRUE},
#'    you must supply a \code{label}. The default is \code{flat = FALSE}.
stageRunner__overlay <- function(other_runner, label = NULL, flat = FALSE) {
  stopifnot(is.stagerunner(other_runner))
  for (stage_index in seq_along(other_runner$stages)) {
    name <- names(other_runner$stages)[[stage_index]]
    index <-
      if (identical(name, '') || identical(name, NULL)) stage_index
      else if (name %in% names(stages)) name
      else stop('Cannot overlay because keys do not match')
    stages[[index]]$overlay(other_runner$stages[[stage_index]], label, flat)
  }
  TRUE
}

#' Transform the callable's of the terminal nodes of a stageRunner.
#'
#' Every terminal node in a stageRunner is of type stageRunnerNode.
#' These each have a callable, and this method transforms those
#' callables in the way given by the first argument.
#'
#' @name stageRunner__transform
#' @param transformation function. The function which transforms one callable
#'   into another.
stageRunner__transform <- function(transformation) {
  for (stage_index in seq_along(stages))
    stages[[stage_index]]$transform(transformation)
}

#' Append one stageRunner to the end of another.
#'
#' @name stageRunner__append
#' @param other_runner stageRunner. Another stageRunner to append to the current one.
#' @param label character. The label for the new stages (this will be the name of the
#'   newly appended list element).
stageRunner__append <- function(other_runner, label = NULL) {
  stopifnot(is.stagerunner(other_runner))
  new_stage <- structure(list(other_runner), names = label)
  stages <<- base::append(stages, new_stage)
  TRUE
}

#' Retrieve a flattened list of canonical stage names for a stageRunner object
#'
#' For example, if we have stages
#'   \code{stages = list(a = list(b = 1, c = 2), d = 3, e = list(f = 4, g = 5))}
#' then this method would return
#'   \code{list('a/b', 'a/c', 'd', 'e/f', 'e/g')}
#'
#' @name stageRunner__stage_names
#' @return a list of canonical stage names.
#' @examples
#' f <- function() {}
#' sr <- stageRunner$new(new.env(),
#'   list(a = stageRunner$new(new.env(), list(b = f, c = f)), d = f,
#'   e = stageRunner$new(new.env(), list(f = f, g = f))))
#' sr$stage_names()
stageRunner__stage_names <- function() {
  nested_stages <- function(x) if (is.stagerunner(x)) nested_stages(x$stages) else x
  nested_names(lapply(stages, nested_stages))
}

#' For stageRunners with caching, find the next unexecuted stage.
#'
#' @name stageRunner__next_stage
#' @return a character stage key giving the next unexecuted stage.
#'   If all stages have been executed, this returns \code{FALSE}.
#'   If the stageRunner does not have caching enabled, this will
#'   always return the first stage key (`'1'`).
stageRunner__next_stage <- function() {
  for (stage_index in seq_along(stages)) {
    is_unexecuted_terminal_node <- is.stageRunnerNode(stages[[stage_index]]) &&
      !stages[[stage_index]]$was_executed()
    has_unexecuted_terminal_node <- is.stagerunner(stages[[stage_index]]) &&
      is.character(tmp <- stages[[stage_index]]$next_stage())

    if (is_unexecuted_terminal_node) return(as.character(stage_index))
    else if (has_unexecuted_terminal_node)
      return(paste(c(stage_index, tmp), collapse = '/'))
  }
  FALSE
}

#' Generic for printing stageRunner objects.
#' 
#' @name stageRunner__show
#' @param indent integer. Internal parameter for keeping track of nested
#'   indentation level.
stageRunner__show <- function(indent = 0) {
  if (missing(indent)) {
    sum_stages <- function(x) sum(vapply(x,
      function(x) if (is.stagerunner(x)) sum_stages(x$stages) else 1L, integer(1)))
    caching <- if (remember) ' caching' else ''
    cat("A", caching, " stageRunner with ", sum_stages(.self$stages), " stages:\n", sep = '')
  }
  stage_names <- names(stages) %||% rep("", length(stages))

  # A helper function for determining if a stage has been run yet.
  began_stage <- function(stage)
    if (is.stagerunner(stage)) any(vapply(stage$stages, began_stage, logical(1)))
    else if (is.stageRunnerNode(stage)) !is.null(stage$cached_env)
    else FALSE

  lapply(seq_along(stage_names), function(index) {
    prefix <- paste0(rep('  ', (if (is.numeric(indent)) indent else 0) + 1), collapse = '')
    marker <-
      if (remember && began_stage(stages[[index]])) {
        next_stage <- treeSkeleton$new(stages[[index]])$last_leaf()$successor()$object
        if (( is.null(next_stage) && !.self$.root()$.finished) ||
            (!is.null(next_stage) && !began_stage(next_stage))) 
          '*' # Use a * if this is the next stage to be executed
          # TODO: Fix the bug where we are unable to tell if the last stage
          # finished without a .finished internal field.
          # We need to look at and set predecessors, not successors.
        else '+' # Other use a + for completely executed stage
      } else '-'
    prefix <- gsub('.$', marker, prefix)
    stage_name <- 
      if (is.na(stage_names[[index]]) || stage_names[[index]] == "")
        paste0("< Unnamed (stage ", index, ") >")
      else stage_names[[index]]
    cat(prefix, stage_name, "\n")
    if (is.stagerunner(stages[[index]]))
      stages[[index]]$show(indent = indent + 1)
  })

  if (missing(indent)) { cat('Context '); print(context) }
  NULL
}

#' Whether or not the stageRunner has a key matching this input.
#'
#' @param key ANY. The potential key.
#' @return \code{TRUE} or \code{FALSE} accordingly.
stageRunner__has_key <- function(key) {
  has <- tryCatch(normalize_stage_keys(key, stages), error = function(.) FALSE)
  any(c(has, recursive = TRUE))
}

#' Clear all caches in this stageRunner, and recursively.
#' @name stageRunner__.clear_cache
stageRunner__.clear_cache <- function() {
  for (i in seq_along(stages)) {
    if (is.stagerunner(stages[[i]])) stages[[i]]$.clear_cache()
    else stages[[i]]$cached_env <<- NULL
  }
  TRUE
}

#' Set all parents for this stageRunner, and recursively
#' @name stageRunner__.set_parents
stageRunner__.set_parents <- function() {
  for (i in seq_along(stages)) {
    # Set convenience helper attribute "child_index" to ensure that treeSkeleton
    # can find this stage.
    if (inherits(stages[[i]], 'refClass')) {
      # http://stackoverflow.com/questions/22752021/why-is-r-capricious-in-its-use-of-attributes-on-reference-class-objects
      unlockBinding('.self', attr(stages[[i]], '.xData'))
      attr(attr(stages[[i]], '.xData')$.self, 'child_index') <<- i
      lockBinding('.self', attr(stages[[i]], '.xData'))
    } else attr(stages[[i]], 'child_index') <<- i

    if (!inherits(stages[[i]], 'refClass')) {
      attr(stages[[i]], 'parent') <<- .self
    } else {
      # if stages[[i]] has a .set_parents method (e.g. it is a stagerunner), run that
      if ('.set_parents' %in% ls(stages[[i]]$.refClassDef@refMethods, all.names = TRUE))
        stages[[i]]$.set_parents()
      stages[[i]]$parent(.self)
    }
  }
  .parent <<- NULL
}

#' Determine the root of the stageRunner.
#'
#' @name stageRunner__.root
#' @return the root of the stageRunner
stageRunner__.root <- function() {
  treeSkeleton$new(.self)$root()$object
}

#' Stage runner is a reference class for parametrizing and executing
#' a linear sequence of actions.
#' 
#' @name stageRunner
#' @export
NULL

stageRunner <- setRefClass('stageRunner',
  fields = list(context = 'environment', stages = 'list', remember = 'logical',
                .mode = 'character', .parent = 'ANY', .finished = 'logical'),
  methods = list(
    initialize   = stageRunner__initialize,
    run          = stageRunner__run,
    around       = stageRunner__around,
    coalesce     = stageRunner__coalesce,
    overlay      = stageRunner__overlay,
    transform    = stageRunner__transform,
    append       = stageRunner__append,
    stage_names  = stageRunner__stage_names,
    parent       = accessor_method(.parent),
    children     = function() { stages },
    next_stage   = stageRunner__next_stage,
    show         = stageRunner__show,
    has_key      = stageRunner__has_key,
    mode         = accessor_method(.mode),
    .set_parents = stageRunner__.set_parents,
    .clear_cache = stageRunner__.clear_cache,
    .root        = stageRunner__.root
  )
)

#' Check whether an R object is a stageRunner object
#'
#' @export
#' @param obj any object.
#' @return \code{TRUE} if the object is of class
#'    \code{stageRunner}, \code{FALSE} otherwise.
is.stagerunner <- function(obj) inherits(obj, 'stageRunner')
#' @export
is.stageRunner <- is.stagerunner

#' Stagerunner nodes are environment wrappers around individual stages
#' (i.e. functions) in order to track meta-data (e.g., for caching).
#' 
#' @param fn function. This will be wrapped in an environment.
#' @param parent_obj stageRunner. The enclosing stageRunner object.
#' @param parent_env environment. The parent environment of the created
#'   \code{stageRunnerNode} object. The default is the calling
#'   environment (i.e., \code{parent.frame()}).
#' @return an environment with some additional attributes for
#'   navigating in a tree-like structure.
#stageRunnerNode <- function(fn, parent_obj, parent_env = parent.frame()) {
#  env <- new.env(parent = parent_env)
#  class(env) <- c('stageRunnerNode', class(env))
#  env$fn <- fn
#
#  # Make a stageRunnerNode commensurate with treeSkeleton
#  # parent will be set later
#  if (!missing(parent_obj)) attr(env, 'parent') <- parent_obj
#  attr(env, 'children') <- list()
#
#  env
#}

#' @name stageRunnerNode
#' @docType class
stageRunnerNode <- setRefClass('stageRunnerNode',
  fields = list(callable = 'ANY',
                cached_env = 'ANY',
                .context = 'ANY',
                .parent = 'ANY',
                executed = 'logical'),
  methods = list(
    initialize = function(.callable, .context = NULL) {
      stopifnot(is_any(.callable, c('stageRunner', 'function', 'NULL')))
      callable <<- .callable; .context <<- .context; executed <<- FALSE
    },
    run = function(..., .cached_env = NULL, .callable = callable) {
      # TODO: Clean this up by using environment injection utility fn
      correct_cache <- .cached_env %||% cached_env
      if (is.null(.callable)) FALSE
      else if (is.stagerunner(.callable))
        .callable$run(..., .cached_env = correct_cache)
      else {
        tmp <- new.env(parent = environment(.callable))
        environment(.callable) <- tmp
        environment(.callable)$cached_env <- correct_cache
        .callable(.context, ...)
        environment(.callable) <- parent.env(environment(.callable))
      }
      executed <<- TRUE
    }, 

    # This function goes hand in hand with stageRunner$around
    around = function(other_node) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.function(other_node)) {
        warning("Cannot apply stageRunner$around in a terminal ",
                "node except with a function. Instead, I got a ",
                class(other_node)[1])
        return(FALSE)
      }

      new_callable <- other_node
      # Inject yield() keyword
      yield_env <- new.env(parent = environment(new_callable))
      yield_env$.parent_context <- .self
      yield_env$yield <- function() {
        # ... lives up two frames, but the run function lives up 1,
        # so we have to do something ugly
        run <- eval.parent(quote(.parent_context$run))
        args <- append(eval.parent(quote(list(...)), n = 2),
          list(.callable = callable))
        do.call(run, args, envir = parent.frame())
      }
      environment(yield_env$yield) <- new.env(parent = baseenv())
      environment(yield_env$yield)$callable <- callable

      environment(new_callable) <- yield_env
      callable <<- new_callable
      TRUE
    },

    overlay = function(other_node, label = NULL, flat = FALSE) {
      if (is.stageRunnerNode(other_node)) other_node <- other_node$callable
      if (is.null(other_node)) return(FALSE)
      if (!is.stagerunner(other_node)) 
        other_node <- stageRunner$new(.context, other_node)

      # Coerce the current callable object to a stageRunner so that
      # we can append the other_node's stageRunner.
      if (!is.stagerunner(callable)) 
        callable <<- stageRunner$new(.context, callable)

      # TODO: Fancier merging here
      if (isTRUE(flat)) {
        if (!is.character(label)) stop("flat coalescing needs a label")
        callable$stages[[label]] <<- other_node
      } else callable$append(other_node, label)
    },
    transform = function(transformation) {
      if (is.stagerunner(callable)) callable$transform(transformation)
      else callable <<- transformation(callable)
    },
    was_executed = function() { executed },
    parent   = accessor_method(.parent),
    children = function() list(),
    show     = function() { cat("A stageRunner node containing: \n"); print(callable) }
  )
)

is.stageRunnerNode <- function(obj) inherits(obj, 'stageRunnerNode')

REBOL [
    Title:   "Rectangle-pack"
    Date:    14-Feb-2012/20:39:44+1:00
    Name:    'rectangle-pack
    Version: 1.0.0
	History: [
		1.0.0 27-Oct-2010 {Initial version}
		1.1.0 14-Feb-2012 {
			Added pow2-rectangle-pack and pow2-box-pack functions.
			It's possible to specify pre-sorting method} 
	]
    File: %rectangle-pack.r
    Author: "Oldes"
    Owner: none
    Rights: none
    Needs: none
    Tabs: none
    Usage: [
		probe pow2-rectangle-pack [
			120x10 "img1"
			125x5  "img2"
			100x4  "img3"
		]
		probe pow2-box-pack [
			120x10 "img1"
			125x5  "img2"
			100x4  "img3"
		]
	]
    Purpose: none
    Comment: {
    This code was inspired by this page:
    http://www.blackpawn.com/texts/lightmaps/default.html
    It's not exactly the same as this one is not using recursion, but works fine for my purposes.
    Here are for example packed bitmaps into 256x256 texture:
    http://box.lebeda.ws/~hmm/rebol/rectangle-pack-result.jpg
    }
    History: none
    Language: none
    Type: none
    Email: none
]

ctx-rectangle-pack: context [
	padding: 1x1
	max-size: 8192x8192
	verbose: 0
	
	round-to-pow2: func[v /local p][ repeat i 14 [if v <= (p: 2 ** i) [return p]] none]
	
	max-pow2-size: func[data /local maxpair ][
		maxpair:  0x0
		foreach [size id] data [
			maxpair: max maxpair size
		]
		maxpair/x: to-integer round-to-pow2 maxpair/x
		maxpair/y: to-integer round-to-pow2 maxpair/y
		maxpair
	]
	min-pow2-size: func[data /local minpair ][
		minpair:  0x0
		foreach [size id] data [
			minpair: max minpair size
		]
		minpair/x: to-integer round-to-pow2 minpair/x
		minpair/y: to-integer round-to-pow2 minpair/y
		minpair
	]
	pow2-area: func[size][
		(round-to-pow2 size/x) * (round-to-pow2 size/y)
	]
	
	set 'pow2-box-pack func[images /method sort-method /local size data-to-process result][

		size: min-pow2-size images
		size: as-pair tmp: min size/x size/y tmp
		
		data-to-process: copy images

		while [
			not empty? second result: rectangle-pack/method data-to-process size sort-method
		][
			size: size * 2
			;print reform ["retry with size:" size]
		]
		reduce [size result]
	]
	
	set 'pow2-rectangle-pack func[images /method sort-method /local size data-to-process result][

		minsize: min-pow2-size images
		data-to-process: copy images

		minArea:   to-integer #{7FFFFFFF}
		minResult: none
		
		size: minsize
		until [
			until [
				result: rectangle-pack/method data-to-process size sort-method
				area: size/x * size/y
				;print ["test size:" size]
				if empty? second result [
					if minArea >= area [
						;print ["???" result/3  ]
						if any [
							none? minResult
							minArea > area
							(pow2-area size) < (pow2-area minResult/1)
							all [
								(pow2-area size) = (pow2-area minResult/1)
								any [
									size/x = size/y
									(max size/x size/y) < (max minResult/1/x minResult/1/y)
								]
							]
						][
							minArea: area
							minResult: reduce [size result]
							;print ["NEW MIN AREA:" area]
						]
					]
					break
				]
				size/x: size/x * 2
				;print ["?X" area minArea]
				not all [
					area < minArea
					size/x <= max-size/x
				]
			]
			size/y: size/y * 2
			size/x: minsize/x
			area: pow2-area size
			;print ["?Y" area minArea size/y]
			not all [
				area <= minArea
				size/y <= max-size/y
			]
		]
		
		;print "-----------"
		;probe minArea
		unless minResult [
			probe result
			minResult: reduce [max-size result]
		]
		minResult
	]

	set 'rectangle-pack func[
		"Takes block of sizes and ids and tries to pack them to specified area, returns block with placed and skiped data"
		size-data   [block!] "block with [size1 id1 size2 id2 ...]"
		target-area [pair! ] "Size of the target area"
		/method sort-method 
		/local placed skiped free-bins free-area placed? rw rh rx ry width height
	][
		if verbose > 0 [print ["RECTPACK to size:" target-area]]
		sort/compare/skip size-data func[a b /local oa ob][
			switch/default sort-method [
				2 [
					;precedence: side Y
					case [
						a/y < b/y [ 1]
						a/y > b/y [-1]
						a/x < b/x [ 1]
						a/x > b/x [-1]
						true      [ 0]
					]
				]
				3 [
					;predecence: area
					case[
						(oa: a/x * a/y) > (ob: b/x * b/y) [-1]
						oa < ob                           [ 1]
						true                              [ 0]
					]
				]
				4 [
					;precedence: any side's size
					case[
						(oa: max a/x a/y) > (ob: max b/x b/y) [-1]
						oa < ob                           [ 1]
						true                              [ 0]
					]
				]
			][;default = 1:
				;precedence: side X
				case [
					a/x < b/x [ 1]
					a/x > b/x [-1]
					a/y < b/y [ 1]
					a/y > b/y [-1]
					true      [ 0]
				]
			]
		] 2
		
		placed:    copy []
		skiped:    copy []
		free-bins: reduce [target-area/x target-area/y 0 0]
		
		foreach [size id] size-data [
			free-bins: head free-bins
			placed?: false
			while [not tail? free-bins][
				set [rw rh rx ry] free-bins
				width:  size/x + padding/x
				height: size/y + padding/y
				either all [
					width <= rw
					height <= rh
				][
					repend placed [as-pair rx ry size id]
					placed?: true
					change/part free-bins reduce either (rw  - width) > (rh - height) [
						[
							free-bins/1 - width
							free-bins/2
							free-bins/3 + width
							free-bins/4
							width
							free-bins/2 - height
							free-bins/3
							free-bins/4 + height
						]
					][
						[
							free-bins/1 - width
							height
							free-bins/3 + width
							free-bins/4
							free-bins/1
							free-bins/2 - height
							free-bins/3
							free-bins/4 + height
						]
					] 4
					break
				][
					free-bins: skip free-bins 4
				]
			]
			unless placed? [
				;print ["NOT FOUND SPACE FOR:" size "^/^-" id]
				repend skiped [size id]
			]
		]
		free-area: 0
		foreach [rw rh rx ry] free-bins [
			free-area: free-area + (rw * rh)
		]

		new-line/skip placed true 3
		reduce [placed skiped free-area]
	]
]

REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	;--                 [objects images shapes sounds strings]
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   30]
		%PlanetaZluta      [600     1300   100    250   30]
		%PlanetaTermiti    [600     1300   100    290   30]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 300 30]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 0.5 * length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script exe console][
		script: temp-dir/red-console.red
		exe: temp-dir/console
		
		if Windows? [append exe %.exe]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < build-date				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red
			write temp-dir/wcwidth.reds read-cache console/wcwidth.reds
			write temp-dir/win32.reds read-cache console/win32.reds
			write temp-dir/POSIX.reds read-cache console/POSIX.reds

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			delete temp-dir/wcwidth.reds
			delete temp-dir/win32.reds
			delete temp-dir/POSIX.reds

			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Check if s3mpi package is installed and loaded.
#'
#' Stopped if s3mpi package is not installed.
#'
#' @return \code{TRUE} or \code{FALSE} indicating if loading and 
#'  attaching is successful.
common_s3mpi_package_loader <- function() {
  if (!'s3mpi' %in% installed.packages())
    stop("You must install and set up the s3mpi package from ",
         "https://github.com/robertzk/s3mpi", call. = FALSE)
  require(s3mpi)
}

#' Common s3 reader.
#'
#' Call s3 reader with arguments.
common_s3_reader <- function(opts) {
  common_s3mpi_package_loader()

  # If the user provided an s3 path, like "s3://somebucket/some/path/", 
  # pass it along to the s3read function.
  args <- list(name = opts$resource)
  if (is.element('s3path', names(opts))) args$.path <- opts$s3path
  do.call(s3mpi::s3read, args)
}

#' Common s3 formatter.
#' 
#' Format s3 options.
#'
#' @return options.
common_s3_formatter <- function(opts) {
  environment(common_file_formatter) <- parent.frame()
  opts <- common_file_formatter(opts)
  if (is.element('bucket', names(opts)))
    opts$s3path <- paste0("s3://", opts$bucket, "/")
  opts
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- object
    if (name_exists("object$output$options$data")) {
      data_restore_on_exit <- object$output$options$data
      on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
      obj$output$options$data <- NULL
    }
    if (name_exists("object$output$options$label")) {
      label_restore_on_exit <- object$output$options$label
      on.exit(object$output$options$label <- label_restore_on_exit, add = TRUE)
      obj$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

 # TODO: (RK) Read default_options in from config, so a user can
 # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_s3data_adapter <- function() {
  write_function <- function(object, opts) {
    common_s3mpi_package_loader()

    obj <- list(data = switch(1 + name_exists("object$output$options$data"), 
                              NULL, object$output$options$data), 
                label = switch(1 + name_exists("object$output$options$label"), 
                               NULL, object$output$options$label))

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = obj, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(common_s3_reader, write_function, format_function = common_s3_formatter,
          default_options = list(), keyword = 's3data')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file   = construct_file_adapter,
                          s3     = construct_s3_adapter,
                          r      = construct_R_adapter,
                          s3data = construct_s3data_adapter)
plotCategoryOverview = function(results, score, scoreCutoff, cancerType) {
	# Filter the genes according to user's criteria
	genes = as.character(subset(results, cancer == cancerType & score.type == "combined" & score >= scoreCutoff)$gene)
	
	# Sort the genes according to highest sum across all cancer types
	# Get the subset with the selected genes and drop unused levels
	gene.order = subset(result.df, score.type=="combined" & gene %in% genes)
	gene.order$gene = droplevels(gene.order$gene)
	# Do the sorting
	gene.order = names(sort(unlist(lapply(split(gene.order$score, gene.order$gene), sum, na.rm=TRUE))))
	
	# Get the data.frame for plotting
	result.df = subset(results, gene %in% genes)
	result.df$gene = factor(result.df$gene, levels=gene.order)
	result.df$score.type = factor(result.df$score.type, levels=c("CNA", "Expr", "Meth", "Mut", "shRNA", "combined"))
	result.df$cancer = factor(result.df$cancer, levels=sort(unique(as.character(result.df$cancer))))
	
	# Overwrite the score column with the score type to make it categorical
	# Combined scores are not plotted later
	result.df[, 2] = as.character(result.df[, 2])
	result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 2] = as.character(result.df[which(!is.na(result.df[, 2]) & result.df[, 2] == "1"), 3])
	result.df[which(is.na(result.df[, 2]) | result.df[, 2] == "0"), 2] = "NONE"
	
	ggplot(subset(result.df, score.type != "combined" & gene %in% topgenes), aes(x=score.type, y=gene)) + 
	geom_tile(aes(fill=score), color="white", size=0.7) +
	scale_fill_manual(values=c(NONE="white", CNA="#888888", Expr="#E69F00", Meth="#56B4E9", Mut="#009E73", shRNA="#F0E442"), 
		          breaks=c("CNA", "Expr", "Meth", "Mut", "shRNA")) +
	labs(x="", y="") +
	facet_grid(.~cancer) + 
	theme(panel.background=element_rect(color="white", fill="white"),
	      panel.margin=unit(10, "points"),
	      axis.ticks=element_blank(),
	      axis.text.x=element_blank(),
	      axis.text.y=element_text(color="gray30", size=16, face="bold"),
	      axis.title.x=element_text(color="gray30", size=16, face="bold"),
	      strip.text.x=element_text(color="gray30", size=16, face="bold"),
	      legend.text=element_text(color="gray30", size=16, face="bold"),
	      legend.title=element_blank(),
	      legend.position="bottom")
	)
}


REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script bin exe console][
		script: temp-dir/red-console.red
		exe:	temp-dir/console
		
		bin: either slash = first system/options/boot [
			system/options/boot
		][
			join system/options/path system/options/boot
		]
		if Windows? [
			append exe %.exe
			if %.exe <> suffix? bin [append bin %.exe]
		]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < modified? bin				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
profiles <- read.csv("summary.csv", header=T)

print(profiles)

f2si2<-function (number, rounding=F, sep=" ") 
{
    lut <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-09, 1e-06, 
        0.001, 1, 1000, 1e+06, 1e+09, 1e+12, 1e+15, 1e+18, 1e+21, 
        1e+24)
    pre <- c("y", "z", "a", "f", "p", "n", "u", "m", "", "k", 
        "M", "G", "T", "P", "E", "Z", "Y")
    ix <- findInterval(number, lut)
    if (ix>0 && lut[ix]!=1) {
        if (rounding==T) {
         sistring <- paste(round(number/lut[ix]), pre[ix], sep=sep)
        }
        else {
         sistring <- paste(number/lut[ix], pre[ix], sep=sep)
        }
    }
    else {
        sistring <- as.character(number)
    }
    return(sistring)
}


png("profile-keys-analysis.png", height=500, width=800, pointsize=18)

par(mar=c(5,9,2,2)+0.1)
bplt <- barplot(profiles$suburi_keys, names.arg=profiles$profile_id, horiz=T, las=2, xlim=c(0, 500000), axes=F)
axis(1, at=c(0:10)*50000, labels=sapply(c(0:10)*50000, FUN=f2si2, rounding=T, sep=""))
text(x=profiles$suburi_keys, y=bplt, labels=sapply(profiles$suburi_keys, FUN=f2si2, rounding=T, sep=""), pos=4, offset=0.2, xpd=T)
title(xlab="Number of Sub-URI Keys")

dev.off()

xlb <- c("H1", "H2", "H3", "H4", "H5", "Hx", "P1", "P2", "P3", "P4", "P5", "Px")

png("profile-keys-line-analysis.png", height=500, width=800, pointsize=18)

par(mar=c(4,4,2,2)+0.1)
plot(profiles$suburi_keys, type='b', xaxt="n", yaxt="n", ylab="", xlab="")
axis(1, at=c(1:12), labels=xlb)
axis(2, at=c(0:10)*50000, labels=sapply(c(0:10)*50000, FUN=f2si2, rounding=T, sep=""))
title(ylab="Number of Sub-URI Keys", xlab="Max segments (H: Host segments, P: Path segments)")

dev.off()
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.
    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      data_restore_on_exit <- object$object$container$output$options$data
      label_restore_on_exit <- object$object$container$output$options$label
      on.exit(object$object$container$output$options$data <- data_restore_on_exit, add = TRUE)
      on.exit(object$object$container$output$opitons$label <- label_restore_on_exit, add = TRUE)
      object$object$container$output$options$data <- NULL
      object$object$container$output$options$label <- NULL
    } else {
      data_restore_on_exit <- object$output$options$data
      label_restore_on_exit <- object$output$options$label
      on.exit(object$output$options$data <- data_restore_on_exit, add = TRUE)
      on.exit(object$output$opitons$label <- label_restore_on_exit, add = TRUE)
      object$output$options$data <- NULL
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_data_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object <- list(data = object$object$container$output$options$data, 
                     label = object$object$container$output$options$label)
    } else {
      object <- list(data = object$output$options$data, 
                     label = object$output$options$label)
    }
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 'data')
}
# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3   = construct_s3_adapter,
                          r    = construct_R_adapter,
                          data = construct_data_adapter)
#!/usr/bin/env Rscript

library(ggplot2)
library(reshape)

hours_m = as.numeric(read.csv("analysis/time-hours-stats.csv",header=F,nrows=1))
hours_stdev = as.numeric(read.csv("analysis/time-hours-stats.csv",
                                  header=F,nrows=1,skip=1))

df <- data.frame(freqs=hours_m,stdev=hours_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=0:23,y=freqs)) +
  xlab("Hour of Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity') +
  #geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-hours-bar.png",width=7,height=6)

hours = read.csv("analysis/time-hours-full.csv",header=F)
p <- ggplot() +
  stat_ecdf(aes(x=hours[[1]])) +
  stat_ecdf(aes(x=hours[[2]])) +
  stat_ecdf(aes(x=hours[[3]])) +
  stat_ecdf(aes(x=hours[[4]])) +
  stat_ecdf(aes(x=hours[[5]])) +
  stat_ecdf(aes(x=hours[[6]])) +
  stat_ecdf(aes(x=hours[[7]])) +
  stat_ecdf(aes(x=hours[[8]])) +
  stat_ecdf(aes(x=hours[[9]])) +
  stat_ecdf(aes(x=hours[[10]])) +
  stat_ecdf(aes(x=hours[[11]])) +
  stat_ecdf(aes(x=hours[[12]])) +
  stat_ecdf(aes(x=hours[[13]])) +
  stat_ecdf(aes(x=hours[[14]])) +
  stat_ecdf(aes(x=hours[[15]])) +
  stat_ecdf(aes(x=hours[[16]])) +
  stat_ecdf(aes(x=hours[[17]])) +
  stat_ecdf(aes(x=hours[[18]])) +
  stat_ecdf(aes(x=hours[[19]])) +
  stat_ecdf(aes(x=hours[[20]])) +
  stat_ecdf(aes(x=hours[[21]])) +
  stat_ecdf(aes(x=hours[[22]])) +
  stat_ecdf(aes(x=hours[[23]])) +
  stat_ecdf(aes(x=hours[[24]])) +
  theme(legend.title=element_blank()) +
  xlab("Number of Hourly Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-hours-ecdf.png",width=7,height=6)

wdays_m = as.numeric(read.csv("analysis/time-wdays-stats.csv",header=F,nrows=1))
wdays_stdev = as.numeric(read.csv("analysis/time-wdays-stats.csv",
                                  header=F,nrows=1,skip=1))
wday_str = c("Mon","Tues","Weds","Thurs","Fri","Sat","Sun")
df <- data.frame(freqs = wdays_m, wdays = factor(wday_str,levels=wday_str),
                 stdev=wdays_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=wdays,y=freqs)) +
  xlab("Week Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(y=freqs)) +
  geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-wdays-bar.png",width=7,height=6)

wdays = read.csv("analysis/time-wdays-full.csv",header=F)
p <- ggplot() +
  stat_ecdf(data=data.frame(wdays[[1]]),aes(x=wdays[[1]],colour="m")) +
  stat_ecdf(data=data.frame(wdays[[2]]),aes(x=wdays[[2]],colour="t")) +
  stat_ecdf(data=data.frame(wdays[[3]]),aes(x=wdays[[3]],colour="w")) +
  stat_ecdf(data=data.frame(wdays[[4]]),aes(x=wdays[[4]],colour="th")) +
  stat_ecdf(data=data.frame(wdays[[5]]),aes(x=wdays[[5]],colour="f")) +
  stat_ecdf(data=data.frame(wdays[[6]]),aes(x=wdays[[6]],colour="s")) +
  stat_ecdf(data=data.frame(wdays[[7]]),aes(x=wdays[[7]],colour="su")) +
  scale_color_manual(
      name="",
      breaks = c("m","t","w","th","f","s","su"),
      values = c("m"="#CCE5FF", "t"="#99CCFF", "w"="#66B2FF", "th"="#3399FF",
                 "f"="#0080FF", "s"="#0066CC", "su"="#004C99"),
      labels = c("m"="Mon", "t"="Tues", "w"="Weds", "th"="Thurs", "f"="Fri",
                 "s"="Sat", "su"="Sun")
  ) +
  theme(legend.title=element_blank()) +
  xlab("Number of Daily Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-wdays-ecdf.png",width=7,height=6)

top_cmds = read.csv("analysis/top-cmds.csv",header=T)
df <- data.frame(
  freqs = top_cmds[[1]],
  cmd_names = factor(top_cmds[[2]],levels=top_cmds[[2]])
)
p <- ggplot(df,aes(x=cmd_names,y=freqs)) +
  xlab("Command") +
  ylab("Frequency") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
ggsave("plots/top-cmds.png",width=7,height=6)

cmd_lengths = as.numeric(read.csv("analysis/cmd-lengths.csv",header=F))
df = data.frame(cmd_lengths)
p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)),
      breaks=seq(0,max(df),10),
      minor_breaks=seq(0,max(df),5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-full.png",width=7,height=6)

p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)/3),
      breaks=seq(0,max(df)/3,10),
      minor_breaks=seq(0,max(df)/3,5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-zoomed.png",width=7,height=6)
REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script bin exe console][
		script: temp-dir/red-console.red
		exe:	temp-dir/console
		
		bin: either slash = first system/options/boot [
			system/options/boot
		][
			join system/options/home system/options/boot
		]
		if Windows? [
			append exe %.exe
			if %.exe <> suffix? bin [append bin %.exe]
		]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < modified? bin				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object$output$options$data <- NULL
      object$output$options$label <- NULL
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_data_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
      object <- list(data = object$output$options$data, 
                     label = object$output$options$label)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}
# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3   = construct_s3_adapter,
                          r    = construct_R_adapter,
                          data = construct_data_adapter)
#!/usr/bin/env Rscript

library(ggplot2)
library(reshape)

hours_m = as.numeric(read.csv("analysis/time-hours-stats.csv",header=F,nrows=1))
hours_stdev = as.numeric(read.csv("analysis/time-hours-stats.csv",
                                  header=F,nrows=1,skip=1))

df <- data.frame(freqs=hours_m,stdev=hours_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=0:23,y=freqs)) +
  xlab("Hour of Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity') +
  #geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-hours-bar.png",width=7,height=6)

hours = read.csv("analysis/time-hours-full.csv",header=F)
p <- ggplot() +
  stat_ecdf(aes(x=hours[[1]])) +
  stat_ecdf(aes(x=hours[[2]])) +
  stat_ecdf(aes(x=hours[[3]])) +
  stat_ecdf(aes(x=hours[[4]])) +
  stat_ecdf(aes(x=hours[[5]])) +
  stat_ecdf(aes(x=hours[[6]])) +
  stat_ecdf(aes(x=hours[[7]])) +
  stat_ecdf(aes(x=hours[[8]])) +
  stat_ecdf(aes(x=hours[[9]])) +
  stat_ecdf(aes(x=hours[[10]])) +
  stat_ecdf(aes(x=hours[[11]])) +
  stat_ecdf(aes(x=hours[[12]])) +
  stat_ecdf(aes(x=hours[[13]])) +
  stat_ecdf(aes(x=hours[[14]])) +
  stat_ecdf(aes(x=hours[[15]])) +
  stat_ecdf(aes(x=hours[[16]])) +
  stat_ecdf(aes(x=hours[[17]])) +
  stat_ecdf(aes(x=hours[[18]])) +
  stat_ecdf(aes(x=hours[[19]])) +
  stat_ecdf(aes(x=hours[[20]])) +
  stat_ecdf(aes(x=hours[[21]])) +
  stat_ecdf(aes(x=hours[[22]])) +
  stat_ecdf(aes(x=hours[[23]])) +
  stat_ecdf(aes(x=hours[[24]])) +
  theme(legend.title=element_blank()) +
  xlab("Number of Hourly Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-hours-ecdf.png",width=7,height=6)

wdays_m = as.numeric(read.csv("analysis/time-wdays-stats.csv",header=F,nrows=1))
wdays_stdev = as.numeric(read.csv("analysis/time-wdays.csv",header=F,nrows=1,skip=1))
wday_str = c("Mon","Tues","Weds","Thurs","Fri","Sat","Sun")
df <- data.frame(freqs = wdays_m, wdays = factor(wday_str,levels=wday_str),
                 stdev=wdays_stdev)
limits <- aes(ymax = freqs + stdev, ymin=freqs - stdev)
p <- ggplot(df,aes(x=wdays,y=freqs)) +
  xlab("Week Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(y=freqs)) +
  #geom_errorbar(limits, width=0.25) +
  theme_bw()
ggsave("plots/time-wdays-bar.png",width=7,height=6)

wdays = read.csv("analysis/time-wdays-full.csv",header=F)
p <- ggplot() +
  stat_ecdf(data=data.frame(wdays[[1]]),aes(x=wdays[[1]],colour="m")) +
  stat_ecdf(data=data.frame(wdays[[2]]),aes(x=wdays[[2]],colour="t")) +
  stat_ecdf(data=data.frame(wdays[[3]]),aes(x=wdays[[3]],colour="w")) +
  stat_ecdf(data=data.frame(wdays[[4]]),aes(x=wdays[[4]],colour="th")) +
  stat_ecdf(data=data.frame(wdays[[5]]),aes(x=wdays[[5]],colour="f")) +
  stat_ecdf(data=data.frame(wdays[[6]]),aes(x=wdays[[6]],colour="s")) +
  stat_ecdf(data=data.frame(wdays[[7]]),aes(x=wdays[[7]],colour="su")) +
  scale_color_manual(
      name="",
      breaks = c("m","t","w","th","f","s","su"),
      values = c("m"="#CCE5FF", "t"="#99CCFF", "w"="#66B2FF", "th"="#3399FF",
                 "f"="#0080FF", "s"="#0066CC", "su"="#004C99"),
      labels = c("m"="Mon", "t"="Tues", "w"="Weds", "th"="Thurs", "f"="Fri",
                 "s"="Sat", "su"="Sun")
  ) +
  theme(legend.title=element_blank()) +
  xlab("Number of Daily Commands") +
  ylab("") +
  theme_bw()
ggsave("plots/time-wdays-ecdf.png",width=7,height=6)

top_cmds = read.csv("analysis/top-cmds.csv",header=T)
df <- data.frame(
  freqs = top_cmds[[1]],
  cmd_names = factor(top_cmds[[2]],levels=top_cmds[[2]])
)
p <- ggplot(df,aes(x=cmd_names,y=freqs)) +
  xlab("Command") +
  ylab("Frequency") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
ggsave("plots/top-cmds.png",width=7,height=6)

cmd_lengths = as.numeric(read.csv("analysis/cmd-lengths.csv",header=F))
df = data.frame(cmd_lengths)
p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)),
      breaks=seq(0,max(df),10),
      minor_breaks=seq(0,max(df),5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-full.png",width=7,height=6)

p <- ggplot() +
  stat_ecdf(data=df,aes(x=cmd_lengths)) +
  xlab("Base Command Length") +
  ylab("") +
  scale_x_continuous(
      limits=c(0,max(df)/3),
      breaks=seq(0,max(df)/3,10),
      minor_breaks=seq(0,max(df)/3,5)
  ) +
  theme_bw()
ggsave("plots/cmd-lengths-zoomed.png",width=7,height=6)
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    object$output$options$data <- NULL
    object$output$options$label <- NULL
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

#' Construct an Amazon Web Services S3 data adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes data to Amazon's S3.
construct_data_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = list(data = object$output$options$data, 
                            label = object$output$options$label), 
                 name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- paste(opts$s3path, "data", "label", 
        sep = "_")
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}
# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3   = construct_s3_adapter,
                          r    = construct_R_adapter,
                          data = construct_data_adapter)
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141220_1214"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  ###
  # BE AWARE: hard-coded switching from 'memory savings in %' to 'speedup factor'.
  ##
  # memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)
  memorySavingComparedToTheOther <- (theOther$footprintInBytes_median / ours$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}

# http://stackoverflow.com/questions/11340444/is-there-an-r-function-to-format-number-using-unit-prefix
formatCsUnits__ <- function (number,rounding=T) 
{
  lut <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-09, 1e-06, 
           0.001, 1, 1000, 1e+06, 1e+09, 1e+12, 1e+15, 1e+18, 1e+21, 
           1e+24)
  pre <- c("y", "z", "a", "f", "p", "n", "u", "m", "", "K", 
           "M", "G", "T", "P", "E", "Z", "Y")
  ix <- findInterval(number, lut)
  if (lut[ix]!=1) {
    if (rounding==T) {
      sistring <- paste(formatC(number/lut[ix], digits=0, format="f"),pre[ix], sep="")
    }
    else {
      sistring <- paste(formatC(number/lut[ix], digits=0, format="f"), pre[ix], sep="")
    } 
  }
  else {
    sistring <- paste(round(number, digits=0))
  }
  return(sistring)
}

formatCsUnits <- Vectorize(formatCsUnits__)

formatFactor__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    digits = 2
    
    if (rounding==T) {
      x <- format(round(arg, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(arg, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatFactor <- Vectorize(formatFactor__)

formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  arg_fmt <- formatFactor(arg, rounding=T)
  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg_fmt, "}$", sep = "")
  } else {
    paste("$", arg_fmt, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

### 
# Cache Statistics
##
benchmarksPerfStatFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "perf-stat", "log", sep=".")
benchmarksPerfStat <- read.csv(benchmarksPerfStatFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarksPerfStat) <- c("L1_REF", "L1_MISSES", "L2_REF", "L2_HIT", "L3_REF", "L3_MISSES")

benchmarksPerfStat$L2_MISSES <- benchmarksPerfStat$L2_REF - benchmarksPerfStat$L2_HIT

benchmarksPerfStat$L1_HIT <- benchmarksPerfStat$L1_REF - benchmarksPerfStat$L1_MISSES
benchmarksPerfStat$L3_HIT <- benchmarksPerfStat$L3_REF - benchmarksPerfStat$L3_MISSES

benchmarksPerfStat$L1_HIT_RATE <- benchmarksPerfStat$L1_HIT / benchmarksPerfStat$L1_REF
benchmarksPerfStat$L2_HIT_RATE <- benchmarksPerfStat$L2_HIT / benchmarksPerfStat$L2_REF
benchmarksPerfStat$L3_HIT_RATE <- benchmarksPerfStat$L3_HIT / benchmarksPerfStat$L3_REF

benchmarksPerfStat$L1_MISS_RATE <- 1 - benchmarksPerfStat$L1_HIT_RATE
benchmarksPerfStat$L2_MISS_RATE <- 1 - benchmarksPerfStat$L2_HIT_RATE
benchmarksPerfStat$L3_MISS_RATE <- 1 - benchmarksPerfStat$L3_HIT_RATE

#data.frame(benchmarksCleaned, benchmarksPerfStat)


#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(data.frame(benchmarksCleaned, benchmarksPerfStat), id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)



###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- dataFormatter(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# ###
# # Results as saving percentags
# ##
# measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
# measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')
# dataFormatter <- latexMathPercent
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)

# ###
# # Results as speedup factors
# ##
# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# dataFormatter <- latexMathFactor
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)


createCacheStatTable <- function(input, dataType, dataStructureOrigin, measureVars, benchmarkName, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Benchmark == benchmarkName & input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
  
  my_ylim <- range(0, 1.0)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT_RATE, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT_RATE, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT_RATE)
  boxplot(ylim=my_ylim, benchmarksCast$VF_SCALA_L1_HIT_RATE, benchmarksCast$VF_SCALA_L2_HIT_RATE, benchmarksCast$VF_SCALA_L3_HIT_RATE)
  boxplot(ylim=my_ylim, benchmarksCast$VF_CLOJURE_L1_HIT_RATE, benchmarksCast$VF_CLOJURE_L2_HIT_RATE, benchmarksCast$VF_CLOJURE_L3_HIT_RATE)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT_RATE, benchmarksCast$VF_SCALA_L1_HIT_RATE, benchmarksCast$VF_CLOJURE_L1_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_HIT, benchmarksCast$VF_SCALA_L1_HIT, benchmarksCast$VF_CLOJURE_L1_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_REF, benchmarksCast$VF_SCALA_L1_REF, benchmarksCast$VF_CLOJURE_L1_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L1_MISSES, benchmarksCast$VF_SCALA_L1_MISSES, benchmarksCast$VF_CLOJURE_L1_MISSES)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT_RATE, benchmarksCast$VF_SCALA_L2_HIT_RATE, benchmarksCast$VF_CLOJURE_L2_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_HIT, benchmarksCast$VF_SCALA_L2_HIT, benchmarksCast$VF_CLOJURE_L2_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_REF, benchmarksCast$VF_SCALA_L2_REF, benchmarksCast$VF_CLOJURE_L2_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L2_MISSES, benchmarksCast$VF_SCALA_L2_MISSES, benchmarksCast$VF_CLOJURE_L2_MISSES)
  
  boxplot(ylim=my_ylim, benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT_RATE, benchmarksCast$VF_SCALA_L3_HIT_RATE, benchmarksCast$VF_CLOJURE_L3_HIT_RATE)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_HIT, benchmarksCast$VF_SCALA_L3_HIT, benchmarksCast$VF_CLOJURE_L3_HIT)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_REF, benchmarksCast$VF_SCALA_L3_REF, benchmarksCast$VF_CLOJURE_L3_REF)
  boxplot(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_L3_MISSES, benchmarksCast$VF_SCALA_L3_MISSES, benchmarksCast$VF_CLOJURE_L3_MISSES)
  
  sel <- c("Param_size", "Param_valueFactoryFactory", "L3_MISSES")
  tmp <- dcast(input[input$Benchmark == benchmarkName & input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size + Param_valueFactoryFactory ~ variable)[sel]  
  # tmp[,3:NCOL(tmp)] <- round(tmp[,3:NCOL(tmp)], 2)
  tmp[,3:NCOL(tmp)] <- formatCsUnits(tmp[,3:NCOL(tmp)])
  
  
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
  
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
#   tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
#   tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)
  
  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  
  
  
#   ###
#   # Create boxplots as well
#   ##
#   outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
#   fontScalingFactor <- 1.2
#   pdf(outFileName, family = "Times", width = 10, height = 3)
#   
#   selection <- tableAll[2:NCOL(tableAll)]
#   names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
#   
#   par(mar = c(3.5,4.75,0,0) + 0.1)
#   par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
#   
#   boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
#           cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
#   
#   z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
#   zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
#   par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
#   axis(2, at=z, labels=zz, las=2,
#        cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
#   
#   #   abline(v =  5.5)
#   
#   #abline(h =  0.75, lty=3)
#   #abline(h =  0.5, lty=3)
#   #abline(h =  0.25, lty=3)
#   abline(h =  0)
#   abline(h = -0.5, lty=3)
#   dev.off()
#   embed_fonts(outFileName)
  
}

###
# Results as speedup factors
##
measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
dataFormatter <- latexMathFactor

createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "EntryIteration", dataFormatter)
createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "Iteration", dataFormatter)
createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, "EqualsRealDuplicate", dataFormatter)

# createCacheStatTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createCacheStatTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createCacheStatTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # Hack for model object requiring customized
    # serializer, e.g., xgb.Booster
    if (is(object, 'tundraContainer') &&
        is(object$output$model, 'xgb.Booster')) {
			object <- serialize_xgb_object(object)
    }

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script bin exe console][
		script: temp-dir/red-console.red
		exe:	temp-dir/console
		bin:	join system/options/home system/options/boot
		
		if Windows? [
			append exe %.exe
			append bin %.exe
		]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < modified? bin				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
0.4.3#!/usr/bin/env Rscript

# library(extrafont) # First time: Run font_import() in R shell.
# loadfonts()

library(ggplot2)
library(reshape)

hours_m = as.numeric(read.csv("analysis/time-hours.csv",header=F,nrows=1))
hours_stdev = as.numeric(read.csv("analysis/time-hours.csv",header=F,nrows=1,skip=1))

p <- ggplot() +
  xlab("Hour of Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(x=0:23.,y=hours_m)) +
  theme_bw()
  # TODO: Error bars.
ggsave("plots/time-hours.png",width=7,height=6)

wdays_m = as.numeric(read.csv("analysis/time-wdays.csv",header=F,nrows=1))
wdays_stdev = as.numeric(read.csv("analysis/time-wdays.csv",header=F,nrows=1,skip=1))
wday_str = c("Mon","Tues","Weds","Thurs","Fri","Sat","Sun")
df <- data.frame(freqs = wdays_m, wdays = factor(wday_str,levels=wday_str))
p <- ggplot(df,aes(x=wdays,y=freqs)) +
  xlab("Week Day") +
  ylab("Average Commands Executed") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
  # TODO: Error bars.
ggsave("plots/time-wdays.png",width=7,height=6)

top_cmds = read.csv("analysis/top-cmds.csv",header=T)
df <- data.frame(
  freqs = top_cmds[[1]],
  cmd_names = factor(top_cmds[[2]],levels=top_cmds[[2]])
)
p <- ggplot(df,aes(x=cmd_names,y=freqs)) +
  xlab("Command") +
  ylab("Frequency") +
  geom_bar(stat='identity',aes(y=freqs)) +
  theme_bw()
ggsave("plots/top-cmds.png",width=7,height=6)
REBOL [
	Title:   "Red command-line front-end"
	Author:  "Nenad Rakocevic, Andreas Bolka"
	File: 	 %red.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic, Andreas Bolka. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
	Usage:   {
		do/args %red.r "path/source.red"
	}
	Encap: [quiet secure none title "Red" no-window] 
]

unless value? 'encap-fs [do %system/utils/encap-fs.r]

unless all [value? 'red object? :red][
	do-cache %compiler.r
]

redc: context [

	Windows?: system/version/4 = 3
	
	if encap? [
		temp-dir: switch/default system/version/4 [
			2 [											;-- MacOS X
				libc: load/library %libc.dylib
				sys-call: make routine! [cmd [string!]] libc "system"
				%/tmp/red/
			]
			3 [											;-- Windows
				either lib?: find system/components 'Library [
					sys-path: to-rebol-file get-env "SystemRoot"
					shell32: load/library sys-path/System32/shell32.dll
					libc:  	 load/library sys-path/System32/msvcrt.dll

					CSIDL_COMMON_APPDATA: to integer! #{00000023}

					SHGetFolderPath: make routine! [
							hwndOwner 	[integer!]
							nFolder		[integer!]
							hToken		[integer!]
							dwFlags		[integer!]
							pszPath		[string!]
							return: 	[integer!]
					] shell32 "SHGetFolderPathA"

					sys-call: make routine! [cmd [string!] return: [integer!]] libc "system"

					path: head insert/dup make string! 255 null 255
					unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [
						fail "SHGetFolderPath failed: can't determine temp folder path"
					]
					append dirize to-rebol-file trim path %Red/
				][
					sys-call: func [cmd][call/wait cmd]
					append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/
				]
			]
		][												;-- Linux (default)
			any [
				exists? libc: %libc.so.6
				exists? libc: %/lib32/libc.so.6
				exists? libc: %/lib/i386-linux-gnu/libc.so.6	; post 11.04 Ubuntu
				exists? libc: %/usr/lib32/libc.so.6				; e.g. 64-bit Arch Linux
				exists? libc: %/lib/libc.so.6
				exists? libc: %/System/Index/lib/libc.so.6  	; GoboLinux package
				exists? libc: %/system/index/framework/libraries/libc.so.6  ; Syllable
				exists? libc: %/lib/libc.so.5
			]
			libc: load/library libc
			sys-call: make routine! [cmd [string!]] libc "system"
			%/tmp/red/
		]
	]
	
	;; Select a default target based on the REBOL version.
	default-target: does [
		any [
			select [
				2 "Darwin"
				3 "MSDOS"
				4 "Linux"
				7 "FreeBSD"
			] system/version/4
			"MSDOS"
		]
	]

	fail: func [value] [
		print value
		if system/options/args [quit/return 1]
		halt
	]

	fail-try: func [component body /local err] [
		if error? set/any 'err try body [
			err: disarm err
			foreach w [arg1 arg2 arg3][
				set w either unset? get/any in err w [none][
					get/any in err w
				]
			]
			fail [
				"***" component "Internal Error:"
				system/error/(err/type)/type #":"
				reduce system/error/(err/type)/(err/id) newline
				"*** Where:" mold/flat err/where newline
				"*** Near: " mold/flat err/near newline
			]
		]
	]
	
	format-time: func [time [time!]][
		round (time/second * 1000) + (time/minute * 60000)
	]

	load-filename: func [filename /local result] [
		unless any [
			all [
				#"%" = first filename
				attempt [result: load filename]
				file? result
			]
			attempt [result: to-rebol-file filename]
		] [
			fail ["Invalid filename:" filename]
		]
		result
	]

	load-targets: func [/local targets] [
		targets: load-cache %system/config.r
		if exists? %system/custom-targets.r [
			insert targets load %system/custom-targets.r
		]
		targets
	]
	
	red-system?: func [file [file!] /local ws rs?][
		ws: charset " ^-^/^M"
		parse/all/case read file [
			some [
				thru "Red"
				opt ["/System" (rs?: yes)]
				any ws 
				#"[" (return to logic! rs?)
				to end
			]
		]
		no
	]
	
	safe-to-local-file: func [file [file!]][
		if all [
			find file: to-local-file file #" "
			Windows?
		][
			file: rejoin [{"} file {"}]					;-- avoid issues with blanks in path
		]
		file
	]
	
	run-console: func [/with file [string!] /local opts result script exe console][
		script: temp-dir/red-console.red
		exe: temp-dir/console
		
		if Windows? [append exe %.exe]
		
		unless exists? temp-dir [make-dir temp-dir]
		
		if any [
			not exists? exe 
			(modified? exe) < build-date				;-- check that console is up to date.
		][
			console: %environment/console/
			write script read-cache console/console.red
			write temp-dir/help.red read-cache console/help.red
			write temp-dir/input.red read-cache console/input.red

			opts: make system-dialect/options-class [	;-- minimal set of compilation options
				link?: yes
				unicode?: yes
				config-name: to word! default-target
				build-basename: %console
				build-prefix: temp-dir
				red-help?: yes							;-- include doc-strings
			]
			opts: make opts select load-targets opts/config-name

			print "Pre-compiling Red console..."
			result: red/compile script opts
			system-dialect/compile/options/loaded script opts result/1
			
			delete script
			delete temp-dir/help.red
			delete temp-dir/input.red
			
			if all [Windows? not lib?][
				print "Please run red.exe again to access the console."
				quit/return 1
			]
		]
		exe: safe-to-local-file exe
		if with [repend exe [#" " file]]
		sys-call exe									;-- replace the buggy CALL native
		quit/return 0
	]

	parse-options: has [
		args src opts output target verbose filename config config-name base-path type
		mode target?
	] [
		args: any [
			system/options/args
			parse any [system/script/args ""] none
		]
		target: default-target
		opts: make system-dialect/options-class [link?: yes]

		parse/case args [
			any [
				  ["-c"	| "--compile"]		(type: 'exe)
				| ["-r" | "--no-runtime"]   (opts/runtime?: no)		;@@ overridable by config!
				| ["-d" | "--debug" | "--debug-stabs"]	(opts/debug?: yes)
				| ["-o" | "--output"]  		set output skip
				| ["-t" | "--target"]  		set target skip (target?: yes)
				| ["-v" | "--verbose"] 		set verbose skip	;-- 1-3: Red, >3: Red/System
				| ["-h" | "--help"]			(mode: 'help)
				| ["-V" | "--version"]		(mode: 'version)
				| "--red-only"				(opts/red-only?: yes)
				| ["-dlib" | "--dynamic-lib"] (type: 'dll)
				;| ["-slib" | "--static-lib"] (type 'lib)
			]
			set filename skip (src: load-filename filename)
		]
		
		if mode [
			switch mode [
				help	[print read-cache %usage.txt]
				version [print load-cache %version.r]
			]
			quit/return 0
		]

		;; Process -t/--target first, so that all other command-line options
		;; can potentially override the target config settings.
		unless config: select load-targets config-name: to word! trim target [
			fail ["Unknown target:" target]
		]
		base-path: either encap? [
			system/options/path
		][
			system/script/parent/path
		]
		opts: make opts config
		opts/config-name: config-name
		opts/build-prefix: base-path

		;; Process -o/--output (if any).
		if output [
			either slash = last output [
				attempt [opts/build-prefix: to-rebol-file output]
			][
				opts/build-basename: load-filename output
				if slash = first opts/build-basename [
					opts/build-prefix: %""
				]
			]
		]

		;; Process -v/--verbose (if any).
		if verbose [
			unless attempt [opts/verbosity: to integer! trim verbose] [
				fail ["Invalid verbosity:" verbose]
			]
		]
		
		;; Process -dlib/--dynamic-lib (if any).
		if any [type = 'dll opts/type = 'dll][
			if type = 'dll [opts/type: type]
			if opts/OS <> 'Windows [opts/PIC?: yes]
		]
		
		;; Check common syntax mistakes
		if all [
			any [type output verbose target?]			;-- -c | -o | -dlib | -t | -v
			none? src
		][
			fail "Source file is missing"
		]
		if all [output output/1 = #"-"][				;-- -o (not followed by option)
			fail "Missing output file or path"
		]
		
		;; Process input sources.
		unless src [
			either encap? [
				run-console
			][
				fail "No source files specified."
			]
		]
		
		if all [encap? none? output none? type][
			run-console/with filename
		]
		
		if slash <> first src [							;-- if relative path
			src: clean-path join base-path src			;-- add working dir path
		]
		unless exists? src [
			fail ["Cannot access source file:" src]
		]

		reduce [src opts]
	]

	main: has [src opts build-dir result saved rs? prefix] [
		set [src opts] parse-options
		
		rs?: red-system? src

		;; If we use a build directory, ensure it exists.
		if all [prefix: opts/build-prefix find prefix %/] [
			build-dir: copy/part prefix find/last prefix %/
			unless attempt [make-dir/deep build-dir] [
				fail ["Cannot access build dir:" build-dir]
			]
		]
		
		print [
			newline
			"-=== Red Compiler" read-cache %version.r "===-" newline newline
			"Compiling" src "..."
		]
		
		unless rs? [
	;--- 1st pass: Red compiler ---
			
			fail-try "Red Compiler" [
				result: red/compile src opts
			]
			print ["...compilation time :" format-time result/2 "ms"]
			if opts/red-only? [exit]
		]
		
	;--- 2nd pass: Red/System compiler ---
		
		print [
			newline
			"Compiling to native code..."
		]
		fail-try "Red/System Compiler" [
			unless encap? [change-dir %system/]
			result: either rs? [
				system-dialect/compile/options src opts
			][
				opts/unicode?: yes							;-- force Red/System to use Red's Unicode API
				opts/verbosity: max 0 opts/verbosity - 3	;-- Red/System verbosity levels upped by 3
				system-dialect/compile/options/loaded src opts result/1
			]
			unless encap? [change-dir %../]
		]
		print ["...compilation time :" format-time result/1 "ms"]
		
		if result/2 [
			print [
				"...linking time     :" format-time result/2 "ms^/"
				"...output file size :" result/3 "bytes^/"
				"...output file      :" to-local-file result/4
			]
		]
		unless Windows? [print ""]							;-- extra LF for more readable output
	]

	fail-try "Driver" [main]
	if encap? [quit/return 0]
]
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141218_0337"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  ###
  # BE AWARE: hard-coded switching from 'memory savings in %' to 'speedup factor'.
  ##
  # memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)
  memorySavingComparedToTheOther <- (theOther$footprintInBytes_median / ours$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}

formatFactor__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    digits = 2
    
    if (rounding==T) {
      x <- format(round(arg, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(arg, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatFactor <- Vectorize(formatFactor__)

formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  arg_fmt <- formatFactor(arg, rounding=T)
  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg_fmt, "}$", sep = "")
  } else {
    paste("$", arg_fmt, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars, dataFormatter) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- dataFormatter(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- dataFormatter(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- dataFormatter(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# ###
# # Results as saving percentags
# ##
# measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
# measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')
# dataFormatter <- latexMathPercent
# 
# createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
# createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)

###
# Results as speedup factors
##
measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')
dataFormatter <- latexMathFactor

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala, dataFormatter)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure, dataFormatter)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala, dataFormatter)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure, dataFormatter)
library(pbdMPI, quiet = TRUE)
library(pbdDMAT, quiet = TRUE)
library(pbdADIOS, quiet = TRUE)
library(raster, quiet=TRUE)
library(ggplot2, quiet=TRUE)
library(grid, quiet=TRUE)

## begin function definitions
adios.init <- function(method="ADIOS_READ_METHOD_BP", par="verbose=3")
{
    invisible(adios.read.init.method("ADIOS_READ_METHOD_BP",
                                     params="verbose=3"))
}

adios.open <- function(file, timeout=1, method="ADIOS_READ_METHOD_BP",
                       lockmode="ADIOS_LOCKMODE_NONE")
{
    ## timeout default is 1 sec
    pt <- adios.read.open(file, adios.timeout=timeout, "ADIOS_READ_METHOD_BP",
                          adios.lockmode="ADIOS_LOCKMODE_NONE")
    if(comm.rank() == 0) bpls <- system(paste("bpls", file), intern=TRUE)
    else bpls <- NULL
    bpls <- bcast(bpls)
    list(pt=pt, bpls=bpls)
}

raster_plot <- function(x, nrow, ncol, basename="raster", sequence=1, swidth=3)
{
    x <- data.frame(rasterToPoints(raster(matrix(x, nrow, ncol),
                                          xmn=0, xmx=ncol, ymn=0, ymx=nrow)))
    names(x) <- c("x", "y", basename)
    png(paste(basename, "_", formatC(sequence, width=swidth, flag=0), "_",
              comm.rank(), ".png", sep=""))
    print(ggplot(x, aes_string(x="x", y="y", fill=basename)) + geom_raster() +
          theme_minimal() + theme(axis.text.x=element_blank(),
                                  axis.ticks.x=element_blank(),
                                  axis.title.x=element_blank(),
                                  legend.position="none",
                                  plot.margin=unit(c(0,0,0,0),"cm")
                                  )
          )
    dev.off()
}
## end function definitions

init.grid()
adios.init()

## specify and open file for reading
dir.data <- "/lustre/atlas/scratch/ost/stf006/heat"
file <- paste(dir.data, "heat.bp", sep="/")
file.ptr <- adios.open(file)

## select variable to read
variable <- "T"

## get variable dimensions
varinfo = adios.inq.var(file.ptr$pt, variable)
block <- adios.inq.var.blockinfo(file.ptr$pt, varinfo)
ndim <- custom.inq.var.ndim(varinfo)
dims <- custom.inq.var.dims(varinfo)

## get dimensions and split
source("pbdADIOS/tests/partition.r")
g.dim <- dims
split <- c(TRUE, FALSE)
my.data.partition <- data.partition(seq(0, 0, along.with=g.dim), g.dim, split)
my.dim <- my.count <- my.data.partition$my.dim
my.start <- my.data.partition$my.start
my.grid <- my.data.partition$my.grid

## partition across first dimension (expects at least 2d)
slice_size0 <- as.integer(dims[1] %/% comm.size())
slice_size <- slice_size0
if(comm.rank() == (comm.size() - 1))
    slice_size <- as.integer(slice_size + (dims[1] %% comm.size()))
start <- c(as.integer(comm.rank() * slice_size0), rep(0, ndim - 1))
count <- c(slice_size, as.integer(dims[2:ndim]))

errno <- 0 # Default value 0
steps <- 0
retval <- 0
bufsize <- 10
buffer <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a0 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a1 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
a2 <- matrix(NA, ncol=prod(my.count), nrow=bufsize)
rhs <- cbind(rep(1, bufsize), poly(1:bufsize, degree=2))

while(errno != -21) { ## This is hard-coded for now. -21=err_end_of_stream
    steps = steps + 1 ## Double check with Norbert. Should it start with 1 or 2

    ## set reading bounding box
    adios.selection  <- adios.selection.boundingbox(ndim, my.start, my.count)
    comm.print("Selection.boundingbox complete ...")
    
    ## schedule the read
    adios.data <- adios.schedule.read(varinfo, my.start, my.count, file.ptr$pt,
                                      adios.selection, variable, 0, 1)
    comm.print("Schedule read complete ...")
    
    ## perform the read
    adios.perform.reads(file.ptr$pt, 1)
    comm.print("Perform read complete ...")

    data_chunk <- custom.data.access(adios.data, adios.selection, varinfo)
    comm.print("Data access complete ...")

    ## print a few to verify
    comm.cat("first 5:", head(data_chunk, 5),"\n")
    comm.cat("last 5:", tail(data_chunk, 5),"\n")

    ## shape into matrix with first dim as rows
    ## local reshape dimensions
    my.ncol <- prod(my.dim[2])
    my.nrow <- my.dim[1]
    ldim <- c(my.nrow, my.ncol)

    ## global reshape dimensions
    g.ncol <- prod(g.dim[2])
    g.nrow <- g.dim[1]
    gdim <- c(g.nrow, g.ncol)
    
    ## now glue into a ddmatrix
    ##  x <- matrix(data_chunk, nrow=my.nrow, ncol=my.ncol, byrow=FALSE)
    ##  X <- new("ddmatrix", Data=x, dim=gdim, ldim=ldim, bldim=ldim, ICTXT=2)

    ## Fit a quadratic to a moving window of 10 steps
    ## Actually don't need the ddmatrix for this and can go straight
    ## from data_chunk into buffer matrix
    buffer <- rbind(buffer[-1, ], data_chunk)

    ## plot the original local matrix (swapping row to col - C to R)
    raster_plot(data_chunk, my.ncol, my.nrow, "T", steps)
    
    if(steps >= bufsize)
        {
            fit <- lm.fit(rhs, buffer)$coefficients
            raster_plot(fit[1, ], my.ncol, my.nrow, "a0", steps)
            raster_plot(fit[2, ], my.ncol, my.nrow, "a1", steps)
            raster_plot(fit[3, ], my.ncol, my.nrow, "a2", steps)
        }
    
    ## All these work fine!
    ##    X <- as.blockcyclic(X, bldim=c(4, 4))
    ##    X.pc <- prcomp(X)
    ##    comm.print(X.pc)
    
    s <- sum(data_chunk)
    n <- length(data_chunk)
    sa <- allreduce(s)
    na <- allreduce(n)
    comm.cat(comm.rank(), "mean =", sa/na, "lmean =", s/n, "ln =", n, "\n",
             quiet=TRUE, all.rank=TRUE)

    ##
    ## Here, write out the results of the analysis
    ## For testing purposes, write the data.chunk back.
    ##
    
    ## try to get more data
    adios.advance.step(file.ptr$pt, 0, adios.timeout.sec=1)
    comm.print(paste("Done advance.step", steps, "..."))
     
    ## check errors
    errno <- adios.errno()
    comm.cat("Error Num",errno, "\n")

    ## if error is timeout (or EOF)
    if(errno == -22){ #-22 = err_step_notready
        comm.cat(comm.rank(), "Timeout waiting for more data. Quitting ...\n")
        break
    }
if(steps > 20) break
} # While end 

comm.print("Broke out of loop ...")
adios.read.close(file.ptr$pt)
comm.print("File closed")
adios.read.finalize.method("ADIOS_READ_METHOD_BP")
comm.print("Finalized adios ...")
finalize() # pbdMPI finalize

library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=TRUE, add.comment=TRUE, 
                               add.row.margin=TRUE, add.col.margin=TRUE,
                               style=None) {
  #print(str(tabular))
  
  if ( is.null(caption(tabular)) ) { add.caption  <- FALSE}
  if ( is.null(col.margin(tabular)) ) { col.margin  <- FALSE}
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------

  caption <- attr(tabular, 'caption')
  col.margin <- attr(tabular, 'col.margin')
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  attr(tabular, 'caption') <- caption
  attr(tabular, 'col.margin') <- col.margin
  rm(caption, col.margin)
  
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- caption(tabular)
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(as.data.frame(as.vector(col.margin(tabular))))
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000", halign='right')
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = sheet, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = sheet, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = sheet, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1, spacer_rows=2) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 1 + spacer_rows
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#!/usr/bin/env Rscript

# Parse the --file= argument out of command line args and
# determine where base directory is so that we can source
# our common sub-routines
arg0 <- sub("--file=(.*)", "\\1", grep("--file=", commandArgs(), value = TRUE))
dir0 <- dirname(arg0)
source(file.path(dir0, "common.r"))

theme_set(theme_grey(base_size = 17))

# Setup parameters for the script
params = matrix(c(
  'help',    'h', 0, "logical",
  'width',   'x', 2, "integer",
  'height',  'y', 2, "integer",
  'outfile', 'o', 2, "character",
  'indir',   'i', 2, "character",
  'tstart',  '1',  2, "integer",
  'tend',    '2',  2, "integer",
  'ylabel1stgraph', 'Y',  2, "character"
  ), ncol=4, byrow=TRUE)

# Parse the parameters
opt = getopt(params)

if (!is.null(opt$help))
  {
    cat(paste(getopt(params, command = basename(arg0), usage = TRUE)))
    q(status=1)
  }

# Initialize defaults for opt
if (is.null(opt$width))   { opt$width   = 1280 }
if (is.null(opt$height))  { opt$height  = 960 }
if (is.null(opt$indir))   { opt$indir  = "current"}
if (is.null(opt$outfile)) { opt$outfile = file.path(opt$indir, "summary.png") }
if (is.null(opt$ylabel1stgraph)) { opt$ylabel1stgraph = "Op/sec" }

# Load the benchmark data, passing the time-index range we're interested in
b = load_benchmark(opt$indir, opt$tstart, opt$tend)

# If there is no actual data available, bail
if (nrow(b$latencies) == 0)
{
  stop("No latency information available to analyze in ", opt$indir)
}

png(file = opt$outfile, width = opt$width, height = opt$height)

# First plot req/sec from summary
plot1 <- qplot(elapsed, successful / window, data = b$summary,
                geom = c("smooth", "point"),
                xlab = "Elapsed Secs", ylab = opt$ylabel1stgraph,
                main = "Throughput") +

                geom_smooth(aes(y = successful / window, colour = "ok"), size=0.5) +
                geom_point(aes(y = successful / window, colour = "ok"), size=2.0) +

                geom_smooth(aes(y = failed / window, colour = "error"), size=0.5) +
                geom_point(aes(y = failed / window, colour = "error"), size=2.0) +

                scale_colour_manual("Response", values = c("#FF665F", "#188125"))


# Setup common elements of the latency plots
latency_plot <- ggplot(b$latencies, aes(x = elapsed)) +
                   facet_grid(. ~ op) +
                   labs(x = "Elapsed Secs", y = "Latency (ms)")

# Plot median, mean and 95th percentiles
plot2 <- latency_plot + labs(title = "Mean, Median, and 95th Percentile Latency") +
            geom_smooth(aes(y = median, color = "median"), size=0.5) +
            geom_point(aes(y = median, color = "median"), size=2.0) +

            geom_smooth(aes(y = mean, color = "mean"), size=0.5) +
            geom_point(aes(y = mean, color = "mean"), size=2.0) +

            geom_smooth(aes(y = X95th, color = "95th"), size=0.5) +
            geom_point(aes(y = X95th, color = "95th"), size=2.0) +

            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X95th", "mean", "median"),
            #                 labels = c("95th", "Mean", "Median"))

# Plot 99th percentile
plot3 <- latency_plot + labs(title = "99th Percentile Latency") +
            geom_smooth(aes(y = X99th, color = "99th"), size=0.5) +
            geom_point(aes(y = X99th, color = "99th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91"))
            # scale_color_hue("Percentile",
            #                 breaks = c("X99_9th","X99th" ),
            #                 labels = c("99.9th", "99th"))

# Plot 99.9th percentile
plot4 <- latency_plot + labs(title = "99.9th Percentile Latency") +
            geom_smooth(aes(y = X99_9th, color = "99.9th"), size=0.5) +
            geom_point(aes(y = X99_9th, color = "99.9th"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

# Plot 100th percentile
plot5 <- latency_plot + labs(title = "Maximum Latency") +
            geom_smooth(aes(y = max, color = "max"), size=0.5) +
            geom_point(aes(y = max, color = "max"), size=2.0) +
            scale_colour_manual("Percentile", values = c("#FF665F", "#009D91", "#FFA700"))

grid.newpage()

pushViewport(viewport(layout = grid.layout(5, 1)))

vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

print(plot1, vp = vplayout(1,1))
print(plot2, vp = vplayout(2,1))
print(plot3, vp = vplayout(3,1))
print(plot4, vp = vplayout(4,1))
print(plot5, vp = vplayout(5,1))

dev.off()
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=TRUE, add.comment=TRUE, 
                               add.row.margin=TRUE, add.col.margin=TRUE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000", halign='right')
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = sheet, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = sheet, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = sheet, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = sheet, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1, spacer_rows=2) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 1 + spacer_rows
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141215_0357"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup\n", "Insert\n", "Delete\n", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.2
  pdf(outFileName, family = "Times", width = 10, height = 3)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(3.5,4.75,0,0) + 0.1)
  par(mgp=c(3.5, 1.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  
  boxplot(selection, ylim=range(-0.1, 1.0), yaxt="n", las=0, ylab="savings (in %)", 
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
  z  <- c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
  zz <- c("0%", "20%", "40%", "60%", "80%", "100%")
  par(mgp=c(0, 0.75, 0)) # c(axis.title.position, axis.label.position, axis.line.position)
  axis(2, at=z, labels=zz, las=2,
       cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)
#' Conduct an aggregate query on amcat
#'
#' This function is similar to using the 'show table' function in AmCAT. It allows you to specify a
#' number of queries and get the number of hits per search term, per period, etc.
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param axis1 The first grouping (break/group by) variable, e.g. year, month, week, day, or medium
#' @param axis2 The second grouping (break/group by) variable, e.g. medium. Do not use a date interval here.
#' @param ... additional arguments to pass to the AmCAT API. 
#' @return A data frame with hits per group
#' @export
amcat.aggregate <- function(conn, queries, labels=queries, sets, axis1=NULL, axis2=NULL, ...) {
  result = NULL
  queries = as.character(queries)
  for (i in 1:length(queries)) {
    if (!is.na(queries[i])) {
      r = amcat.getobjects(conn,"aggregate", filters=list(q=queries[i], sets=sets, axis1=axis1, axis2=axis2, ...))
      if (nrow(r) > 0) {
        if (names(r)[1] == "count") {
          r$query = labels[i]
          result = rbind(result, r)
        } else {
          warning(paste("Error on querying",labels[i]))
        }
      }
    }
  }  
  # convert axis1 to Date object if needed
  if (!is.null(axis1))
    if (axis1 %in% c("year", "quarter", "month", "week", "day")) result[, axis1] = as.Date(result[, axis1])
  return(result)
}

#' Conduct a query on amcat
#'
#' This function is similar to using the 'show article list' function in AmCAT. It allows you to specify a
#' number of queries and get document metadata and number of hits per document
#'
#' @param conn the connection object from \code{\link{amcat.connect}}
#' @param queries a vector of queries to run
#' @param labels if given, labels corresponding to the queries
#' @param sets one or more article set ids to query on
#' @param ... additional arguments to pass to the AmCAT API, e.g. extra filters
#' @return A data frame with hits per article
#' @export
amcat.hits <- function(conn, queries, labels=queries, sets, minimal=T, ...) {
  result = NULL
  for (i in 1:length(queries)) {
    q = paste("count", queries[i], sep="#")
    r = amcat.getobjects(conn, "search",filters=list(q=q, col="hits", sets=sets, minimal=minimal, ...))
    if (nrow(r) > 0) {
      r$query = labels[i]
      result = rbind(result, r)
    } else {
      warning(paste("Query",labels[i]," produced no results"))
    }
  }
  return(result)
}
#Code for eBird migration project
# (c) 2013 -2014 Sarah Supp 

library(ggmap)
library(maptools)
library(fields)
library(sp)
library(raster)
library(maps)
library(mapdata)
library(rgdal)
library(raster)
library(gamm4)

#set working directory
main = "C:/Users/sarah/Dropbox/ActiveResearchProjects/Hummingbird_eBirdMigration"
figpath = "C:/Users/sarah/Dropbox/ActiveResearchProjects/Hummingbird_eBirdMigration/Figures"
gitpath = "C:/Users/sarah/Documents/GitHub/hb-migration"
wd = "C:/Users/sarah/Dropbox/ActiveResearchProjects/Hummingbird_eBirdMigration/data"
setwd(wd)


#---------------------------------------------------------------------------------------
#              predict migration paths, dates, speed, and error across years
#---------------------------------------------------------------------------------------

# read in summary of effort data (Number of eBird checklists submitted per day per year)
effort = read.table("FAL_hummingbird_data/checklist_12_2004-2013wh_grp.txt", header=TRUE, as.is=TRUE)

# read in country outline shp files
USAborder = readShapePoly("borders/USA_adm/USA_adm0.shp")
Mexborder = readShapePoly("borders/MEX_adm/MEX_adm0.shp")
Canborder = readShapePoly("borders/CAN_adm/CAN_adm0.shp")

# read in the altitude layers, make rasters
elev = raster("alt_5m_bil/alt.bil")

# plot elev + map for extent
myext <- c(-175, -50, 15, 75)
plot.new()
#plot(elev, ext = myext, xlab="Longitude", ylab = "Latitude", xlim = c(-175,-50), ylim = c(15,75), col=gray(0:256/256))

borders <- function(){
  plot(USAborder, ext=myext, border="black", add=TRUE)
  plot(Mexborder, ext=myext, border="black", add=TRUE)
  plot(Canborder, ext=myext, border="black", add=TRUE)
}

plot(elev, ext=myext, addfun=borders, ylab="Latitude", xlab="Longitude", xlim = c(-175,-50), ylim = c(15,75), col=gray(0:256/256)) 

# read in the north america equal area hex grid map (FAL) and format for use
# other options include a quad map (terr_4h6/nw_vector_grid.shp) or a hexmap with land only (terr_4h6/terr_4h6.shp", sep="")
hexgrid = readShapePoly(paste(main, "/data/icosahedron_land_and_sea/icosahedron.shp", sep="")) #hex with land and sea, cropped to North America

# plot the hexgrid on a map of north america
plot(NA, NA, xlim=c(-175, -50), ylim=c(15, 75), xlab = "Longitude", ylab = "Latitude")
map('worldHires', c("usa", "canada", "mexico"), add=TRUE, fill=T, col="lightblue")
plot(hexgrid, add=T)

# make a North America base map
noam = get_map(location = "North America", zoom=3, maptype = "terrain", color = "bw")

# map total birder effort 2004:2013
eft = PlotChecklistMap(effort, hexgrid, wd)
rm(eft)

# read in eBird data
files = list.files(pattern = "*.txt")

#for each eBird file, print the number sightings per year and per month.
#plot the locations of sightings on a map, color coded by month
for (f in 1:length(files)){
  
  require(ggmap)
  require(ggplot2)
  require(plyr)
  require(reshape2)
  require(Rmisc)
  require(sp)
  require(raster)
  require(segmented)
  source(paste(gitpath, "/migration-fxns.r", sep=""))
  
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                    "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                    "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")
  
  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)
  
  #grab species name for setting directory paths and naming figures
  species = humdat$SCI_NAME[1] 
  species = gsub(" ","", species, fixed=TRUE)
  species = gsub("\"", "", species, fixed=TRUE)
  
  # set years of data to use - data after 2007 is more reliable
  years = c(2004:2013)

  #start a new directory
  dirpath = paste(figpath, "/", species, sep="")
     #dir.create(dirpath, showWarnings = TRUE, recursive = FALSE) #only need if directory did not previously exist
  
  #show how many records there are for the species across the years, write to txt file
  #yeartable = PlotRecords(humdat$YEAR, species)
  #ggsave(file=paste(dirpath, "/", "years", species, ".pdf", sep=""))
  
  write.table(yeartable, file = paste(dirpath, "/", species,".txt",sep=""), row.names=FALSE)
  
  #save a figure of the geographic number of checklists for the species, over all the years
  #count = PlotChecklistMap(humdat, hexgrid, dirpath)
  
  for (y in 1:length(years)){
    yrdat = humdat[which(humdat$YEAR == years[y]),]
    yreffort = effort[which(effort$YEAR == years[y]),]
    
    #plot frequency of sightings per month
    #monthtable = PlotRecords(yrdat$month, species)
    
    #get daily weighted mean location 
    meanlocs = AlternateMeanLocs(yrdat, species, hexgrid, yreffort)
    
    #use GAM model to predict daily location along a smoothing line
    preds = EstimateDailyLocs(meanlocs)
    
    #use gam approach to estimate rough starting points for segmentation from the mean loc latitude data
    startpoints = round(Est3MigrationDates(meanlocs))
    migration = startpoints
    
    #save a plot of the species migration route mapped onto continent with real observations
    pdf(file = paste(dirpath, "/trimmed-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
    BasePlotMigration(preds, yrdat, migration, elev, USAborder, Mexborder, Canborder, myext)
    dev.off() 
    
    #save a plot of the species migration mapped onto an elevation raster
    pdf(file = paste(dirpath, "/elev-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
    ElevPlotMigration(preds, yrdat, migration, elev, USAborder, Mexborder, Canborder, myext)
    dev.off() 
    
    #get Great Circle distances traveled each day between predicted daily locations
    dist = DailyTravel(preds, 4, 5, species, years[y], migration)
    
    #estimate migration speed for spring and fall
    speed = MigrationSpeed(dist, migration)
    
    #plot smoothed migration trajectory for the species and year
    #mig_path = PlotMigrationPath(preds, noam, species, years[y])
    #ggsave(mig_path, file=paste(dirpath, "/", "migration", species, years[y], ".pdf", sep=""))
    
#     #plot occurrences with lines showing beginning and end of migration
     PlotOccurrences(meanlocs, species, years[y], migration)
     ggsave(file=paste(dirpath, "/", "occurrences", species, years[y], ".tiff", sep=""), dpi=600)

    #Subset western species by flyway data (check bias in SE US data points) Sensu La Sorte et al in press - 
        #"The role of atmospheric conditions in the seasonal dynamics of North American migration flyways" - JOurnal of Biogeography
    if (species %in% c("Archilochusalexandri", "Selasphorusplatycercus", "Selasphorusrufus", "Selasphoruscalliope")) {
          
      #only use data west of the 103rd meridian (western flyway)
      west_yrdat = yrdat[which(yrdat$LONGITUDE <= -103),]
      
      #get daily weighted mean location 
      west_meanlocs = AlternateMeanLocs(west_yrdat, species, hexgrid, yreffort)
      
      #use GAM model to predict daily location along a smoothing line
      west_preds = EstimateDailyLocs(west_meanlocs)
      
      #use gam approach to estimate rough starting points for segmentation from the mean loc latitude data
      west_migration = round(Est3MigrationDates(west_meanlocs))
      
      #get Great Circle distances traveled each day between predicted daily locations
      west_dist = DailyTravel(west_preds, 4, 5, species, years[y], west_migration)
      
      #estimate migration speed for spring and fall
      west_speed = MigrationSpeed(west_dist, west_migration)
      
      #save a plot of the species migration route mapped onto continent with real observations
      pdf(file = paste(dirpath, "/WEST_trimmed-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
      BasePlotMigration(west_preds, west_yrdat, west_migration, elev, USAborder, Mexborder, Canborder, myext)
      dev.off() 
      
      #save a plot of the species migration mapped onto an elevation raster
      pdf(file = paste(dirpath, "/WEST_elev-route_", species, years[y], ".pdf", sep=""), width = 7, height = 4.5)
      ElevPlotMigration(west_preds, west_yrdat, west_migration, elev, USAborder, Mexborder, Canborder, myext)
      dev.off() 
    }

    else {
      #create dummy variables for the eastern species. In this case, west == all variables
      west_preds = preds
      west_migration = migration
      west_speed = speed
    }

    #add year to preds, so we can save it to compare across years
    preds$year = years[y]
    west_preds$year = years[y]
    
    if (y == 1){
      pred_data = preds
      migdates = data.frame("spr_begin" = migration[[1]], "spr_end" = migration[[2]], 
                            "fal_begin" = migration[[2]], "fal_end" = migration[[3]],
                            "species" = species, "year" = years[y])
      migspeed = data.frame("spr" = speed[1], "fal" = speed[2], "species" = species, "year" = years[y])
      
      west_pred_data = west_preds
      west_migdates = data.frame("spr_begin" = west_migration[1], "spr_end" = west_migration[2], 
                                 "fal_begin" = west_migration[2], "fal_end" = west_migration[3],
                                 "species" = species, "year" = years[y])
      west_migspeed = data.frame("spr" = west_speed[1], "fal" = west_speed[2], "species" = species, "year" = years[y])
    }
    else{
      pred_data = rbind(pred_data, preds)
      dates = c(migration[[1]], migration[[2]], migration[[2]], migration[[3]], "species" = species, year = years[y])
      speed = c(speed, species, years[y])
      migdates = rbind(migdates, dates)
      migspeed = rbind(migspeed, speed)
      
      west_pred_data = rbind(west_pred_data, west_preds)
      west_dates = c(west_migration[[1]], west_migration[[2]], west_migration[[2]], west_migration[[3]], "species" = species, year = years[y])
      west_speed = c(west_speed, species, years[y])
      west_migdates = rbind(west_migdates, west_dates)
      west_migspeed = rbind(west_migspeed, west_speed)
    }
    
    if (y == length(years)){
      #write migration timing and speed data to file
      write.table(migdates, file = paste(getwd(), "/output_data/migration", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(migspeed, file = paste(getwd(), "/output_data/speed", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(pred_data, file = paste(getwd(), "/output_data/centroids", species, ".txt", sep=""), 
                  append=FALSE,row.names=FALSE)
      
      #write western flyway migration timing and speed data to file
      write.table(west_migdates, file = paste(getwd(), "/output_data/west_migration", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(west_migspeed, file = paste(getwd(), "/output_data/west_speed", species, ".txt", sep=""), 
                  append=FALSE, row.names=FALSE)
      write.table(west_pred_data, file = paste(getwd(), "/output_data/west_centroids", species, ".txt", sep=""), 
                  append=FALSE,row.names=FALSE)
    }
    
    rm(list=ls()[ls() %in% c("sitemap", "meanmap", "yrdat", "meanlocs", "migration", "preds", "dist", "mig_path", "speed",
                             "west_migration", "west_preds", "west_dist", "west_speed")])   # clears the memory of the map and year-level data
  }
  rm(list=ls()[!ls() %in% c("f", "files", "noam", "hexgrid", "effort", "pred_data", "migdates", 
                            "wd", "main", "gitpath","figpath", "USAborder", "Mexborder", "Canborder", "elev", "myext")])   # clears the memory of everything except the file list, iterator, and base map
}


#---------------------------------------------------------------------------------------
#                   compare migration rates and dates across species
#---------------------------------------------------------------------------------------
require(ggmap)
require(ggplot2)
require(plyr)
require(reshape2)
require(Rmisc)
require(sp)
require(raster)
require(gamm4)
require(chron)
require(fields)
require(RColorBrewer)
source(paste(gitpath, "/migration-fxns.r", sep=""))

setwd(wd)

# read in eBird data for migration speed, dates, and predicted path (should be in same order for species)
rfiles = list.files(path = paste(getwd(), "/output_data/", sep=""), pattern = "west_speed", full.names=TRUE)
mfiles = list.files(path = paste(getwd(), "/output_data/", sep=""), pattern = c("west_migration.*txt"), full.names=TRUE)
cfiles = list.files(path = paste(getwd(), "/output_data/", sep=""), pattern = "west_centroids.*.txt", full.names=TRUE)

# species ordered by data files, body sizes from Dunning 2008, migration distance from Nature Serve centroids
species = c("Black-chinned", "Ruby-throated", "Calliope", "Broad-tailed", "Rufous")
mass = c(3.4, 3.1, 2.65, 3.55, 3.5)
distance = c(1721.49, 2765.86, 3252.82, 1737.89, 4102.58)
spdata = data.frame(species, mass, distance, "lat_r2"= NA, "lon_r2" = NA, "spr_speed" = NA,
                    "fal_speed" = NA, "spr_date" = NA, "fal_date" = NA)


#------------------------------------------ ANALYZE THE DATA -------------------------------------

#-------------------- 
#       model to test variance in lat and lon across years, with year as a random effect
#-------------------- get gamm4 results using all years (2004-2013) and later years (2008-2013)
for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds_sub = preds[which(preds$year > 2007),]
  print(preds[1,1]) #species name
  years = c(2004:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    spring = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday < dates[y,2]),]
    fall = preds[which(preds$year == years[y] & preds$jday > dates[y,2] & preds$jday <= dates[y,4]),]
    
    if (y == 1){
      migpreds = between
      pred_spr = spring
      pred_fal = fall
    }
    else{
      migpreds = rbind(migpreds, between)
      pred_spr = rbind(pred_spr, spring)
      pred_fal = rbind(pred_fal, fall)
    }
  }
  
  # subset the seasonal data by the recent years (2008-2013)
  pred_spr_sub = pred_spr[which(pred_spr$year > 2007),]
  pred_fal_sub = pred_fal[which(pred_fal$year > 2007),]
  
  #gam analysis to determine variance across years, using all of the daily centroids (Jday 1-365) in each year
  lon_gam = gamm4(lon ~ s(jday, k=10), random = ~(1|year), data = preds_sub)
  print (paste("R2 for Longitude is:", round(summary(lon_gam$gam)$r.sq,4)))
  lat_gam = gamm4(lat ~ s(jday, k=10), random = ~(1|year), data=preds_sub)
  print (paste("R2 for Latitude is:", round(summary(lat_gam$gam)$r.sq,4)))
  
  #gam analysis to determine variance across years, using only spring centroids (start of spring to peak latitude date)
  lon_gam_spr = gamm4(lon ~ s(jday, k=10), random = ~(1|year), data=pred_spr_sub)
  print (paste("R2 for spring Longitude is:", round(summary(lon_gam_spr$gam)$r.sq,4)))
  lat_gam_spr = gamm4(lat ~ s(jday, k=10), random = ~(1|year), data=pred_spr_sub)
  print (paste("R2 for spring Latitude is:", round(summary(lat_gam_spr$gam)$r.sq,4)))
  
  #gam analsysis to determine variance across years, using only fall centroids (peak latitude to end of fall date)
  lon_gam_fal = gamm4(lon ~ s(jday, k=10), random = ~(1|year), data=pred_fal_sub)
  print (paste("R2 for fall Longitude is:", round(summary(lon_gam_fal$gam)$r.sq,4)))
  lat_gam_fal = gamm4(lat ~ s(jday, k=10), random = ~(1|year), data=pred_fal_sub)
  print (paste("R2 for fall Latitude is:", round(summary(lat_gam_fal$gam)$r.sq,4)))
  
  spdata[f,4] = summary(lat_gam$gam)$r.sq
  spdata[f,5] = summary(lon_gam$gam)$r.sq
}


#--------------------
#       get linear model results using years (2008-2013) and plot as barplot
#-------------------- 
lm_mig = data.frame("species"="Archilochusalexandri", "season" = "spring", "year" = 1, "lat_slope" = 1, "lat_r2" = 1, "lon_slope" = 1, "lon_r2" = 1)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  species = preds[1,1] #species name
  years = c(2008:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    spring = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday < dates[y,2]),]
    fall = preds[which(preds$year == years[y] & preds$jday > dates[y,2] & preds$jday <= dates[y,4]),]
    
    #get slope & r2 of spring and fall latitudinal migration
    spr_lm = LinearMigration(spring, years[y])
    spr_lm = data.frame("species" = species, "season"= "spring", spr_lm)
    fal_lm = LinearMigration(fall, years[y])
    fal_lm = data.frame("species" = species, "season"= "fall", fal_lm)
    lm_mig = rbind(lm_mig, spr_lm)
    lm_mig = rbind(lm_mig, fal_lm)
  }
}
lm_mig = lm_mig[-1,] #delete first row of dummy data

#plot the variance in estimated migration begin and end for all and for recent years
pdf(file = paste(figpath, "/linearslope_all_species.pdf", sep=""), width = 6, height = 5)

bxp_rate = ggplot(lm_mig, aes(season, abs(lat_slope), fill=season)) + geom_boxplot() + theme_classic() + 
  scale_fill_manual(values=c("cadetblue", "orange"), guide = "none") + 
  ylab("linear slope of seasonal migration") + theme(text = element_text(size=12)) + 
  scale_y_continuous(breaks = seq(0, 0.40, by = 0.10), limits = c(0,0.40)) + theme(text = element_text(size=12)) +
  facet_wrap(~species)

multiplot(bxp_rate, cols = 1)
dev.off()


#--------------------------- 
#       generate figures and table data for migration speed
#--------------------------- boxplots of migration speed for spring vs. fall for each species
rate = data.frame("spr" =1, "fal" = 1, "species" = "none", "year" = 1)
for (f in 1:length(rfiles)){
  sp_rate = read.table(rfiles[f], header=TRUE, sep=" ", fill=TRUE, comment.char="")
#  sp_rate = subset(sp_rate, year>2007) #use only years 2008-2013
  rate = rbind(rate, sp_rate)
  
  #print the mean and standard deviation of speed for each species (note: this includes all years, unless uncomment above line)
  print(sp_rate$species[1])
  print(paste("spring sd:", sd(sp_rate$spr)))
  print(paste("spring mean:", mean(sp_rate$spr)))
  print(paste("fall sd:", sd(sp_rate$fal)))
  print(paste("fall mean:", mean(sp_rate$fal)))
  print("")
  
  spdata[f,6] = mean(sp_rate$spr)
  spdata[f,7] = mean(sp_rate$fal)
}

rate = subset(rate, year > 2007) #subset to better-sampled years
r = melt(rate[,c(1,2,3,4)], id.vars = c("year", "species"))
names(r) = c("year", "species", "season", "rate")

#plot the variance in estimated migration speed for all and for recent years
pdf(file = paste(figpath, "/speed_all_species.pdf", sep=""), width = 15, height = 3)
  
bxp_speed = ggplot(r, aes(season, rate, fill=season)) + geom_boxplot() + theme_bw() + 
    scale_fill_manual(values=c("cadetblue", "orange"), guide="none") + ylab("km/day") + 
    scale_y_continuous(breaks = seq(0, 80, by = 20), limits = c(0,80)) + 
    facet_wrap(~species, nrow=1)
  
multiplot(bxp_speed, cols = 5)
dev.off() 


#--------------------------
#         generate figures and table data for migration dates
# ------------------------ Boxplots of the number of days +/- mean migration date, by species
dates = data.frame("spr_begin" = 1, "mid" = 1, "fal_end" = 1, "species" = "none", "year" = 1)

for (f in 1:length(mfiles)){
  sp_dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
# sp_dates = subset(sp_dates, year>2007)
  
  #Print species table data (note: this includes all years, unless uncomment above line)
  print(sp_dates$species[1])
  print(paste("spring begin median:", median(sp_dates$spr_begin)))
  print(paste("spring begin sd:", sd(sp_dates$spr_begin)))
  print(paste("lat peak median:", median(sp_dates$spr_end)))
  print(paste("lat peak sd:", sd(sp_dates$spr_end)))
  print(paste("fall end median:", median(sp_dates$fal_end)))
  print(paste("fall end sd:", sd(sp_dates$fal_end)))
  print("")
  
  #standardize dates, to get number of days +/- mean
  sp_dates = subset(sp_dates, year > 2007)
  
  spdata[f,8] = round(sd(sp_dates$spr_begin),4)
  spdata[f,9] = round(sd(sp_dates$fal_end), 4)
  
  sp_dates$spr_begin = sp_dates$spr_begin - mean(sp_dates$spr_begin)
  sp_dates$mid = sp_dates$spr_end - mean(sp_dates$spr_end)
  sp_dates$fal_end = sp_dates$fal_end - mean(sp_dates$fal_end)
  dates = rbind(dates, sp_dates[,c(1,7,4,5,6)])

}

dates = dates[-1,]
d = melt(dates, id.vars = c("species", "year"))
names(d) = c("species", "year", "season", "date")
  
#plot the variance in estimated migration begin and end for all and for recent years
pdf(file = paste(figpath, "/migdates_all_species.pdf", sep=""), width = 15, height = 3)
  
bxp_date = ggplot(d, aes(season, date, fill=season)) + geom_boxplot() + theme_bw() + 
  scale_fill_manual(values=c("cadetblue", "olivedrab3", "orange"), guide = "none") + 
  ylab("number of days -/+ mean date") + theme(text = element_text(size=12)) + 
  scale_y_continuous(breaks = seq(-40, 40, by = 20), limits = c(-40,40)) +
  facet_wrap(~species, nrow=1)
  
  multiplot(bxp_date)
  dev.off()


#------------------------------------------ PLOT THE DATA -------------------------------------


#------------------------------------
#       plot the data for species comparisons
#------------------------------------

ggplot(spdata, aes(distance, lat_r2)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Latitude R2 by date") + stat_smooth(method = "lm") + theme_classic()

ggplot(spdata, aes(distance, lon_r2)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Longitude R2 by date") + stat_smooth(method = "lm") + theme_classic()

ggplot(spdata, aes(distance, spr_speed)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Population spring migration speed (km/day)") + 
  stat_smooth(method = "lm", col = "cadetblue", fill = "cadetblue", alpha = 0.2) + 
  theme_classic() #+ geom_text(label=species)

ggplot(spdata, aes(distance, fal_speed)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("Population fall migration speed (km/day)") + stat_smooth(method = "lm", col = "orange", fill = "orange", alpha = 0.2) +
  theme_classic() #+ geom_text(label=species)

ggplot(spdata, aes(distance, spr_date)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("sd in spring onset") + stat_smooth(method = "lm", col = "cadetblue", fill = "cadetblue", alpha = 0.2) +
  theme_classic()

ggplot(spdata, aes(distance, fal_date)) + geom_point(size = mass) + xlab("total migration distance") +
  ylab("sd in fall arrival") + stat_smooth(method = "lm", col = "orange", fill = "orange", alpha = 0.2) +
  theme_classic()


#---------------------------------
#       plot standard deviation in the daily centroid estimates across years 2008-2013
#---------------------------------
for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  species = preds[1,1] #species name
  years = c(2008:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]

    if (y == 1){
      migpreds = between
    }
    else{
      migpreds = rbind(migpreds, between)
    }
  }
  
  #compare location across the years using mean and sd for 2008:2013
  jdays = sort(unique(migpreds$jday))
  patherr = data.frame("jday"=1,"meanlat"=1, "sdlat"=1, "meanlon"=1, "sdlon"=1)
  outcount = 1
  for (j in min(jdays):max(jdays)){
    tmp = migpreds[which(migpreds$jday == j),]
    meanlat = mean(tmp$lat)
    sdlat = sd(tmp$lat)
    meanlon = mean(tmp$lon)
    sdlon = sd(tmp$lon)
    patherr[outcount,] = c(j, meanlat, sdlat, meanlon, sdlon)
    outcount = outcount + 1
  }
    
  # plot the standard deviation in daily lat and lon across the 10 years, and across 6 most recent years
  pdf(file = paste(dirpath, "/ErrorinDailyLocs", species, ".pdf", sep=""), width = 5, height = 8)
  
  ymax = max(c(patherr$sdlat, patherr$sdlon),na.rm=TRUE) 
  sdlocs = ggplot(patherr, aes(jday, sdlat)) + geom_point(size=1) + theme_classic() + 
    ggtitle(paste(species, "sd in daily locs", min(years), "-", max(years))) +
    scale_y_continuous(breaks = seq(0, ymax, by = 0.5), limits = c(0, ymax)) + 
    scale_x_continuous(breaks = seq(0, 366, by = 25), limits = c(0, 366)) + 
    geom_point(aes(jday, sdlon), col = "indianred", size=1) + ylab("stdev daily lat (black) and lon (red)")

  lonlatday = ggplot(patherr, aes(sdlon, sdlat, col=jday)) + geom_point(size=1) + theme_classic() +
    scale_y_continuous(breaks = seq(0, ymax, by = 0.5), limits = c(0, ymax))  +
    scale_x_continuous(breaks = seq(0, ymax, by = 0.5), limits = c(0, ymax)) 
 
  multiplot(sdlocs, lonlatday, cols = 1)
  dev.off()
}
  
  
#---------------------------------
#       plot all migration routes for a species on a map with elevation raster
#---------------------------------
pdf(file = paste(figpath, "/elev-route_summary_all_species.pdf", sep=""), width = 7, height = 4.5)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds = subset(preds, year > 2007)
  elev = raster("alt_5m_bil/alt.bil")  #elevation layers
  myext = c(-175, -50, 15, 75) #set extent to North America
  species = preds[1,1] #species name
  
  AllMigration(preds, elev, myext, species)
}
dev.off() 


#---------------------------------
#       plot standard error in predicted centroids across years
#---------------------------------
pdf(file=paste(figpath, "/se_corlon-lat_all_species.pdf", sep=""), width = 10, height = 7)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  species = preds[1,1] #species name
  years = c(2004:2013)

  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
  
    if (y == 1){ migpreds = between }
    else{ migpreds = rbind(migpreds, between) }
  }
  
  if (species == "Selasphoruscalliope") {by = 1}
  else {by = 0.5}
  
  ymax = max(c(migpreds$lat_se, migpreds$lon_se))
  latlon = ggplot(migpreds, aes(lon_se, lat_se)) + ggtitle(species) +
    xlab("estimated longitude standard error") + ylab("estimated latitude standard error") +
  geom_point(alpha = 0.5) + theme_classic() + facet_wrap(~year) +
  theme(text = element_text(size=12)) +
  scale_y_continuous(breaks = seq(0, ymax, by = by), limits = c(0, ymax)) +
  scale_x_continuous(breaks = seq(0, ymax, by = by), limits = c(0, ymax))
  multiplot(latlon, cols = 1)
}
dev.off()


#---------------------------------
#       plot standard error in predicted centroids across years, by julian date
#---------------------------------
pdf(file = paste(figpath, "/error_se-latlon_all_species.pdf", sep=""), width = 10, height = 4)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = subset(dates, year > 2007)
  species = preds[1,1] #species name
  years = c(2008:2013)
  
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    
    if (y == 1){ migpreds = between }
    else{ migpreds = rbind(migpreds, between) }
  }

  ymax = max(c(migpreds$lat_se, migpreds$lon_se)) 
  lat = ggplot(migpreds, aes(jday, lat_se, col=as.factor(year))) + geom_point(size=1) + theme_classic() +
  geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
  geom_vline(xintercept = c(dates$fal_end), col = "orange") + ggtitle(species) +
  xlab("Julian Day") + ylab("latitude centroid standard error") +
  scale_y_continuous(breaks = seq(0, ymax, by = 0.25), limits = c(0, ymax))+
  theme(text = element_text(size=12))

  lon = ggplot(migpreds, aes(jday, lon_se, col=as.factor(year))) + geom_point(size=1) + theme_classic() +
  geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
  geom_vline(xintercept = c(dates$fal_end), col = "orange") + ggtitle(species) +
  xlab("Julian Day") + ylab("longitude centroid standard error") +
  scale_y_continuous(breaks = seq(0, ymax, by = 0.25), limits = c(0, ymax)) +
  theme(text = element_text(size=12))

  multiplot(lat, lon, cols = 2)
}
dev.off()


#---------------------------------
#       plot predicted latitude and longitude as distribution across the years for all species
#---------------------------------
# save plots comparing daily lat and long and migration date across the years
pdf(file = paste(figpath, "/AllYears_lon-lat_all_species.pdf", sep=""), width = 8, height = 5)

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds = subset(preds, year > 2007)
  dates = subset(dates, year > 2007)
  species = preds[1,1] #species name
  
  yrlylat = ggplot(preds, aes(jday, lat, col=year)) + geom_point(size=1) + theme_classic() +
    geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
    geom_vline(xintercept = c(dates$spr_end), col = "olivedrab3") +
    geom_vline(xintercept = c(dates$fal_end), col = "orange") +
    scale_x_continuous(breaks = seq(0, 365, by = 30)) + 
    theme(text = element_text(size=20)) + ggtitle(species)
  
  yrlylon = ggplot(preds, aes(jday, lon, col=year)) + geom_point(size=1) + theme_classic() +
    geom_vline(xintercept = c(dates$spr_begin), col = "cadetblue") +
    geom_vline(xintercept = c(dates$spr_end), col = "olivedrab3") +
    geom_vline(xintercept = c(dates$fal_end), col = "orange") +
    scale_x_continuous(breaks = seq(0, 365, by = 30)) + 
    theme(text = element_text(size=20))

  multiplot(yrlylat, cols = 1)
  multiplot(yrlylon, cols = 1)
}
dev.off()

#----------------------------------------------------------
#       Makes Figure B3. Observations across the years (2004-2013)
#       For Appendix B
#----------------------------------------------------------

#NOTE!!: For this to work, make sure files and mfiles is in the same species-order!!
for (f in 1:length(files)) {
  
  #read in raw data
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = subset(dates, year > 2007)
  
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                    "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                    "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")
  
  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)
  
  #grab species name for later identification
  species = humdat$SCI_NAME[1]
  species = gsub("\"", "", species, fixed=TRUE)
  years = c(2004:2013)
  
  for (y in 1:length(years)){
    dat = subset(humdat, YEAR==years[y])
    yrobs = data.frame(table(dat$DAY))
    yrobs$year = years[y]
    
    if(y == 1) { obs = yrobs}
    else{ obs = rbind(obs, yrobs)}
  }
    names(obs) = c("jday", "freq")
    obs$jday = as.numeric(obs$jday)
    obs$freq = as.numeric(obs$freq)
  ymax = max(obs$freq) + 25
  
  ggplot(obs, aes(jday, freq)) + geom_point(alpha=0.4) + xlab("Julian day of Year") + ylab("Number of Checklists") + 
    theme_classic() + theme(text = element_text(size=12)) +     
    geom_smooth(se=T, method='gam', formula=y~s(x, k=40), gamma=1.5) +
    scale_x_continuous(breaks = seq(0, 365, by = 50), limits = c(0,365)) + 
    scale_y_continuous(breaks = seq(0, ymax, by = 50)) +
    geom_vline(xintercept = dates[,1], col = "cadetblue", size = 0.5) +
    geom_vline(xintercept = dates[,4], col = "orange", size = 0.5) +
    geom_vline(xintercept = dates[,2], col = "olivedrab3", size = 0.5) 

  ggsave(file=paste(figpath, "/B3_occurrences", species, years[y], ".tiff", sep=""), dpi=600, height=3, width=4)
}


#-----------------------------------------------------------
#       Make synthetic panel figure for manuscript  - FIGURE 1
#       Make parts separately, and bring back together 
#         in Illustrator or Inkscape
#-----------------------------------------------------------
#reorder files to match manuscript ordering
files = c(files[4],files[1],files[2],files[3],files[5])
cfiles = c(cfiles[2],cfiles[1],cfiles[4],cfiles[3],cfiles[5])
mfiles = c(mfiles[2],mfiles[1],mfiles[4],mfiles[3],mfiles[5])

for (f in 1:length(files)) {
  
  #read in raw data
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")
  
  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                    "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                    "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")
  
  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)
  
  #grab species name for later identification
  species = humdat$SCI_NAME[1]
  species = gsub("\"", "", species, fixed=TRUE)
   
  #plot the geographic number of checklists for the species, over all the years  
  #find the number of obs in each cell
  t = table(as.factor(humdat$POLYFID))
  
  #Merge the count data for the hexes with all the hexes in the map
  df = data.frame(POLYFID = names(t), count=as.numeric(t))
  df2 = data.frame(POLYFID = unique(hexgrid$POLYFID))
  df3 = merge(df2, df, all.x=TRUE)
  df3$species = species
  
  #combine all the datasets so we can get the colors on the same scale
  if (f == 1) {
    df3.1 = df3
    splist = species
  }
  
  else{
    df3.1 = rbind(df3.1, df3)
    splist = c(splist, species)
  }
}

# Set colors and legend scale by all species (e.g. some will be red, some will be shades of yellow)
  #matches colors with the number of observations
  yltord = colorRampPalette(brewer.pal(9, "YlOrRd"))(length(unique(df3.1$count)))
  cols = data.frame(id=c(NA,sort(unique(df3.1$count))), cols=yltord, stringsAsFactors=FALSE)
  df4 = merge(df3.1, cols, by.x="count", by.y="id")
  #set scale for legend
  vls = sort(unique(round(cols$id/500)*500))
  vls[1] = 1
  cols2 = rev(heat.colors(length(vls)))

#separate back out by species for plotting
for (s in 1:length(splist)){
  df4.1 = subset(df4, species == splist[s])
  df5 = merge(hexgrid, df4.1, by.x="POLYFID", by.y="POLYFID", all.x=TRUE)
  df5$cols = ifelse(is.na(df5$count), "white", df5$cols)  #hexes with no counts are white
  df5 = df5[order(df5$POLYFID),]

  #make a map with hexes colored by the number of times the species was observed in a given hex
  setEPS()
  postscript(file = paste(figpath, "/fig1_col1_", splist[s], ".eps", sep=""), width = 3, height = 3)
  plot(NA, NA, xlim = c(-140,-60), ylim=c(15,55),xlab="", ylab="", axes=FALSE)
    plot(hexgrid, col=df5$cols, border = "white", lwd = 0.25, las=1, add=TRUE)
    mtext(side=2,line=2, splist[s])
    map("worldHires", c("usa", "canada", "mexico"), add=TRUE, cex = 0.25)
  dev.off()
  
  #plot the legend separately
  setEPS()
  postscript(file = paste(figpath, "/fig1_col1_legend.eps", sep=""), width = 3, height = 3)
  plot(NA, NA, xlim = c(0,5), ylim=c(0,5), axes=FALSE, xlab = "", ylab="")
  legend.col(col = cols[,2], lev = sort(unique(df4$count)))
  dev.off()
}

for (f in 1:length(files)) {
  #read in the centroid and migration data (by western flyway), use data for years 2008-2013
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds_sub = preds[which(preds$year > 2007),]
  dates_sub = dates[which(dates$year > 2007),]
  species = preds[1,1]
  years = c(2008:2013)
  
# plot the migration routes in the next figure
preds_sub$month = as.factor(preds_sub$month)
cols3 = data.frame(id=c(sort(unique(preds_sub$month))), cols=tim.colors(length(unique(preds_sub$month))), stringsAsFactors=FALSE)
preds_sub = merge(preds_sub, cols3, by.x="month", by.y="id")
#set color scale
vls = sort(unique(round(cols3$id)))
vls[1] = 1
cols4 = tim.colors(length(vls))

setEPS()
postscript(file = paste(figpath, "/fig1_col2_", species, ".eps", sep=""), width = 3, height = 3)
plot(preds_sub$lon, preds_sub$lat, col=preds_sub$cols, pch=19, cex=0.25, ylab="", xlab="", xlim = c(-140, -60), ylim = c(15, 55),
     cex.lab = 1, cex.axis=1, axes=FALSE)
  map("worldHires", c("usa", "canada", "mexico"), add=TRUE)
  points(preds_sub$lon, preds_sub$lat, col=preds_sub$cols, pch=19, cex=0.25)
dev.off()

#plot legend separately  
setEPS()
postscript(file = paste(figpath, "/fig1_col2_legend.eps", sep=""), width = 3, height = 3)
plot(NA, NA, xlim = c(0,5), ylim=c(0,5), axes=FALSE, xlab = "", ylab="")
  legend("bottomleft", legend=vls, pch=22, pt.bg=cols4, pt.cex=0.75, cex=0.75, bty="n",
       col="black", title="month", x.intersp=1, y.intersp=0.5)  
dev.off()

# plot the latitudinal patterns with estimated dates of migration
setEPS()
postscript(file = paste(figpath, "/fig1_col4_", species, ".eps", sep=""), width = 3, height = 3)
latmin = ((min(preds_sub$lat)%/%5+1)*5)-5
latmax = ((max(preds_sub$lat)%/%5+1)*5) + 5 

par(bty="l")
plot(preds_sub$jday, preds_sub$lat, pch = 19, xlab = "", ylab = "", 
     cex.axis = 1, col = "grey20", cex = 0.25)
  abline(v=dates_sub$spr_begin, col="cadetblue")
  abline(v=dates_sub$spr_end, col = "olivedrab3")
  abline(v=dates_sub$fal_end, col = "orange")
dev.off()

}




#---------------------------------
#       plot predicted latitude with 95% confidence intervals
#---------------------------------
# save plots comparing daily lat and long and migration date across the years

for (f in 1:length(cfiles)){
  preds = read.table(cfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  preds = subset(preds, year > 2007)
  dates = subset(dates, year > 2007)
  species = preds[1,1] #species name
  
  #calculate 95% CI
  preds$lat_ucl = preds$lat + 1.96 * preds$lat_se
  preds$lat_lcl = preds$lat - 1.96 * preds$lat_se
  preds$lon_ucl = preds$lon + 1.96 * preds$lon_se
  preds$lon_lcl = preds$lon - 1.96 * preds$lon_se
  
  years = c(2008:2013)
  #grab only the predicted daily centroids from between the migration dates
  for (y in 1:length(years)){
    between = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday <= dates[y,4]),]
    spring = preds[which(preds$year == years[y] & preds$jday >= dates[y,1] & preds$jday < dates[y,2]),]
    fall = preds[which(preds$year == years[y] & preds$jday > dates[y,2] & preds$jday <= dates[y,4]),]
    
    if (y == 1){
      migpreds = between
      pred_spr = spring
      pred_fal = fall
    }
    else{
      migpreds = rbind(migpreds, between)
      pred_spr = rbind(pred_spr, spring)
      pred_fal = rbind(pred_fal, fall)
    }
  }
     
  # plot spring and fall separately, color-coded to compare overlap
  seasons = ggplot(pred_spr, aes(lon, lat), col = year, group=year, order.by=jday) + theme_classic() + 
    geom_rect(data=pred_spr, aes(xmin=lon_lcl,ymin=lat_lcl,xmax=lon_ucl,ymax=lat_ucl, group=year), fill="cadetblue", alpha=0.02) +
    geom_path(aes(group=year)) + 
    geom_rect(data=pred_fal, aes(xmin=lon_lcl,ymin=lat_lcl,xmax=lon_ucl,ymax=lat_ucl, group=year), fill="orange", alpha=0.02) +
    geom_path(data=pred_fal, aes(lon, lat, group=year)) + 
    theme(text = element_text(size=12)) + xlab("longitude") + ylab("latitude")
  
  pdf(file = paste(figpath, "/fig1_col3_", species, ".pdf", sep=""), width = 3, height = 3)
  multiplot(seasons, cols = 1)
  dev.off()
}



#---------------------------------
#       Figure B1 for appendix, total eBird effort 2004-2013
#---------------------------------

#find the number of obs in each cell
t = table(as.factor(effort$POLYFID))

#Merge the count data for the hexes with all the hexes in the map
df = data.frame(POLYFID = names(t), count=as.numeric(t))
df2 = data.frame(POLYFID = unique(hexgrid$POLYFID))
df3 = merge(df2, df, all.x=TRUE)

#matches colors with the number of observations
#   # Set colors and legend scale by all species (e.g. some will be red, some will be shades of yellow)
yltord = colorRampPalette(brewer.pal(9, "YlOrRd"))(length(unique(df3$count)))
cols = data.frame(id=c(NA,sort(unique(df3$count))), cols=yltord, stringsAsFactors=FALSE)
df4 = merge(df3, cols, by.x="count", by.y="id")
df5 = merge(hexgrid, df4, by.x="POLYFID", by.y="POLYFID", all.x=TRUE)

#   #set scale for legend
vls = sort(unique(round(cols$id/500)*500))
vls[1] = 1
cols2 = rev(heat.colors(length(vls)))

#hexes with no counts are white
df5$cols = ifelse(is.na(df5$count), "white", df5$cols)
df5 = df5[order(df5$POLYFID),]

#make a map with hexes colored by the number of times the species was observed in a given hex
setEPS()
postscript(file = paste(figpath, "/FigureB1.eps", sep=""), width = 5.5, height = 4)
plot(NA, NA, xlim = c(-170,-50), ylim=c(15,75),xlab="", ylab="", axes=FALSE)
plot(hexgrid, col=df5$cols, border = "white", lwd = 0.25, las=1, add=TRUE)
map("worldHires", c("usa", "canada", "mexico"), add=TRUE, cex = 0.25)
dev.off()

#plot the legend separately
setEPS()
postscript(file = paste(figpath, "/figB1_col1_legend.eps", sep=""), width = 3, height = 3)
plot(NA, NA, xlim = c(0,5), ylim=c(0,5), axes=FALSE, xlab = "", ylab="")
legend.col(col = cols[,2], lev = sort(unique(df4$count)))
dev.off()


#--------------------------------------------------
#   wrt question about number of obs in eastern US
#--------------------------------------------------
for (f in 1:length(files)){
  humdat = read.table(files[f], header=TRUE, sep=",", quote="", fill=TRUE, as.is=TRUE, comment.char="")

  names(humdat) = c("SCI_NAME", "PRIMARY_COM_NAME","YEAR", "DAY", "TIME", "GROUP_ID", "PROTOCOL_ID",
                  "PROJ_ID", "DURATION_HRS", "EFFORT_DISTANCE_KM", "EFFORT_AREA_HA", "NUM_OBSERVERS",
                  "LATITUDE", "LONGITUDE", "SUB_ID", "POLYFID", "MONTH")

  humdat$MONTH = factor(humdat$MONTH, levels=c(1:12), ordered=TRUE)

  #grab species name for later identification
  species = humdat$SCI_NAME[1]

  #subset eastern observations
  east = subset(humdat, LONGITUDE > -103)
  eastwinter = subset(east, MONTH %in% c(11, 12, 1, 2, 3))
  plot(table(east$YEAR), main=species)
  plot(table(eastwinter$YEAR), main=species)
}
  

#----------------------------------------------
#       Reviewer comment: detecting trends
#----------------------------------------------

#aggregate all the dates files
for (f in 1:length(mfiles)){
  dates = read.table(mfiles[f], header=TRUE, sep=" ", as.is=TRUE, fill=TRUE, comment.char="")
  if (f == 1) { d = dates }
  else { d = rbind(d, dates) }
}
d = d[,-2]
d = subset(d, year > 2007)
names(d) = c("spring_begin", "peak_latitude", "autumn_end", "species", "year")

#plot the data
spring = ggplot(d, aes(year, spring_begin, group=species)) + geom_line(aes(linetype=species)) + 
  theme_bw() + ylab("begin spring migration")
breed = ggplot(d, aes(year, peak_latitude, group=species)) + geom_line(aes(linetype=species)) + 
  theme_bw() + ylab("reach peak latitude")
autumn = ggplot(d, aes(year, autumn_end, group=species)) + geom_line(aes(linetype=species)) + 
   theme_bw() + ylab("end autumn migration")

pdf(file = paste(figpath, "/migration_trends.pdf", sep=""), width = 6, height = 7)
  multiplot(spring, breed, autumn, cols=1)
dev.off()


library(plyr)
# Break up d by species, then fit the specified model to each piece and return a list
# SPRING
models <- dlply(d, "species", function(df) 
  lm(spring_begin ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, anova, .print = TRUE)
l_ply(models, summary, .print = TRUE)

# PEAK LAT
models <- dlply(d, "species", function(df) 
  lm(peak_latitude ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, anova, .print = TRUE)

# AUTUMN
models <- dlply(d, "species", function(df) 
  lm(autumn_end ~ year, data = df))
# Apply coef to each model and return a data frame
ldply(models, coef)
# Print the summary of each model
l_ply(models, anova, .print = TRUE)
#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141215_0357"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

orderedBenchmarkNames <- function(dataType) {
  candidates <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "EntryIteration"]
  }
}

orderedBenchmarkNamesForBoxplot <- function(dataType) {
  candidates <- c("Lookup", "Insert", "Delete", "Iteration\n(Key)", "Iteration\n(Entry)", "Equality\n(Distinct)", "Equality\n(Derived)", "Footprint\n(32-bit)", "Footprint\n(64-bit)")
  
  if (dataType == "MAP") {
    candidates
  } else {
    candidates[candidates != "Iteration\n(Entry)"]
  }
}

createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- orderedBenchmarkNames(dataType)
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  


  ###
  # Create boxplots as well
  ##
  outFileName <-paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "boxplot", sep="-"), "pdf", sep=".")
  fontScalingFactor <- 1.3
  pdf(outFileName, family = "Times", width = 9, height = 3.5)
  
  selection <- tableAll[2:NCOL(tableAll)]
  names(selection) <- orderedBenchmarkNamesForBoxplot(dataType)
  
  par(mar = c(6.5,3.5,0,0) + 0.1)
  boxplot(selection, ylim=range(-0.1, 1.0), las=2,
          cex.lab=fontScalingFactor, cex.axis=fontScalingFactor, cex.main=fontScalingFactor, cex.sub=fontScalingFactor)
  
#   abline(v =  5.5)
  
  #abline(h =  0.75, lty=3)
  #abline(h =  0.5, lty=3)
  #abline(h =  0.25, lty=3)
  abline(h =  0)
  abline(h = -0.5, lty=3)
  dev.off()
  embed_fonts(outFileName)
  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)

#'@title arrange_ggplot2
#'@description
#'Arranges ggplot2 plot objects in a grid using code from Stephen Turner's website.
#'from http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html
#'use pdf(); arrange(p1,p2,ncol=1); dev.off() to save the plot to a file
#'@param list list of plot objects
#'@param ncol number of columns, can be null
#'@param nrow number of rows, can be null
#'@param as.table boolean, determines order in grid
#'@export

arrange_ggplot2 <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
  library(ggplot2)
  library(grid)
  vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
  
  dots <- list(...)
  n <- length(dots)
  if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
  if(is.null(nrow)) { nrow = ceiling(n/ncol)}
  if(is.null(ncol)) { ncol = ceiling(n/nrow)}
  ## NOTE see n2mfrow in grDevices for possible alternative
  grid.newpage()
  pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
  ii.p <- 1
  for(ii.row in seq(1, nrow)){
    ii.table.row <- ii.row	
    if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
    for(ii.col in seq(1, ncol)){
      ii.table <- ii.p
      if(ii.p > n) break
      print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
      ii.p <- ii.p + 1
    }
  }
}

#'@title vertical_dotchart
#'@description
#'Produces a vertical dot chart, with a metric variable giving the length of a horizontal 
#'line segment and a dot colored by a grouping variable.  Each row in the data frame becomes a 
#'row in the dotchart.  The y variable is a label for each row, and rows can be grouped
#'by a grouping variable.  The plot can be sorted in descending order of the x metric variable,
#'or grouped by the grouping variable and then sorted.   
#'
#'@param df Data frame to be plotted
#'@param x_var Name of the metric variable to be plotted, as a string
#'@param x_label Name of the metric variable as a plot legend string
#'@param y_var Name of the categorical variable labeling each row in the data frame
#'@param y_label Name of the categorical variable, as a plot legend string
#'@param y_group_var Name of a categorical variable which groups the rows
#'@param legend_title Title of the legend for groups, defaults to "Experiment Group"
#'@param sort.by.xvar Boolean flag to sort rows by the metric variable, defaults to TRUE
#'@param group.by.ygroup Boolean flag to sort groups of rows by the grouping variable, defaults to TRUE
#'@return ggplot2 object
#'@export

vertical_dotchart <- function(df, 
                              x_var = xvar, 
                              x_label = xlabel, 
                              y_var = yvar, 
                              y_label = "Experiment", 
                              y_group_var = NULL, 
                              legend_title = "Experiment Group",
                              sort.by.xvar = TRUE, 
                              group.by.ygroup = TRUE) {
  
  require(ggplot2)
  require(ggthemes)

  # prevent a conflict if the user doesn't set the flag but leaves off a grouping variable
  if(is.null(y_group_var)) {
    group.by.ygroup = FALSE
  }
  
  if(sort.by.xvar == TRUE) {
      df$yvar_sorted <- reorder(df[[y_var]], df[[x_var]])
      plt <- ggplot(df, aes_string(x = x_var, y = "yvar_sorted")) 
    } else {
      plt <- ggplot(df, aes_string(x = x_var, y = y_var))
    }

  plt <- plt + geom_segment(aes(yend = experiments), xend = 0, color = "grey50")
  plt <- plt + ylab(y_label)
  plt <- plt + xlab(x_label)
  
  if(!is.null(y_group_var)) {
    plt <- plt + geom_point(size = 3, aes_string(color = y_group_var)) + labs(color = legend_title)
  } else {
    plt <- plt + geom_point(size = 3)
  }

  plt <- plt + theme_pander()
  plt <- plt + theme(panel.grid.major.x = element_blank(),
                     panel.grid.minor.x = element_blank(),
                     strip.background = element_blank(), strip.text = element_blank())
  if(group.by.ygroup == TRUE) {
    form <- as.formula(paste(y_group_var, "~", ".", sep = " "))
    plt <- plt + facet_grid(form, scales = "free_y", space = "free_y")
  }
  
  plt
}







#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141215_0357"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")


createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=TRUE, add.comment=TRUE, 
                               add.row.margin=TRUE, add.col.margin=TRUE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  
  # determine position index of rows
  # --------------------------------
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r <- table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  # --------------------------------

  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c <- table_end_c + 1 } 

  


  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = 1, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1, spacer_rows=2) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 1 + spacer_rows
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#' This R script will process all R mardown files (those with in_ext file extention,
#' .rmd by default) in the current working directory. Files with a status of
#' 'processed' will be converted to markdown (with out_ext file extention, '.markdown'
#' by default). It will change the published parameter to 'true' and change the
#' status parameter to 'publish'.
#' 
#' @param path_site path to the local root storing the site files
#' @param dir_rmd directory containing R Markdown files (inputs)
#' @param dir_md directory containing markdown files (outputs)
#' @param url_images where to store/get images created from plots directory +"/" (relative to path_site)
#' @param out_ext the file extention to use for processed files.
#' @param in_ext the file extention of input files to process.
#' @param recursive should rmd files in subdirectories be processed.
#' @return nothing.
#' @author Jason Bryer <jason@bryer.org> edited by Andy South
rmd2md <- function( path_site = getwd(),
                    dir_rmd = "_rmd",
                    dir_md = "_posts",                              
                    #dir_images = "figures",
                    url_images = "figures/",
                    out_ext='.md', 
                    in_ext='.rmd', 
                    recursive=FALSE) {
  
  require(knitr, quietly=TRUE, warn.conflicts=FALSE)

  #andy change to avoid path problems when running without sh on windows 
  files <- list.files(path=file.path(path_site,dir_rmd), pattern=in_ext, ignore.case=TRUE, recursive=recursive)
  
  for(f in files) {
    message(paste("Processing ", f, sep=''))
    content <- readLines(file.path(path_site,dir_rmd,f))
    frontMatter <- which(substr(content, 1, 3) == '---')
    if(length(frontMatter) >= 2 & 1 %in% frontMatter) {
      statusLine <- which(substr(content, 1, 7) == 'status:')
      publishedLine <- which(substr(content, 1, 10) == 'published:')
      if(statusLine > frontMatter[1] & statusLine < frontMatter[2]) {
        status <- unlist(strsplit(content[statusLine], ':'))[2]
        status <- sub('[[:space:]]+$', '', status)
        status <- sub('^[[:space:]]+', '', status)
        if(tolower(status) == 'process') {
          #This is a bit of a hack but if a line has zero length (i.e. a
          #black line), it will be removed in the resulting markdown file.
          #This will ensure that all line returns are retained.
          content[nchar(content) == 0] <- ' '
          message(paste('Processing ', f, sep=''))
          content[statusLine] <- 'status: publish'
          content[publishedLine] <- 'published: true'
          
          #andy change to path
          outFile <- file.path(path_site, dir_md, paste0(substr(f, 1, (nchar(f)-(nchar(in_ext)))), out_ext))
                   
          #render_markdown(strict=TRUE)
          #render_markdown(strict=FALSE) #code didn't render properly on blog
          
          #andy change to render for jekyll
          render_jekyll(highlight = "pygments")
          #render_jekyll(highlight = "prettify") #for javascript
          
          opts_knit$set(out.format='markdown') 
                    
          # andy BEWARE don't set base.dir!! it caused me problems
          # "base.dir is never used when composing the URL of the figures; it is 
          # only used to save the figures to a different directory. 
          # The URL of an image is always base.url + fig.path"
          # https://groups.google.com/forum/#!topic/knitr/18aXpOmsumQ
                    
          opts_knit$set(base.url = "/")
          opts_chunk$set(fig.path = url_images)                     
          
          try(knit(text=content, output=outFile), silent=FALSE)
          
        } else {
          warning(paste("Not processing ", f, ", status is '", status, 
                        "'. Set status to 'process' to convert.", sep=''))
        }
      } else {
        warning("Status not found in front matter.")
      }
    } else {
      warning("No front matter found. Will not process this file.")
    }
  }
  invisible()
}REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	;-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     200    100    200   15]
		%PlanetaDomovska   [600     1300   100    250   30]
		%PlanetaZluta      [600     1300   100    250   30]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1300]
	]
	;-- !!!!!!!!!!!!!!! HARDOCDED VALUES !!!!!!!!!!!!!!!!!!!!!
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1300 100 250 30]
		]
	]

	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]#!/usr/bin/env Rscript
setwd("~/tmp/jmh-dscg-benchmarks-results")

timestamp <- "20141205_0033"

# install.packages("vioplot")
# install.packages("beanplot")
# install.packages("ggplot2")
# install.packages("reshape2")
# install.packages("functional")
# install.packages("plyr")
# install.packages("extrafont")
# install.packages("scales")
library(vioplot)
library(beanplot)
library(ggplot2)
library(reshape2)
library(functional)
library(plyr) # needed to access . function
library(extrafont)
library(scales)
loadfonts()


capwords <- function(s, strict = FALSE) {
  cap <- function(s) paste(toupper(substring(s, 1, 1)),
{s <- substring(s, 2); if(strict) tolower(s) else s},
sep = "", collapse = " " )
sapply(strsplit(s, split = " "), cap, USE.NAMES = !is.null(names(s)))
}


calculateMemoryFootprintOverhead <- function(requestedDataType, dataStructureOrigin) {
  ###
  # Load 32-bit and 64-bit data and combine them.
  ##
  dss32_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "32bit", timestamp, sep="-"), "csv", sep=".")
  dss32_stats <- read.csv(dss32_fileName, sep=",", header=TRUE)
  dss32_stats <- within(dss32_stats, arch <- factor(32))
  #
  dss64_fileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/map-sizes-and-statistics", "64bit", timestamp, sep="-"), "csv", sep=".")
  dss64_stats <- read.csv(dss64_fileName, sep=",", header=TRUE)
  dss64_stats <- within(dss64_stats, arch <- factor(64))
  #
  dss_stats <- rbind(dss32_stats, dss64_stats)
  
  
  classNameTheOther <- switch(dataStructureOrigin, 
                              Scala = paste("scala.collection.immutable.Hash", capwords(tolower(requestedDataType)), sep = ""),
                              Clojure = paste("clojure.lang.PersistentHash", capwords(tolower(requestedDataType)), sep = ""))  

  classNameOurs <-  paste("org.eclipse.imp.pdb.facts.util.Trie", capwords(tolower(requestedDataType)), "_5Bits", sep = "")
  
  ###
  # If there are more measurements for one size, calculate the median.
  # Currently we only have one measurment.
  ##
  dss_stats_meltByElementCount <- melt(dss_stats, id.vars=c('elementCount', 'className', 'dataType', 'arch'), measure.vars=c('footprintInBytes')) # measure.vars=c('footprintInBytes')
  dss_stats_castByMedian <- dcast(dss_stats_meltByElementCount, elementCount + className + dataType + arch ~ "footprintInBytes_median", median, fill=0)
  
  mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_5Bits"
  setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_5Bits"

#   mapClassName <- "org.eclipse.imp.pdb.facts.util.TrieMap_BleedingEdge"
#   setClassName <- "org.eclipse.imp.pdb.facts.util.TrieSet_BleedingEdge"
  
  ###
  # Calculate different baselines for comparison.
  ##
  dss_stats_castByBaselinePDBDynamic <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == mapClassName | dss_stats_castByMedian$className == setClassName,], min)
  names(dss_stats_castByBaselinePDBDynamic) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDBDynamic')
  
  # dss_stats_castByBaselinePDB0To4 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet",], min)
  # names(dss_stats_castByBaselinePDB0To4) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To4')
  # 
  # dss_stats_castByBaselinePDB0To8 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",], min)
  # names(dss_stats_castByBaselinePDB0To8) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To8')
  # 
  # dss_stats_castByBaselinePDB0To12 <- aggregate(footprintInBytes_median ~ elementCount + dataType + arch, dss_stats_castByMedian[dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" | dss_stats_castByMedian$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",], min)
  # names(dss_stats_castByBaselinePDB0To12) <- c('elementCount', 'dataType', 'arch', 'footprintInBytes_baselinePDB0To12')
  
  ###
  # Merges baselines.
  ##
  dss_stats_with_min <- merge(dss_stats_castByMedian, dss_stats_castByBaselinePDBDynamic)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To4)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To8)
  # dss_stats_with_min <- merge(dss_stats_with_min, dss_stats_castByBaselinePDB0To12)
  
  # http://www.dummies.com/how-to/content/how-to-add-calculated-fields-to-data-in-r.navId-812016.html
  dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDBDynamic <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDBDynamic)
  dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDBDynamic <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDBDynamic / dss_stats_with_min$footprintInBytes_median))
  #
  # dss_stats_with_min <- within(dss_stats_with_min, memoryOverheadFactorComparedToPDB0To8 <- dss_stats_with_min$footprintInBytes_median / footprintInBytes_baselinePDB0To8)
  # dss_stats_with_min <- within(dss_stats_with_min, memorySavingComparedToPDB0To8 <- 1 - (dss_stats_with_min$footprintInBytes_baselinePDB0To8 / dss_stats_with_min$footprintInBytes_median))
  
  ###
  # How good score our specializations [map]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMapDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieMap0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # How good score our specializations [set]?
  ##
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "32",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSetDynamic" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To8" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "org.eclipse.imp.pdb.facts.util.TrieSet0To12" & dss_stats_with_min$arch == "64",]$memorySavingComparedToPDBDynamic)
  
  
  ###
  # Compare generic data structure to competition.
  ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memorySavingComparedToPDBDynamic)
  #
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.gs.collections.impl.map.mutable.UnifiedMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "java.util.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.mutable.HashMap",]$memorySavingComparedToPDBDynamic)
  # median(dss_stats_with_min[dss_stats_with_min$className == "com.google.common.collect.ImmutableMap",]$memorySavingComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDBDynamic)
  median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDBDynamic)
  
  
  # ###
  # # Compare specialization to competition.
  # ##
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashMap" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "clojure.lang.PersistentHashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  # 
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "32",]$memoryOverheadFactorComparedToPDB0To8)
  # median(dss_stats_with_min[dss_stats_with_min$className == "scala.collection.immutable.HashSet" & dss_stats_with_min$arch == "64",]$memoryOverheadFactorComparedToPDB0To8)
  
#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className != mapClassName & dss_stats_with_min$className != setClassName,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   # dss.tmp.cast_Map <- dcast(dss.tmp[dss.tmp$dataType == "MAP",], elementCount ~ className + dataType + arch + variable)
#   # dss.tmp.cast_Set <- dcast(dss.tmp[dss.tmp$dataType == "SET",], elementCount ~ className + dataType + arch + variable)

#   sel.tmp <- dss_stats_with_min[dss_stats_with_min$className == classNameTheOther,]
#   dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch', 'dataType', 'className'), measure.vars = c('memoryOverheadFactorComparedToPDBDynamic'))
#   
#   res <- dcast(dss.tmp[dss.tmp$dataType == requestedDataType,], elementCount ~ className + arch + dataType + variable)
#   
#   # sort: first 32 then 64 bit, inside first Scala, then Clojure
#   # res[,c(1,4,2,5,3)]
#   
#   res

  theOther <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameTheOther & dss_stats_castByMedian$dataType == requestedDataType,]
  ours <- dss_stats_castByMedian[dss_stats_castByMedian$className == classNameOurs & dss_stats_castByMedian$dataType == requestedDataType,]

  memorySavingComparedToTheOther <- 1 - (ours$footprintInBytes_median / theOther$footprintInBytes_median)

  sel.tmp = data.frame(ours$elementCount, ours$arch, memorySavingComparedToTheOther)
  colnames(sel.tmp) <- c('elementCount', 'arch', 'memorySavingComparedToTheOther')
  dss.tmp <- melt(sel.tmp, id.vars=c('elementCount', 'arch'), measure.vars = c('memorySavingComparedToTheOther'))

  res <- dcast(dss.tmp, elementCount ~ arch + variable)
  # print(res)
  res
}





formatPercent__ <- function(arg,rounding=F) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    argTimes100 <- as.numeric(arg) * 100
    digits = 0
    
    if (rounding==T) {
      x <- format(round(argTimes100, digits), nsmall=digits, digits=digits, scientific=FALSE)            
    } else {
      x <- format(argTimes100, nsmall=digits, digits=digits, scientific=FALSE)      
    }      
  }
  
  # paste(x, "\\%", sep = "")
  x
}

formatPercent <- Vectorize(formatPercent__)

formatNsmall2__ <- function(arg,rounding=T) {
  if (is.nan(arg)) {
    x <- "0"
  } else {
    if (rounding==T) {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)            
    } else {
      x <- format(round(as.numeric(arg), 2), nsmall=2, digits=2, scientific=FALSE)
    }      
  }
}

formatNsmall2 <- Vectorize(formatNsmall2__)


latexMath__ <- function(arg) {
  paste("$", arg, "$", sep = "")
}

latexMath <- Vectorize(latexMath__)


# latexMathFactor__ <- function(arg) {
#   if (as.numeric(arg) < 1) {
#     paste("${\\color{red}", arg, "\\times}$", sep = "")
#   } else {
#     paste("$", arg, "\\times$", sep = "")
#   }
# }

latexMathFactor__ <- function(arg) {  
  if (as.numeric(arg) < 1) {
    paste("${\\color{red}", arg, "}$", sep = "")
  } else {
    paste("$", arg, "$", sep = "")
  }
}

latexMathFactor <- Vectorize(latexMathFactor__)


latexMathPercent__ <- function(arg) {
  arg_fmt <- formatPercent(arg)
  
  postfix <- "\\%"
  
  if (is.na(arg) | is.nan(arg)) { #  | !is.numeric(arg)
    paste("$", "--", "$", sep = "")
  } else {
    if (as.numeric(arg) < 0) {
      paste("${\\color{red}", arg_fmt, postfix, "}$", sep = "")
    } else {
      paste("$", arg_fmt, postfix, "$", sep = "")
    }
  }
}

latexMathPercent <- Vectorize(latexMathPercent__)


getBenchmarkMethodName__ <- function(arg) {
  strsplit(as.character(arg), split = "[.]time")[[1]][2]
}

getBenchmarkMethodName <- Vectorize(getBenchmarkMethodName__)


benchmarksFileName <- paste(paste("/Users/Michael/Dropbox/Research/hamt-improved-results/results.all", timestamp, sep="-"), "log", sep=".")
benchmarks <- read.csv(benchmarksFileName, sep=",", header=TRUE, stringsAsFactors=FALSE)
colnames(benchmarks) <- c("Benchmark", "Mode", "Threads", "Samples", "Score", "ScoreError", "Unit", "Param_dataType", "Param_run", "Param_sampleDataSelection", "Param_size", "Param_valueFactoryFactory")

benchmarks$Benchmark <- getBenchmarkMethodName(benchmarks$Benchmark)

benchmarksCleaned <- benchmarks[benchmarks$Param_sampleDataSelection == "MATCH" & !grepl("@", benchmarks$Benchmark),c(-2,-3,-4,-7,-10)]
# benchmarksCleaned[benchmarksCleaned$Param_valueFactoryFactory == "VF_PDB_PERSISTENT_BLEEDING_EDGE", ]$Param_valueFactoryFactory <- "VF_PDB_PERSISTENT_CURRENT"

###
# If there are more measurements for one size, calculate the median.
# Currently we only have one measurment.
##
benchmarksCleaned = ddply(benchmarksCleaned, c("Benchmark", "Param_dataType", "Param_size", "Param_valueFactoryFactory"), function(x) c(Score = median(x$Score), ScoreError = median(x$ScoreError)))

#benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory')) # 'Param_valueFactoryFactory'

#ggplot(data=benchmarksByName, aes(x=variable, y=value, fill=as.factor(Param_valueFactoryFactory))) + geom_histogram(position="dodge", stat="identity")  + xlab("node branching factor") + ylab("value") + scale_x_discrete(labels=as.character(seq(1, 64)))

ggplot(benchmarks[benchmarks$Param_size == 1000000,], aes(x=Param_valueFactoryFactory, y=Score, group=Benchmark, fill=Param_valueFactoryFactory)) + geom_bar(position="dodge", stat="identity") + facet_grid(Benchmark ~ Param_size, scales = "free")

#benchmarksCast <- dcast(benchmarksByName, Benchmark + Param_size ~ Param_valueFactoryFactory + Param_dataType + variable)

#benchmarksByName <- melt(benchmarksCleaned[benchmarksCleaned$Param_dataType == "MAP",], id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))
benchmarksByName <- melt(benchmarksCleaned, id.vars=c('Benchmark', 'Param_size', 'Param_dataType', 'Param_valueFactoryFactory'))

# benchmarksTmpCast <- dcast(benchmarksByName, Benchmark + Param_size + Param_dataType ~ Param_valueFactoryFactory + variable)
# benchmarksTmpCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_CLOJURE_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score
# benchmarksTmpCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- benchmarksTmpCast$VF_SCALA_Score / benchmarksTmpCast$VF_PDB_PERSISTENT_CURRENT_Score

# benchmarksByName$value <- formatPercent(benchmarksByName$value, rounding=F)
# benchmarksByName$value <- format(benchmarksByName$value, nsmall=2, digits=3, scientific=TRUE)

# benchmarksByName$Param_sizeLog2 <- paste("2^", log2(benchmarksByName$Param_size), sep = "")
# benchmarksByName$Param_sizeLog2 <- latexMath(paste("2^", log2(benchmarksByName$Param_size), sep = ""))

benchmarksByNameOutput <- data.frame(benchmarksByName)
# benchmarksByNameOutput$value <- formatPercent(benchmarksByName$value, rounding=F)
benchmarksByNameOutput$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksByName$Param_size), "}", sep = ""))
# benchmarksByNameOutput$Param_size <- latexMath(benchmarksByName$Param_size)
# benchmarksByNameOutput$value <- latexMath(benchmarksByName$value)

###
# OLD CODE
##

# # TODO: ensure that Param_dataType is always the same for each invocation
# benchmarksCast_Map <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "MAP",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# benchmarksCast_Set <- dcast(benchmarksByNameOutput[benchmarksByNameOutput$Param_dataType == "SET",], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
# 
# benchmarksCast_Map$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Map$Param_size), "}", sep = ""))
# benchmarksCast_Map$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Map$VF_CLOJURE_Score, "\\pm", benchmarksCast_Map$VF_CLOJURE_ScoreError))
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Map$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Map$VF_SCALA_Score, "\\pm", benchmarksCast_Map$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_SCALA_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Map$VF_CLOJURE_Score / benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_SCALA_Score)
# benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Map$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Map$VF_CLOJURE_Score)
# 
# benchmarksCast_Set$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast_Set$Param_size), "}", sep = ""))
# benchmarksCast_Set$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast_Set$VF_CLOJURE_Score, "\\pm", benchmarksCast_Set$VF_CLOJURE_ScoreError))
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_ScoreError))
# benchmarksCast_Set$VF_SCALA_Interval <- latexMath(paste(benchmarksCast_Set$VF_SCALA_Score, "\\pm", benchmarksCast_Set$VF_SCALA_ScoreError))
# ###
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_SCALA_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast_Set$VF_CLOJURE_Score / benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_SCALA_Score)
# benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast_Set$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast_Set$VF_CLOJURE_Score)

#benchmarksCast <- data.frame(benchmarksCast_Map, benchmarksCast_Set)

# formatPercent(benchmarksCast$VF_CLOJURE_Score, rounding=F)
# 
# format(benchmarksCast$VF_CLOJURE_Score, nsmall=2, digits=3, scientific=TRUE)
# format(benchmarksCast$VF_CLOJURE_ScoreError, nsmall=2, digits=3, scientific=TRUE)

# write.table(benchmarksCast_Map[,c(1,9,13,14,15)], file = "results_latex_map.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(benchmarksCast_Set[,c(1,9,13,14,15)], file = "results_latex_set.tex", sep = " & ", row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE, eol = " \\\\ \n")

# orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
# orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
# 
# orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
# colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")

# selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
#   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
# })

selectComparisionColumns <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)

  #tmp.m$value <- formatNsmall2(tmp.m$value, rounding=T)

  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  # tmp.c$Param_size <- latexMath(paste("2^{", log2(tmp.c$Param_size), "}", sep = ""))
  tmp.c
}

selectComparisionColumnsSummary <- function(inputData, measureVars, orderingByName) {
  tmp.m <- melt(data=join(inputData, orderingByName), id.vars=c('BenchmarkSortingID', 'Benchmark', 'Param_size'), measure.vars=measureVars)
  
  tmp.c <- dcast(tmp.m, Param_size ~ BenchmarkSortingID + Benchmark + variable)
  
  mins.c <- apply(tmp.c, c(2), min) # as.numeric(formatNsmall2(apply(tmp.c, c(2), min), rounding=T))
  maxs.c <- apply(tmp.c, c(2), max) # as.numeric(formatNsmall2(apply(tmp.c, c(2), max), rounding=T))
  #mean.c <- apply(tmp.c, c(2), mean)
  medians.c <- apply(tmp.c, c(2), median) # as.numeric(formatNsmall2(apply(tmp.c, c(2), median), rounding=T))

  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

calculateMemoryFootprintSummary <- function(inputData) {
  mins.c <- apply(inputData, c(2), min) # as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
  maxs.c <- apply(inputData, c(2), max) # as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
  #mean.c <- apply(inputData, c(2), mean)
  medians.c <- apply(inputData, c(2), median) # as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
  
  res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
  rownames(res) <- c('minimum', 'maximum', 'median')
  res
}

# calculateMemoryFootprintSummary <- function(inputData) {
#   mins.c <- as.numeric(formatNsmall2(apply(inputData, c(2), min), rounding=T))
#   maxs.c <- as.numeric(formatNsmall2(apply(inputData, c(2), max), rounding=T))
#   medians.c <- as.numeric(formatNsmall2(apply(inputData, c(2), median), rounding=T))
#   
#   res <- data.frame(rbind(mins.c, maxs.c, medians.c))[-1]
#   rownames(res) <- c('minimum', 'maximum', 'median')
#   res
# }


###
# OLD CODE
##

# tableMapAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll_summary <- selectComparisionColumnsSummary(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# tableMapAll <- selectComparisionColumns(benchmarksCast_Map, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# tableSetAll <- selectComparisionColumns(benchmarksCast_Set, c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score', 'VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score'))
# 
# memFootprintMap <- calculateMemoryFootprintOverhead("MAP") 
# memFootprintMap_fmt <- data.frame(sapply(1:NCOL(memFootprintMap), function(col_idx) { memFootprintMap[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintMap[,c(col_idx)], rounding=T))}))
# colnames(memFootprintMap_fmt) <- colnames(memFootprintMap)
# #
# memFootprintSet <- calculateMemoryFootprintOverhead("SET") 
# memFootprintSet_fmt <- data.frame(sapply(1:NCOL(memFootprintSet), function(col_idx) { memFootprintSet[,c(col_idx)] <- latexMathFactor(formatNsmall2(memFootprintSet[,c(col_idx)], rounding=T))}))
# colnames(memFootprintSet_fmt) <- colnames(memFootprintSet)
# 
# tableMapAll <- data.frame(tableMapAll, memFootprintMap_fmt[,c(2,3,4,5)])
# tableSetAll <- data.frame(tableSetAll, memFootprintSet_fmt[,c(2,3,4,5)])
# 
# 
# 
# tableMapAll_summary <- data.frame(tableMapAll_summary, calculateMemoryFootprintSummary(memFootprintMap))
# tableSetAll_summary <- data.frame(tableSetAll_summary, calculateMemoryFootprintSummary(memFootprintSet))
# 
# tableMapAll_summary_fmt <- data.frame(sapply(1:NCOL(tableMapAll_summary), function(col_idx) { tableMapAll_summary[,c(col_idx)] <- latexMathFactor(tableMapAll_summary[,c(col_idx)]) }))
# rownames(tableMapAll_summary_fmt) <- rownames(tableMapAll_summary)
# tableSetAll_summary_fmt <- data.frame(sapply(1:NCOL(tableSetAll_summary), function(col_idx) { tableSetAll_summary[,c(col_idx)] <- latexMathFactor(tableSetAll_summary[,c(col_idx)]) }))
# rownames(tableSetAll_summary_fmt) <- rownames(tableSetAll_summary)
# 
# write.table(tableMapAll_summary_fmt, file = "all-benchmarks-map-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll_summary_fmt, file = "all-benchmarks-set-summary.tex", sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# 
# # tableMapAll <- data.frame(sapply(1:NCOL(tableMapAll), function(col_idx) { tableMapAll[,c(col_idx)] <- paste("\\tableMapAll_c", col_idx, "{", tableMapAll[,c(col_idx)], "}", sep = "") })) # colnames(tableMapAll)[col_idx]
# # tableSetAll <- data.frame(sapply(1:NCOL(tableSetAll), function(col_idx) { tableSetAll[,c(col_idx)] <- paste("\\tableSetAll_c", col_idx, "{", tableSetAll[,c(col_idx)], "}", sep = "") })) # colnames(tableSetAll)[col_idx]
# 
# write.table(tableMapAll, file = "all-benchmarks-map.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
# write.table(tableSetAll, file = "all-benchmarks-set.tex", sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")


createTable <- function(input, dataType, dataStructureOrigin, measureVars) {
  lowerBoundExclusive <- 1
  
  benchmarksCast <- dcast(input[input$Param_dataType == dataType & input$Param_size > lowerBoundExclusive,], Benchmark + Param_size ~ Param_valueFactoryFactory + variable)
    
  benchmarksCast$Param_out_sizeLog2 <- latexMath(paste("2^{", log2(benchmarksCast$Param_size), "}", sep = ""))
  benchmarksCast$VF_CLOJURE_Interval <- latexMath(paste(benchmarksCast$VF_CLOJURE_Score, "\\pm", benchmarksCast$VF_CLOJURE_ScoreError))
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Interval <- latexMath(paste(benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score, "\\pm", benchmarksCast$VF_PDB_PERSISTENT_CURRENT_ScoreError))
  benchmarksCast$VF_SCALA_Interval <- latexMath(paste(benchmarksCast$VF_SCALA_Score, "\\pm", benchmarksCast$VF_SCALA_ScoreError))
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_SCALA_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  benchmarksCast$VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score <- (benchmarksCast$VF_CLOJURE_Score / benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score <- (benchmarksCast$VF_PDB_PERSISTENT_CURRENT_Score / benchmarksCast$VF_CLOJURE_Score)
  ###
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_Score)
  benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings <- (1 - benchmarksCast$VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_Score)
  
  orderedBenchmarkNames <- c("ContainsKey", "Insert", "RemoveKey", "Iteration", "EntryIteration", "EqualsRealDuplicate", "EqualsDeltaDuplicate")
  orderedBenchmarkIDs <- seq(1:length(orderedBenchmarkNames))
  
  orderingByName <- data.frame(orderedBenchmarkIDs, orderedBenchmarkNames)
  colnames(orderingByName) <- c("BenchmarkSortingID", "Benchmark")
  
  # selectComparisionColumns <- Vectorize(function(castedData, benchmarkName) {
  #   data.frame(castedData[castedData$Benchmark == benchmarkName,])[,c(13,14,15)]
  # })
    
  tableAll_summary <- selectComparisionColumnsSummary(benchmarksCast, measureVars, orderingByName)
  
  memFootprint <- calculateMemoryFootprintOverhead(dataType, dataStructureOrigin) 
  memFootprint <- memFootprint[memFootprint$elementCount > lowerBoundExclusive,]
  memFootprint_fmt <- data.frame(sapply(1:NCOL(memFootprint), function(col_idx) { memFootprint[,c(col_idx)] <- latexMathPercent(memFootprint[,c(col_idx)])}))
  colnames(memFootprint_fmt) <- colnames(memFootprint)
    
  tableAll <- selectComparisionColumns(benchmarksCast, measureVars, orderingByName)
  tableAll <- tableAll[tableAll$Param_size > lowerBoundExclusive,]
  tableAll <- data.frame(tableAll, memFootprint[,c(2,3)])      
  
  tableAll_fmt <- data.frame(
    latexMath(paste("2^{", log2(tableAll$Param_size), "}", sep = "")),
    sapply(2:NCOL(tableAll), function(col_idx) { tableAll[,c(col_idx)] <- latexMathPercent(tableAll[,c(col_idx)])}))
  colnames(tableAll_fmt) <- colnames(tableAll)
  
  tableAll_summary <- data.frame(tableAll_summary, calculateMemoryFootprintSummary(memFootprint))
  tableAll_summary_fmt <- data.frame(sapply(1:NCOL(tableAll_summary), function(col_idx) { tableAll_summary[,c(col_idx)] <- latexMathPercent(tableAll_summary[,c(col_idx)])}))
  rownames(tableAll_summary_fmt) <- rownames(tableAll_summary)

  fileNameSummary <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), "summary", sep="-"), "tex", sep=".")
  write.table(tableAll_summary_fmt, file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_summary_fmt), file = fileNameSummary, sep = " & ", row.names = TRUE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  
  fileName <- paste(paste("all", "benchmarks", tolower(dataStructureOrigin), tolower(dataType), sep="-"), "tex", sep=".")
  write.table(tableAll_fmt, file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")
  #write.table(t(tableAll_fmt), file = fileName, sep = " & ", row.names = FALSE, col.names = FALSE, append = FALSE, quote = FALSE, eol = " \\\\ \n")  
}

# measureVars_Scala <- c('VF_SCALA_BY_VF_PDB_PERSISTENT_CURRENT_Score')
# measureVars_Clojure <- c('VF_CLOJURE_BY_VF_PDB_PERSISTENT_CURRENT_Score')

measureVars_Scala <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_SCALA_ScoreSavings')
measureVars_Clojure <- c('VF_PDB_PERSISTENT_CURRENT_BY_VF_CLOJURE_ScoreSavings')

createTable(benchmarksByNameOutput, "SET", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "SET", "Clojure", measureVars_Clojure)
createTable(benchmarksByNameOutput, "MAP", "Scala", measureVars_Scala)
createTable(benchmarksByNameOutput, "MAP", "Clojure", measureVars_Clojure)


menu <- function(){
	print( "------------------------------------------------------" )
	print( "-------------------------MENU-------------------------" )
	print( "------------------------------------------------------" )
	print( "-------ESCOLHA O ALGORITMO QUE DESEJA EXECUTAR--------" )
	print( "-------[1] - DENFIS+COG-------------------------------" )
	print( "-------[2] - HyFIS+FIRST.MAX--------------------------" )
	print( "-------[3] - HyFIS+LAST.MAX---------------------------" )
	print( "-------[4] - WM+FIRST.MAX-----------------------------" )
	print( "-------[5] - WM+LAST.MAX------------------------------" )
	print( "-------[6] - WM+COG-----------------------------------" )
	print( "-------[7] - GFS.LT.RS+COG----------------------------" )
	print( "-------[8] - GFS.MOGUL+COG----------------------------" )
	print( "-------[9] - PLOTAR VARIAVEIS LINGUISTICAS------------" )
	print( "-------[10] - EXECUTAR TODOS OS ALGORITMOS------------" )
	print( "-------[11] - COMPARAR OS ALGORITMOS------------------" )
	print( "-------[0] - SAIR-------------------------------------" )
	print( "------------------------------------------------------" )
}
runall <- function(){
	performance <- c(1:4)
	source("traffic-WM+FIRST.MAX.r")
	performance[1] <- MSE
	performance[5] <- RMSE
	source("traffic-WM+LAST.MAX.r")
	performance[2] <- MSE
	performance[6] <- RMSE
	source("traffic-HyFIS+FIRST.MAX.r")
	performance[3] <- MSE
	performance[7] <- RMSE
	source("traffic-HyFIS+LAST.MAX.r")
	performance[4] <- MSE
	performance[8] <- RMSE
	print( "-------------------RESULTADOS-------------------------" )
	print( "-------[1] - WM+FIRST.MAX---------MSE: " )
	print(performance[1])
	print( "-------[2] - WM+LAST.MAX----MSE: " )
	print(performance[2])
	print( "-------[3] - HyFIS+FIRST.MAX------MSE: " )
	print(performance[3])
	print( "-------[4] - HyFIS+LAST.MAX-MSE: " )
	print(performance[4])
	print( "-------[1] - WM+FIRST.MAX---------RMSE: " )
	print(performance[5])
	print( "-------[2] - WM+LAST.MAX----RMSE: " )
	print(performance[6])
	print( "-------[3] - HyFIS+FIRST.MAX------RMSE: " )
	print(performance[7])
	print( "-------[4] - HyFIS+LAST.MAX-RMSE: " )
	print(performance[8])
}

clear <- function() {
	elements <- ls() [! ls() %in% c("menu","n","runall", "clear") ]
	rm(list=elements)
}

comparisson <- function(){
    result.test <- cbind(traffic.class , res.test)
    x2 <- seq(from = 1, to = nrow(result.test))
    plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
    lines(x2, result.test[, 2], col="blue", type = "l")
}

readinteger <- function()
{ 
    n <- readline(prompt="Oque deseja? ")
        if(!grepl("^[0-9]+$",n))
        {
            return(readinteger())
        }

    return(as.integer(n))
}

menu()

n <- readinteger()
while(TRUE){
	if(is.na(n)){break}  # breaks when hit enter
    if(n == 0) break;
	if(n != 6) clear()
	if(n == 1) 	{     clear(); source("traffic-DENFIS+COG.r")		}
	else if(n == 2) { clear(); source("traffic-HyFIS+FIRST.MAX.r") }
	else if(n == 3) { clear(); source("traffic-HyFIS+LAST.MAX.r")  }
	else if(n == 4) { clear(); source("traffic-WM+FIRST.MAX.r")    }
	else if(n == 5) { clear(); source("traffic-WM+LAST.MAX.r")     }
	else if(n == 6) { clear(); source("traffic-WM+COG.r")			}
	else if(n == 7) { clear(); source("traffic-LT+COG.r")			}
	else if(n == 8) { clear(); source("traffic-MOGUL+COG.r")		}
	else if(n == 9) plotMF(object.cls)
	else if(n == 10) runall()
    else if(n == 11) comparisson()
	menu()	
        n <- readinteger()
}







menu <- function(){
	print( "------------------------------------------------------" )
	print( "-------------------------MENU-------------------------" )
	print( "------------------------------------------------------" )
	print( "-------ESCOLHA O ALGORITMO QUE DESEJA EXECUTAR--------" )
	print( "-------[1] - DENFIS+COG-------------------------------" )
	print( "-------[2] - HyFIS+FIRST.MAX--------------------------" )
	print( "-------[3] - HyFIS+LAST.MAX---------------------------" )
	print( "-------[4] - WM+FIRST.MAX-----------------------------" )
	print( "-------[5] - WM+LAST.MAX------------------------------" )
	print( "-------[6] - WM+COG-----------------------------------" )
	print( "-------[7] - GFS.LT.RS+COG----------------------------" )
	print( "-------[8] - GFS.MOGUL+COG----------------------------" )
	print( "-------[9] - PLOTAR VARIAVEIS LINGUISTICAS------------" )
	print( "-------[10] - EXECUTAR TODOS OS ALGORITMOS------------" )
	print( "-------[11] - COMPARAR OS ALGORITMOS------------------" )
	print( "-------[0] - SAIR-------------------------------------" )
	print( "------------------------------------------------------" )
}
runall <- function(){
	performance <- c(1:4)
	source("traffic-WM+FIRST.MAX.r")
	performance[1] <- MSE
	performance[5] <- RMSE
	source("traffic-WM+LAST.MAX.r")
	performance[2] <- MSE
	performance[6] <- RMSE
	source("traffic-HyFIS+FIRST.MAX.r")
	performance[3] <- MSE
	performance[7] <- RMSE
	source("traffic-HyFIS+LAST.MAX.r")
	performance[4] <- MSE
	performance[8] <- RMSE
	print( "-------------------RESULTADOS-------------------------" )
	print( "-------[1] - WM+FIRST.MAX---------MSE: " )
	print(performance[1])
	print( "-------[2] - WM+LAST.MAX----MSE: " )
	print(performance[2])
	print( "-------[3] - HyFIS+FIRST.MAX------MSE: " )
	print(performance[3])
	print( "-------[4] - HyFIS+LAST.MAX-MSE: " )
	print(performance[4])
	print( "-------[1] - WM+FIRST.MAX---------RMSE: " )
	print(performance[5])
	print( "-------[2] - WM+LAST.MAX----RMSE: " )
	print(performance[6])
	print( "-------[3] - HyFIS+FIRST.MAX------RMSE: " )
	print(performance[7])
	print( "-------[4] - HyFIS+LAST.MAX-RMSE: " )
	print(performance[8])
}

clear <- function() {
	elements <- ls() [! ls() %in% c("menu","n","runall", "clear") ]
	rm(list=elements)
}

comparisson <- function(){
    result.test <- cbind(traffic.class , res.test)
    x2 <- seq(from = 1, to = nrow(result.test))
    plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
    lines(x2, result.test[, 2], col="blue", type = "l")
}

readinteger <- function()
{ 
    n <- readline(prompt="Oque deseja? ")
        if(!grepl("^[0-9]+$",n))
        {
            return(readinteger())
        }

    return(as.integer(n))
}

menu()

n <- readinteger()
while(TRUE){
	if(is.na(n)){break}  # breaks when hit enter
    if(n == 0) break;
	if(n != 6) clear()
	if(n == 1) 	{     rm(list=ls(all=TRUE)); source("traffic-DENFIS+COG.r")		}
	else if(n == 2) { rm(list=ls(all=TRUE)); source("traffic-HyFIS+FIRST.MAX.r") }
	else if(n == 3) { rm(list=ls(all=TRUE)); source("traffic-HyFIS+LAST.MAX.r")  }
	else if(n == 4) { rm(list=ls(all=TRUE)); source("traffic-WM+FIRST.MAX.r")    }
	else if(n == 5) { rm(list=ls(all=TRUE)); source("traffic-WM+LAST.MAX.r")     }
	else if(n == 6) { rm(list=ls(all=TRUE)); source("traffic-WM+COG.r")			}
	else if(n == 7) { rm(list=ls(all=TRUE)); source("traffic-LT+COG.r")			}
	else if(n == 8) { rm(list=ls(all=TRUE)); source("traffic-MOGUL+COG.r")		}
	else if(n == 9) plotMF(object.cls)
	else if(n == 10) runall()
    else if(n == 11) comparisson()
	menu()	
        n <- readinteger()
}







menu <- function(){
	print( "------------------------------------------------------" )
	print( "-------------------------MENU-------------------------" )
	print( "------------------------------------------------------" )
	print( "-------ESCOLHA O ALGORITMO QUE DESEJA EXECUTAR--------" )
	print( "-------[1] - DENFIS+COG-------------------------------" )
	print( "-------[2] - HyFIS+FIRST.MAX--------------------------" )
	print( "-------[3] - HyFIS+LAST.MAX---------------------------" )
	print( "-------[4] - WM+FIRST.MAX-----------------------------" )
	print( "-------[5] - WM+LAST.MAX------------------------------" )
	print( "-------[6] - WM+COG-----------------------------------" )
	print( "-------[7] - GFS.LT.RS+COG----------------------------" )
	print( "-------[8] - GFS.MOGUL+COG----------------------------" )
	print( "-------[9] - PLOTAR VARIAVEIS LINGUISTICAS------------" )
	print( "-------[10] - EXECUTAR TODOS OS ALGORITMOS------------" )
	print( "-------[11] - COMPARAR OS ALGORITMOS------------------" )
	print( "-------[0] - SAIR-------------------------------------" )
	print( "------------------------------------------------------" )
}
runall <- function(){
	performance <- c(1:4)
	source("traffic-WM+FIRST.MAX.r")
	performance[1] <- MSE
	performance[5] <- RMSE
	source("traffic-WM+LAST.MAX.r")
	performance[2] <- MSE
	performance[6] <- RMSE
	source("traffic-HyFIS+FIRST.MAX.r")
	performance[3] <- MSE
	performance[7] <- RMSE
	source("traffic-HyFIS+LAST.MAX.r")
	performance[4] <- MSE
	performance[8] <- RMSE
	print( "-------------------RESULTADOS-------------------------" )
	print( "-------[1] - WM+FIRST.MAX---------MSE: " )
	print(performance[1])
	print( "-------[2] - WM+LAST.MAX----MSE: " )
	print(performance[2])
	print( "-------[3] - HyFIS+FIRST.MAX------MSE: " )
	print(performance[3])
	print( "-------[4] - HyFIS+LAST.MAX-MSE: " )
	print(performance[4])
	print( "-------[1] - WM+FIRST.MAX---------RMSE: " )
	print(performance[5])
	print( "-------[2] - WM+LAST.MAX----RMSE: " )
	print(performance[6])
	print( "-------[3] - HyFIS+FIRST.MAX------RMSE: " )
	print(performance[7])
	print( "-------[4] - HyFIS+LAST.MAX-RMSE: " )
	print(performance[8])
}

clear <- function() {
	elements <- ls() [! ls() %in% c("menu","n","runall", "clear") ]
	rm(list=elements)
}

comparisson <- function(){
    result.test <- cbind(traffic.class , res.test)
    x2 <- seq(from = 1, to = nrow(result.test))
    plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
    lines(x2, result.test[, 2], col="blue", type = "l")
}

readinteger <- function()
{ 
    n <- readline(prompt="Oque deseja? ")
        if(!grepl("^[0-9]+$",n))
        {
            return(readinteger())
        }

    return(as.integer(n))
}

menu()

n <- readinteger()
while(TRUE){
	if(is.na(n)){break}  # breaks when hit enter
    if(n == 0) break;
	if(n != 6) clear()
	if(n == 1) 	source("traffic-DENFIS+COG.r")
	else if(n == 2) source("traffic-HyFIS+FIRST.MAX.r")
	else if(n == 3) source("traffic-HyFIS+LAST.MAX.r")
	else if(n == 4) source("traffic-WM+FIRST.MAX.r")
	else if(n == 5) source("traffic-WM+LAST.MAX.r")
	else if(n == 6) source("traffic-WM+COG.r")
	else if(n == 7) source("traffic-LT+COG.r")
	else if(n == 8) source("traffic-MOGUL+COG.r")
	else if(n == 9) plotMF(object.cls)
	else if(n == 10) runall()
    else if(n == 11) comparisson()
	menu()	
        n <- readinteger()
}
rm(list=ls(all=TRUE))






## Display the FRBS model
summary(object.cls)

## Plot the membership functions
#plotMF(object.cls)

traffic.class.denorm <- denorm.data(traffic.class, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- denorm.data(res.test, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- round(res.test.denorm)

print("Comparando os valores estimados com os reais")
print(cbind(res.test.denorm, traffic.class.denorm))

## Calculo do erro

y.pred <- res.test
y.real <- traffic.class 
bench <- cbind(y.pred, y.real)
colnames(bench) <- c("pred. val.", "real. val.")
residuals <- (y.real - y.pred)
MSE <- mean(residuals^2)
RMSE <- sqrt(mean(residuals^2))
SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100
err <- c(MSE, RMSE, SMAPE)
names(err) <- c("MSE", "RMSE", "SMAPE")
print("WM: Avaliacao do erro: ")
print(err) 


result.test <- cbind(traffic.class , res.test)
x2 <- seq(from = 1, to = nrow(result.test))
plot(x2, result.test[, 1], col="red", main = "Em vermelho: Os resultados reais. Em azul: os resultados preditos", type = "l", ylab = "MG")
lines(x2, result.test[, 2], col="blue", type = "l")

par(op)
## Display the FRBS model
summary(object.cls)

## Plot the membership functions
#plotMF(object.cls)

traffic.class.denorm <- denorm.data(traffic.class, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- denorm.data(res.test, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- round(res.test.denorm)

print("Comparando os valores estimados com os reais")
print(cbind(res.test.denorm, traffic.class.denorm))

## Calculo do erro

y.pred <- res.test
y.real <- traffic.class 
bench <- cbind(y.pred, y.real)
colnames(bench) <- c("pred. val.", "real. val.")
residuals <- (y.real - y.pred)
MSE <- mean(residuals^2)
RMSE <- sqrt(mean(residuals^2))
SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100
err <- c(MSE, RMSE, SMAPE)
names(err) <- c("MSE", "RMSE", "SMAPE")
print("WM: Avaliacao do erro: ")
print(err) 


result.test <- cbind(traffic.class , res.test)
x2 <- seq(from = 1, to = nrow(result.test))
plot(x2, result.test[, 1], col="red", main = "Mackey Glass: Predicting phase (the Real Data(red) Vs Sim. result(blue))", type = "l", ylab = "MG")
lines(x2, result.test[, 2], col="blue", type = "l")

par(op)
## Display the FRBS model
summary(object.cls)

## Plot the membership functions
#plotMF(object.cls)

traffic.class.denorm <- denorm.data(traffic.class, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- denorm.data(res.test, matrix(traffic.data.range.desnorm[,4],ncol=1,byrow = TRUE), min.scale = 0, max.scale = 1)
res.test.denorm <- round(res.test.denorm)

print("Comparando os valores estimados com os reais")
print(cbind(res.test.denorm, traffic.class.denorm))

## Calculo do erro

y.pred <- res.test
y.real <- traffic.class 
bench <- cbind(y.pred, y.real)
colnames(bench) <- c("pred. val.", "real. val.")
residuals <- (y.real - y.pred)
MSE <- mean(residuals^2)
RMSE <- sqrt(mean(residuals^2))
SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100
err <- c(MSE, RMSE, SMAPE)
names(err) <- c("MSE", "RMSE", "SMAPE")
print("WM: Avaliacao do erro: ")
print(err) 


REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| into rule
				| skip
			]
		]
	]
	
	process-routine-calls: func [code [block!] ctx [word!] ignore [block!] obj [object!] /local rule name][
		parse code rule: [
			some [
				name: word! (
					if all [in obj name/1 not find ignore name/1][
						name/1: decorate-obj-member name/1 ctx
					]
				)
				| path! | set-path! | lit-path!
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				| into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit compose/deep [[
					stack/top: stack/top - 1
					copy-cell stack/top stack/top - 1
					stack/check-call
				]]
			][
				mark: tail output
				unless head? path [
					emit compose/deep [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-word-set
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-word-set*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-word-set* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native (name)	;@@ make a unique name for function's body frame
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original ctx][
		name: get-prefix-func check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		if ctx: find-binding original [
			process-routine-calls body ctx/1 spec select objects ctx/1
		]
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			emit reduce [to set-word! name 'func]
			insert-lf -2
			append/only output spec
			append/only output body
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame name
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-call-directive: func [
		body [block!] global?
		/local name spec cmd types type arg trash ctx
	][
		name: body/1
		switch/default type?/word name [
			word! [name: to word! clean-lf-flag name]
			path! [set [trash name ctx] obj-func-path? body/1]
		][
			throw-error ["invalid function name in #call:" mold body]
		]	
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf either ctx [emit decorate-exec-ctx ctx -2][-1]
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc rejoin [load-cache %version.r ", " now]
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
if ("silent" %in% ls() && silent) {
  fish <- function (...) {}
} else {
  fish <- cat
}
if ("noask" %in% ls() && noask) {
  dog <- fish
} else {
  dog <- cat
  noask <- FALSE
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  dog("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(noask || readline("Nadaljujem? [da/NE] ") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      dog("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      cat("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      dog("Datoteke so pobrisane.\n")
    }
  } else {
    dog("Datoteke niso pobrisane.\n")
  }
} else {
  fish("Ne najdem nobene datoteke PDF.\n")
}
fish("Brišem delovno okolje.\n")
rm(list = ls())
if ("silent" %in% ls() && silent) {
  dog <- function (...) {}
} else {
  dog <- cat
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  cat("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(readline("Nadaljujem? [da/NE]") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      cat("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      cat("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      cat("Datoteke so pobrisane.\n")
    }
  } else {
    cat("Datoteke niso pobrisane.\n")
  }
} else {
  dog("Ne najdem nobene datoteke PDF.\n")
}
dog("Brišem delovno okolje.\n")
rm(list = ls())
if ("silent" %in% ls() && silent) {
  dog <- function (...) {}
} else {
  dog <- cat
}

delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  dog("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(readline("Nadaljujem? [da/NE]") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      dog("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      dog("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      dog("Datoteke so pobrisane.\n")
    }
  } else {
    dog("Datoteke niso pobrisane.\n")
  }
} else {
  dog("Ne najdem nobene datoteke PDF.\n")
}
dog("Brišem delovno okolje.\n")
rm(list = ls())
# 2. faza: Obdelava, uvoz in čiščenje podatkov
source("uvoz/uvoz.r", encoding = "UTF-8")

# 3. faza: Analiza in vizualizacija podatkov
source("vizualizacija/vizualizacija.r", encoding = "UTF-8")

# 4. faza: Napredna analiza podatkov
source("analiza/analiza.r", encoding = "UTF-8")

cat("Končano.\n")delete <- dir(pattern = "\\.pdf$", recursive = TRUE, ignore.case = TRUE)
if (length(delete) > 0) {
  cat("Pobrisane bodo sledeče datoteke:\n", delete, "\n")
  if(readline("Nadaljujem? [da/NE]") == 'da') {
    success <- file.remove(delete)
    if (any(!success)) {
      cat("Sledeče datoteke so pobrisane:\n", delete[success], "\n")
      cat("Sledeče datoteke NISO pobrisane:\n", delete[!success], "\n")
    } else {
      cat("Datoteke so pobrisane.\n")
    }
  } else {
    cat("Datoteke niso pobrisane.\n")
  }
} else {
  cat("Ne najdem nobene datoteke PDF.\n")
}
cat("Brišem delovno okolje.\n")
rm(list = ls())

#' @title random_split_dataset
#' @description 
#' Randomly splits a data frame into a training and test set, with a given fraction of rows in the 
#' test data set.    
#' 
#' @param df data frame to split
#' @param test_fraction 
#' @return list List with "train" and "test" elements
#' @export

random_split_dataset <- function(df, test_fraction) {
  require("caret")
  
  shuffled_df <- df[sample(nrow(df)),]
  indexes = sample(1:nrow(shuffled_df), size=test_fraction*nrow(shuffled_df))
  test = shuffled_df[indexes,]
  train = shuffled_df[-indexes,]
  ret <- list("train" = train, "test" = test)
  ret
}

#' @title get_data_path
#' @description
#' Utility function to help analysis be portable across dev environments and EC2 or
#' StarCluster execution environments.  If passed a "basedir", it uses that as the 
#' basis of a fully qualified path.  If not, it infers a basedir by first checking
#' for environment variable "R_DATA_BASEDIR".  If this does not exist, it then checks
#' for the existence of a variable "data_basedir" in the environment (perhaps from an .rprofile).
#' If this doesn't exist, it uses getwd() as the basedir.  It then appends the "suffix" if 
#' provided, and returns the canonical form of the directory path for the operating system.  
#' 
#' @param string basedir (defaults to NULL)
#' @param string suffix (defaults to NULL)
#' @param string filename
#' @param args  List of command line arguments (to be processed by commandArgs())
#' @examples
#' get_data_path(suffix = "experiment", filename = "foo.r") returns basedir/experiment/foo.r where basedir is the current working directory or the value of the "data_directory" variable.
#' get_data_path(basedir = "/home/foo", suffix = "experiment", filename = "foo.r") returns /home/foo/experiment/foo.r
#' get_data_path(filename = "foo.r", args = commandArgs(trailingOnly = TRUE)) takes the basedir from the command line as the first argument
#' 
#' @export

get_data_path <- function(basedir = "", suffix = "", filename = "", args = "") {
  
  if(basedir != "") {
    p <- c(basedir)
  } else if(args != "") {
    p <- args[1]  
  } else if(Sys.getenv("R_DATA_BASEDIR") != "") {
    p <- c(Sys.getenv("R_DATA_BASEDIR"))
  } else if(exists("data_directory") == TRUE) {
    p <- c(data_directory)
  } else {
    p <- c(getwd())
  }
  

  final <- paste(p, suffix, filename, sep="/", collapse="")
  final
}


#' @title list_files_for_data_path
#' @description 
#' Lists files for a directory, perhaps given a full base directory specified in the 
#' user's environment or in an environment variable.  The goal is to allow the same
#' code to be easily run in multiple desktop environments, by multiple developers
#' who may have different disk directory layouts, and then move that code to servers 
#' and compute clusters, simply by changing one variable which points at the "base" 
#' directory in which files might be found.  
#' 
#' If the "basedir" argument is given, either through an absolute path, or more 
#' likely by passing the command line arguments from a script or an environment/startup variable, 
#' then this basedir is prepended to the "directory" variable.  This full absolute path
#' is then used as the starting point to construct a list of files whose names match the 
#' specified pattern.  This list is constructed using the normal base R function list.files(), 
#' and its return value is passed back to the user, so this function is a drop-in replacement.  
#' 
#' @param character Absolute path to a base directory for searching for directories and files
#' @param character Relative directory or directory path within which files should be searched
#' @param character Pattern for searching for files.  
#' @return A character vector containing file names in the specified directories that match the pattern, or "" if none matched.
#' @export


list_files_for_data_path <- function(basedir = "", directory = "", pattern = "") {
  if(basedir != "") {
    p <- c(basedir)
  } else if(Sys.getenv("R_DATA_BASEDIR") != "") {
    p <- c(Sys.getenv("R_DATA_BASEDIR"))
  } else if(exists("data_directory") == TRUE) {
    p <- c(data_directory)
  } else {
    p <- c(getwd())
  } 
  final <- paste(p, directory, sep="/", collapse="")
  list.files(path = final, pattern=pattern, full.names=TRUE)
}



plotPTraces <- function(pMat, ...)
{
  input_list <- as.list(list(...))
  pMat <- do.call("rbind", pMat)
  n.traces <- min(dim(pMat)[2], 4)
  
  if("log" %in% names(input_list)){
    logY <- input_list$log
    input_list$log <- NULL
  }else{
    logY <- NULL
  }  
  if("main" %in% names(input_list)){
    main <- input_list$main
    input_list$main <- NULL
  }else{
    main <- "Hyperparameter Traces"
  }
  if("xlab" %in% names(input_list)){
    xlab <- input_list$xlab
    input_list$xlab <- NULL
  }else{
    xlab <- "Samples"
  } 
  if("ylab" %in% names(input_list)){
    ylabs <- input_list$ylab
    input_list$ylab <- NULL
  }else{
    if(n.traces == 2)
    {
      ylabs <- c(expression(mu[phi]), expression(sigma[phi]))
    }else{
      ylabs <- c(expression(sigma[epsilon]), expression(mu[phi]), expression(sigma[phi]), "K")
    }
  }
  if("type" %in% names(input_list)){
    type <- input_list$type
    input_list$type <- NULL
  }else{
    type <- "l"
  }
  
  par(oma=c(1,1,2,1), mgp=c(2,1,0), mar = c(3,4,2,1), mfrow=c(2, ceiling(n.traces/2) ))
  for(i in 1:n.traces)
  {
    if(!is.null(logY) & min(pMat[, i]) > 0)
    {
      do.call(plot, c(input_list, list(x=pMat[, i]), list(xlab=xlab), list(ylab=ylabs[i]), list(type=type), list(log=logY)) )
    }else{
      do.call(plot, c(input_list, list(x=pMat[, i]), list(xlab=xlab), list(ylab=ylabs[i]), list(type=type)) )
    }
    #plot(pMat[, i], xlab=xlab, ylab=ylabs[i], type=type)
  }
  title(main=main, outer=T)
}

plotExpectedPhiTrace <- function(phiMat, ...)
{
  input_list <- as.list(list(...))
  
  if("main" %in% names(input_list)){
    main <- input_list$main
    input_list$main <- NULL
  }else{
    main <- expression(paste("Trace E[", phi, "]", sep=""))
  }
  if("xlab" %in% names(input_list)){
    xlab <- input_list$xlab
    input_list$xlab <- NULL
  }else{
    xlab <- "Iteration"
  }
  if("ylab" %in% names(input_list)){
    ylab <- input_list$ylab
    input_list$ylab <- NULL
  }else{
    ylab <- expression(paste("E[", phi, "]", sep=""))
  }
  if("type" %in% names(input_list)){
    type <- input_list$type
    input_list$type <- NULL
  }else{
    type <- "l"
  }
  phiMat <- do.call("cbind", phiMat)
  phiMat <- colMeans(phiMat)
  
  
  do.call( plot, c(input_list, list(x=phiMat), list(xlab=xlab), list(ylab=ylab), list(main=main), list(type=type)) )
  abline(h=1, col="red")
}

plotCUB <- function(reu13.df.obs, bMat, phi.bin, n.use.samples=2000, rescale=F,
                     main="CUB", model.label=c("True Model"), model.lty=1)
{
  ### Arrange data.
  aa.names <- names(reu13.df.obs)
  #phi.bin <- phi.bin * phi.scale
  phi.bin.lim <- range(phi.bin)#range(c(phi.bin, phiMat))
  
  lbound <- max(0, length(bMat)-n.use.samples)
  ubound <- length(bMat)
  b.mat <- do.call(cbind, bMat[lbound:ubound]) 
  Eb <- rowMeans(b.mat)
  Eb <- convert.bVec.to.b(Eb, aa.names)
  
  ### Compute.
  ret.phi.bin <- prop.bin.roc(reu13.df.obs, phi.bin)
  
  if(model=="nse"){
    if("delta_a12" %in% names(list(...))) delta_a12 <- list(...)$delta_a12
    if("a_2" %in% names(list(...))) a_2 <- list(...)$a_2
    prediction <- prop.model.nse(Eb, reu13.df.obs, phi.bin.lim, delta_a12=delta_a12, a_2=a_2)
  }
  else{  prediction <- prop.model.roc(Eb, phi.bin.lim) }
  
  ### Fix xlim at log10 scale. 
  lim.bin <- range(log10(ret.phi.bin[[1]]$center))
  lim.model <- range(log10(prediction[[1]]$center))
  xlim <- c(lim.bin[1] - (lim.bin[2] - lim.bin[1]) / 4,
            max(lim.bin[2], lim.model[2]))
  
  
  mat <- matrix(c(rep(1, 4), 2:21, rep(22, 4)),
                nrow = 7, ncol = 4, byrow = TRUE)
  mat <- cbind(rep(23, 7), mat, rep(24, 7))
  nf <- layout(mat, c(3, rep(8, 4), 2), c(3, 8, 8, 8, 8, 8, 3), respect = FALSE)
  ### Plot title.
  par(mar = c(0, 0, 0, 0))
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.6, main)
  text(0.5, 0.4, date(), cex = 0.6)
  
  ### Plot results.
  for(i.aa in 1:length(aa.names))
  {
    tmp.obs <- ret.phi.bin[[i.aa]]
    tmp.roc <- prediction[[i.aa]]
    
    plotbin(tmp.obs, tmp.roc, main = "", xlab = "", ylab = "",
            lty = model.lty, axes = FALSE, xlim = xlim)
    box()
    main.aa <- oneLetterAAtoThreeLetterAA(aa.names[i.aa])
    text(0, 1, main.aa, cex = 1.5)
    if(i.aa %in% c(1, 5, 9, 13, 17)){
      axis(2)
    }
    if(i.aa %in% 16:19){
      axis(1)
    }
    if(i.aa %in% 1:4){
      axis(3)
    }
    if(i.aa %in% c(4, 8, 12,16)){
      axis(4)
    }
    axis(1, tck = 0.02, labels = FALSE)
    axis(2, tck = 0.02, labels = FALSE)
    axis(3, tck = 0.02, labels = FALSE)
    axis(4, tck = 0.02, labels = FALSE)
  }
  
  ## adding a histogram of phi values to plot
  hist.values <- hist(log10(phi.bin), plot=FALSE, nclass=30)
  plot(hist.values, axes = FALSE, main="", xlab = "", ylab = "")
  box()
  axis(1)

  ### Add label.
#  plot(NULL, NULL, axes = FALSE, main = "", xlab = "", ylab = "",
#        xlim = c(0, 1), ylim = c(0, 1))
#  legend(0.1, 0.8, model.label, lty = model.lty, box.lty = 0)
  
  ### Plot xlab.
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.5, "Production Rate (log10)")
  
  ### Plot ylab.
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.5, "Propotion", srt = 90)
}


plotBMatrixPosterior <- function(bMat, names.aa, interval, param = c("logmu", "deltaeta", "deltat"), main="AA parameter posterior", nclass=100, center=F)
{
  bmat <- convert.bVec.to.b(bMat[[1]], names.aa)
  bmat <- convert.b.to.bVec(bmat)
  names.b <- names(bmat)
  #id.intercept <- grep("Intercept", names.b)
  id.intercept <- grep("log", names.b)
  id.slope <- 1:length(names.b)
  id.slope <- id.slope[-id.intercept]
  
  
  id.plot <- rep(0, length(names.b))
  if(param[1] == "logmu"){
    xlab <- expression(paste("log ( ", mu, " )"))
    id.plot[id.intercept] <- id.intercept
  } else if(param[1] == "deltat"){
    xlab <- expression(paste(Delta, "t"))
    id.plot[id.slope] <- id.slope
  } else if(param[1] == "deltaeta"){
    xlab <- expression(paste(Delta, eta))
    id.plot[id.slope] <- id.slope
  }

  nf <- layout(matrix(c(rep(1, 4), 2:21), nrow = 6, ncol = 4, byrow = TRUE),
               rep(1, 4), c(2, 8, 8, 8, 8, 8), respect = FALSE)  
  #   nf <- layout(matrix(c(rep(1, 5), 2:21), nrow = 5, ncol = 5, byrow = TRUE),
  #                rep(1, 5), c(2, 8, 8, 8, 8), respect = FALSE)
  
  ### Plot title.
  par(mar = c(0, 0, 0, 0))
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.6, main)
  text(0.5, 0.4, date(), cex = 0.6)
  par(mar = c(5.1, 4.1, 4.1, 2.1))
  
  
  ### Plot by aa.
  postMeans <- NULL
  totalncodons <- 1
  for(i.aa in names.aa){
    #id.tmp <- grepl(paste(i.aa,".",sep=""), names.b, fixed=T) & id.plot
    id.tmp <- grepl(paste(i.aa, i.aa, sep="."), names.b, fixed=T) & id.plot
    trace <- lapply(1:length(bMat), function(i){ bMat[[i]][id.tmp] })
    trace <- do.call("rbind", trace)
    if(length(trace) == 0) next
    ncodons <- sum(id.tmp)
    
    ## find x and y limits
    ymax <- vector(mode = "numeric", length = ncodons)
    for(i in 1:ncodons) {
      ymax[i] <- max(hist(trace[interval, i], plot=F, nclass=nclass)$counts)
    }
    if(center){
      if(ncodons > 1){means <- colMeans(trace[interval,])}else{means <- mean(trace[interval,])}
      trace <- trace - mean(means)
    }
    if(ncodons > 1){means <- colMeans(trace[interval,])}else{means <- mean(trace[interval,])}
    postMeans <- c(postMeans, means)
    
    xlim <- range(trace[interval, ])
    ylim <- c(0, max(ymax))
    
    # create empty plot
    main.aa <- oneLetterAAtoThreeLetterAA(i.aa)
    plot(NULL, NULL, xlim = xlim, ylim = ylim,
         xlab = xlab, ylab = "Frequency", main = main.aa)
    plot.order <- order(apply(trace, 2, sd), decreasing = TRUE)
       
    ## Fill plots
    for(i.codon in plot.order){
      hist(trace[interval, i.codon], add=T, nclass=nclass, col=.CF.PT$color[i.codon], lty=0)
    }
    stddev <- format(sd(trace[interval, ]), digits = 3)
    text(x=(xlim[2]+xlim[1])/2, y=ylim[2]-0.1*ylim[2], label=paste("sd =", stddev))
  }

  dens <- density(postMeans)
  xlim <- range(dens$x)
  ylim <- range(dens$y)
  plot(dens, xlim = xlim, ylim = ylim+c(0, 0.2*ylim[2]),
       xlab = xlab, ylab = "Density", main = "Posterior mean distribution")
  stddev <- format(sd(postMeans), digits = 3)
  text(x=(xlim[2]+xlim[1])/2, y=ylim[2]+0.1*ylim[2], label=paste("sd =", stddev))
}

plotTraces <- function(bMat, names.aa, param = c("logmu", "deltaeta", "deltat"), main="AA parameter trace")
{  
  
  bmat <- convert.bVec.to.b(bMat[[1]], names.aa)
  bmat <- convert.b.to.bVec(bmat)
  names.b <- names(bmat)
  id.intercept <- grep("log", names.b)
  id.slope <- 1:length(names.b)
  id.slope <- id.slope[-id.intercept]
  
  
  id.plot <- rep(0, length(names.b))
  if(param[1] == "logmu"){
    ylab <- expression(paste("log ( ", mu, " )"))
    id.plot[id.intercept] <- id.intercept
  } else if(param[1] == "deltat"){
    ylab <- expression(paste(Delta, "t"))
    id.plot[id.slope] <- id.slope
  } else if(param[1] == "deltaeta"){
    ylab <- expression(paste(Delta, eta))
    id.plot[id.slope] <- id.slope
  }
  
  x <- 1:length(bMat)
  xlim <- range(x)
  
  ### Trace plot.
  nf <- layout(matrix(c(rep(1, 4), 2:21), nrow = 6, ncol = 4, byrow = TRUE),
               rep(1, 4), c(2, 8, 8, 8, 8, 8), respect = FALSE)  
#   nf <- layout(matrix(c(rep(1, 5), 2:21), nrow = 5, ncol = 5, byrow = TRUE),
#                rep(1, 5), c(2, 8, 8, 8, 8), respect = FALSE)
  
  ### Plot title.
  par(mar = c(0, 0, 0, 0))
  plot(NULL, NULL, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE)
  text(0.5, 0.6, main)
  text(0.5, 0.4, date(), cex = 0.6)
  par(mar = c(5.1, 4.1, 4.1, 2.1))
  
  ### Plot by aa.
  for(i.aa in names.aa){
    id.tmp <- grepl(paste(i.aa, i.aa, sep="."), names.b, fixed=T) & id.plot
    trace <- lapply(1:length(bMat), function(i){ bMat[[i]][id.tmp] })
    trace <- do.call("rbind", trace)
    if(length(trace) == 0) next
    ylim <- range(trace, na.rm=T)
    
    main.aa <- oneLetterAAtoThreeLetterAA(i.aa)
    plot(NULL, NULL, xlim = xlim, ylim = ylim,
         xlab = "Samples", ylab = ylab, main = main.aa)
    plot.order <- order(apply(trace, 2, sd), decreasing = TRUE)
    for(i.codon in plot.order){
      lines(x = x, y = trace[, i.codon], col = .CF.PT$color[i.codon])
    } 
  }
}

oneLetterAAtoThreeLetterAA <- function(letter)
{
  letters <- list(A="Ala", R="Arg", N="Asn", D="Asp", C="Cys", Q="Gln", E="Glu", 
                  G="Gly", H="His", I="Ile", L="Leu", K="Lys", F="Phe", P="Pro", 
                  S=expression("Ser"[4]), Z=expression("Ser"[2]), T="Thr", Y="Tyr", V="Val", M="Met", W="Trp")
  return(letters[[letter]])
}
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # determine position index of rows
  
  caption_table_space <- 1 # optional whiteline => 1 ipv 2?
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + caption_table_space + 1 } # 
  
  #col_names_r <- data_start_r - 1 # colnames one above data # <-> currently included in data
  col_names_r <- data_start_r 
  
  data_end_r <- data_start_r + n_data_rows
  
  table_end_r <- data_end_r
  
  col_margin_r <- data_end_r + 1  

  if (add.col.margin == TRUE) { table_end_r + 1 } 
  
  # caption and comment are outside of table start-end dimensions?
  
  if ( add.comment == TRUE ) { 
    comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }

  
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  
  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_c <- 1 + ncol(tabular)
  if (add.row.margin == TRUE) { table_end_c + 1 } 

  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = col_names_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = col_names_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)

  # no col margin -> only bottom line
  if (add.col.margin == FALSE) {
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }else{
  # col margin -> mid lid en bottom line
    addStyle(wb, sheet = 1, table_mid_row_style, rows = table_end_r, cols = table_start_c:table_end_c, gridExpand = TRUE)
    addStyle(wb, sheet = 1, table_bottom_row_style, rows = table_end_r+1, cols = table_start_c:table_end_c, gridExpand = TRUE)
  }

#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # determine position index of rows
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + 2 } # optional whiteline => 1 ipv 2?
  
  data_end_r <- data_start_r + n_data_rows
  col_margin_r <- data_end_r + 1  

  if ( add.comment == TRUE ) { comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }
  
#   n_total_rows <- n_data_rows
#   if (add.caption = TRUE) { n_total_rows + 1 }
#   if (add.col.margin = TRUE) { n_total_rows + 1 }
#   if (add.comment = TRUE) { n_total_rows + 1 }
  
  # determine position index of cols
  
  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  table_end_r <- 1 + n_data_cols
  if (add.row.margin == TRUE) { table_end_r + 1 } 

  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # add horizontal line styling
  # ---------------------------
  
  table_top_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_bottom_row_style <- createStyle(border="Top", borderStyle = "medium", borderColour="#000000")
  table_mid_row_style <- createStyle(border="Top", borderStyle = "thin", borderColour="#000000")
  #rc_names_style <- createStyle(textDecoration="bold")
  
  # table top rule -> add to start_table_row
  addStyle(wb, sheet = 1, table_top_row_style, rows = table_start_r, cols = table_start_r:table_end_r, gridExpand = TRUE)
  addStyle(wb, sheet = 1, table_mid_row_style, rows = table_start_r+1, cols = table_start_r:table_end_r, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_mid_row_style, rows = 12, cols = 1:6, gridExpand = TRUE)
#   addStyle(wb, sheet = 1, table_bottom_row_style, rows = 13, cols = 1:6, gridExpand = TRUE)
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
#Topic Model script
#Much of this initial workflow is from Jockers Text Analysis for R 
#and Shawn Graham's Ferguson Grand Jury corpus topic model at https://github.com/shawngraham/ferguson
library(mallet)
library(wordcloud)
library(dplyr)
library(tm)
library(Hmisc)

# import the OCR'd ICC decisions from the text folder
# each decision is here its own text file
#decisions <- mallet.read.dir("text") 

#Better is to use load.r file to provide cleaner texts via get_real_words function, etc

mallet.instances <- mallet.import(decisions$id, decisions$text, "icc.txt", token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")

#' create topic trainer object
n.topics <- 100
topic.model <- MalletLDA(n.topics)

#' load documents
topic.model$loadDocuments(mallet.instances)

## Get the vocabulary, and some statistics about word frequencies.
## These may be useful in further curating the stopword list.
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
#Get additional words for stoplist
#stopwords<- arrange(word.freqs, words, term.freq)
#rank(stopwords)



## Optimize hyperparameters every 20 iterations,
## after 50 burn-in iterations.
topic.model$setAlphaOptimization(20, 50)

## Now train a model. Note that hyperparameter optimization is on, by default.
## We can specify the number of iterations. Here we'll use a large-ish round number.
topic.model$train(400)

## NEW: run through a few iterations where we pick the best topic for each token,
## rather than sampling from the posterior distribution.
topic.model$maximize(40)

#' Get the probability of topics in documents and the probability of words in topics.
#' By default, these functions return raw word counts. Here we want probabilities,
#' so we normalize, and add "smoothing" so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=T, normalized=T)
topic.words <- mallet.topic.words(topic.model, smoothed=T, normalized=T)  ##adap jockers wordcloud script to use this variable

#' from http://www.cs.princeton.edu/~mimno/R/clustertrees.R
#' transpose and normalize the doc topics
topic.docs <- t(doc.topics)
topic.docs <- topic.docs / rowSums(topic.docs)

#Get shorter versions of the topics
topics.labels <- rep("", n.topics)
for (topic in 1:n.topics) topics.labels[topic] <- paste(mallet.top.words(topic.model, topic.words[topic,], num.top.words=7)$words, collapse=" ")


#output some of the topic model raw data
write.csv(topic.docs, "out/icc-topic-docs.csv") 
write.csv(topics.labels, "out/icc-topic-labels.csv") 

# create data.frame with columns as ids and rows as topics
topic_docs <- data.frame(topic.docs)
plotdocs <- names(topic_docs) 
names(topic_docs) <- decisions$id

## cluster based on shared words
plot(hclust(dist(topic.words)), labels=topics.labels)

#' Calculate similarity matrix
#' Shows which documents are similar to each other
#' by their proportions of topics. Based on Matt Jockers' method

library(cluster)
topic_df_dist <- as.matrix(daisy(t(topic_docs), metric = "euclidean", stand = TRUE))
# Change row values to zero if less than row minimum plus row standard deviation
# keep only closely related documents and avoid a dense spagetti diagram
# that's difficult to interpret (hat-tip: http://stackoverflow.com/a/16047196/1036500)
topic_df_dist[ sweep(topic_df_dist, 1, (apply(topic_df_dist,1,min) + apply(topic_df_dist,1,sd) )) > 0 ] <- 0

#' Use kmeans to identify groups of similar authors

km <- kmeans(topic_df_dist, n.topics)
# get names for each cluster
allnames <- vector("list", length = n.topics)
for(i in 1:n.topics){
  allnames[[i]] <- names(km$cluster[km$cluster == i])
}

#Shawn Graham's topics as wordclouds with some of Jockers print to pdf code
pdf(file="icc-topics.pdf")
for(i in 1:40){
  topic.top.words <- mallet.top.words(topic.model,
                                      topic.words[i,], 15)
  print(wordcloud(topic.top.words$words,
                  topic.top.words$weights,
                  c(4,.8), rot.per=0,
                  random.order=F))
  
}
dev.off()

#create some plots of topics across the range of decisions
library(ggplot2)
library(tidyr)
pdf(file="icc-topics-across-docs.pdf")
n.decisions <- length(raw)
cols <- 1:n.decisions
doc_topics <- data.frame(doc.topics, row.names = decisions$id, stringsAsFactors = FALSE)
doc_topics$docs <- cols

topic.cols <- names(doc_topics)

for(i in 1:100){
print(ggplot(doc_topics) + geom_smooth(aes_string(x="docs", y=(topic.cols[i]))))

}  
dev.off()

ggplot(doc_topics, aes(x=docs, y=X30)) + geom_smooth(span = 20)
#Topic Model script
#Much of this initial workflow is from Jockers Text Analysis for R 
#and Shawn Graham's Ferguson Grand Jury corpus topic model at https://github.com/shawngraham/ferguson
library(mallet)
library(wordcloud)
library(dplyr)
library(tm)
library(Hmisc)

# import the OCR'd ICC decisions from the text folder
# each decision is here its own text file
#decisions <- mallet.read.dir("text") 

#Better is to use load.r file to provide cleaner texts via get_real_words function, etc

mallet.instances <- mallet.import(decisions$id, decisions$text, "icc.txt", token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")

#' create topic trainer object
n.topics <- 100
topic.model <- MalletLDA(n.topics)

#' load documents
topic.model$loadDocuments(mallet.instances)

## Get the vocabulary, and some statistics about word frequencies.
## These may be useful in further curating the stopword list.
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
#Get additional words for stoplist
#stopwords<- arrange(word.freqs, words, term.freq)
#rank(stopwords)



## Optimize hyperparameters every 20 iterations,
## after 50 burn-in iterations.
topic.model$setAlphaOptimization(20, 50)

## Now train a model. Note that hyperparameter optimization is on, by default.
## We can specify the number of iterations. Here we'll use a large-ish round number.
topic.model$train(400)

## NEW: run through a few iterations where we pick the best topic for each token,
## rather than sampling from the posterior distribution.
topic.model$maximize(40)

#' Get the probability of topics in documents and the probability of words in topics.
#' By default, these functions return raw word counts. Here we want probabilities,
#' so we normalize, and add "smoothing" so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=T, normalized=T)
topic.words <- mallet.topic.words(topic.model, smoothed=T, normalized=T)  ##adap jockers wordcloud script to use this variable

#' from http://www.cs.princeton.edu/~mimno/R/clustertrees.R
#' transpose and normalize the doc topics
topic.docs <- t(doc.topics)
topic.docs <- topic.docs / rowSums(topic.docs)

#Get shorter versions of the topics
topics.labels <- rep("", n.topics)
for (topic in 1:n.topics) topics.labels[topic] <- paste(mallet.top.words(topic.model, topic.words[topic,], num.top.words=7)$words, collapse=" ")


#output some of the topic model raw data
write.csv(topic.docs, "out/icc-topic-docs.csv") 
write.csv(topics.labels, "out/icc-topic-labels.csv") 

# create data.frame with columns as ids and rows as topics
topic_docs <- data.frame(topic.docs)
plotdocs <- names(topic_docs) 
names(topic_docs) <- decisions$id

## cluster based on shared words
plot(hclust(dist(topic.words)), labels=topics.labels)

#' Calculate similarity matrix
#' Shows which documents are similar to each other
#' by their proportions of topics. Based on Matt Jockers' method

library(cluster)
topic_df_dist <- as.matrix(daisy(t(topic_docs), metric = "euclidean", stand = TRUE))
# Change row values to zero if less than row minimum plus row standard deviation
# keep only closely related documents and avoid a dense spagetti diagram
# that's difficult to interpret (hat-tip: http://stackoverflow.com/a/16047196/1036500)
topic_df_dist[ sweep(topic_df_dist, 1, (apply(topic_df_dist,1,min) + apply(topic_df_dist,1,sd) )) > 0 ] <- 0

#' Use kmeans to identify groups of similar authors

km <- kmeans(topic_df_dist, n.topics)
# get names for each cluster
allnames <- vector("list", length = n.topics)
for(i in 1:n.topics){
  allnames[[i]] <- names(km$cluster[km$cluster == i])
}

#Shawn Graham's topics as wordclouds with some of Jockers print to pdf code
pdf(file="icc-topics.pdf")
for(i in 1:40){
  topic.top.words <- mallet.top.words(topic.model,
                                      topic.words[i,], 15)
  print(wordcloud(topic.top.words$words,
                  topic.top.words$weights,
                  c(4,.8), rot.per=0,
                  random.order=F))
  
}
dev.off()

#create some plots of topics across the range of decisions
library(ggplot2)
library(tidyr)
pdf(file="icc-topics-across-docs.pdf")
cols <- 1:2502
doc_topics <- data.frame(doc.topics, row.names = decisions$id, stringsAsFactors = FALSE)
doc_topics$docs <- cols

topic.cols <- names(doc_topics)

for(i in 1:100){
print(ggplot(doc_topics) + geom_smooth(aes_string(x="docs", y=(topic.cols[i]))))

}  
dev.off()

ggplot(doc_topics, aes(x=docs, y=X30)) + geom_smooth(span = 20)
library(dplyr)
library(tidyr)
library(ggplot2)

gap_dat <- read.delim("06_gap-merged-with-continent.tsv")
gap_dat %>% str
# 'data.frame':  3312 obs. of  6 variables:
# $ country  : Factor w/ 187 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
# $ continent: Factor w/ 6 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...

## During data exploration, I learned that most countries have data every five
## years, e.g. 1952, 1957, 1962, and so on. Let's just make that official.
gap_dat <- gap_dat %>%
  filter(year %% 5 == 2)
gap_dat %>% str # 'data.frame':	2012 obs. of  6 variables:

## number of distinct values for year
(n_years <- n_distinct(gap_dat$year)) # 12

## Does every country contribute data for all years?
country_freq <- gap_dat %>%
  group_by(country) %>%
  tally

ggplot(country_freq, aes(x = n)) + geom_bar(binwidth = 1)
country_freq$n %>% table

## Most countries do contribute data for 12 years
## Who contributes less?
country_freq %>%
  filter(n < 12) %>%
  arrange(n)

## The only thing I see here that I want to fix is to rescue China, which has
## data for 11 of 12 years. Otherwise, I will let these countries go.
keepers <- c(with(country_freq, as.character(country[n == 12])),
             "China") %>% sort
keepers %>% length # 142 countries

## filter gap_dat
gap_dat <- gap_dat %>%
  filter(country %in% keepers) %>%
  droplevels %>%
  arrange(country, year)
gap_dat %>% str
# 'data.frame':  1703 obs. of  6 variables:
# $ country  : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
# $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...

## BEGIN: Fill in missing data for China

## which year is the problem?
(china <- gap_dat %>%
   filter(country == "China"))      # 1952 is missing

## what does the data look like?
china_tidy <- china %>%
  gather(key = "variable", value = "value",
         pop, lifeExp, gdpPercap)
ggplot(china_tidy, aes(x = year, y = value)) +
  facet_wrap(~ variable, scales="free_y") +
  geom_point() + geom_line() +
  scale_x_continuous(breaks = seq(1950, 2011, 15))

## extremely low, low tech imputation for 1952
china_gdp_fit <- lm(gdpPercap ~ year, gap_dat,
                    subset = country == 'China' & year <= 1982)
summary(china_gdp_fit)
(china_gdp_1952 <- predict(china_gdp_fit, data.frame(year = 1952)))
## 400.4486

china_pop_fit <- lm(pop ~ year, gap_dat, subset = country == 'China')
summary(china_pop_fit)
(china_pop_1952 <- predict(china_pop_fit, data.frame(year = 1952)))
## 556263528

china_lifeExp_1952 <- 44 # fiction, but no simple linear fit seems appropriate

gap_dat <- rbind(gap_dat,
                 data.frame(country = 'China', year = 1952,
                            pop = china_pop_1952, continent = 'Asia',
                            lifeExp = china_lifeExp_1952,
                            gdpPercap = china_gdp_1952))
gap_dat <- gap_dat %>%
  arrange(country, year)
gap_dat %>%
  filter(country == "China")
str(gap_dat)
# 'data.frame':  1704 obs. of  6 variables:
# $ country  : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : num  1952 1957 1962 1967 1972 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
# $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...

## revisit the data
china_tidy <- gap_dat %>%
  filter(country == "China") %>%
  gather(key = "variable", value = "value",
         pop, lifeExp, gdpPercap)
ggplot(china_tidy, aes(x = year, y = value)) +
  facet_wrap(~ variable, scales="free_y") +
  geom_point() + geom_line() +
  scale_x_continuous(breaks = seq(1950, 2011, 15))

## END: Fill in missing data for China

write.table(gap_dat,
            "07_gap-every-five-years.tsv",
            quote = FALSE, sep = "\t", row.names = FALSE)

gapminder <- gap_dat

## finally ready to save data for the package
save(gapminder, file = "gapminder.rdata")
library(plyr)  ## revalue()
library(dplyr)
library(ggplot2)

## bring in lightly cleaned datasets extracted from excel spreadsheets

pop_dat <- read.delim("01_pop.tsv")
pop_dat %>% str
# 'data.frame':  14105 obs. of  3 variables:
# $ country: Factor w/ 253 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year   : int  1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 ...
# $ pop    : num  8150368 8284473 8425333 8573217 8728408 ...
## 2014: only difference with 2010 is pop is numeric now, was integer
pop_dat %>% head
pop_dat %>% tail

le_dat <- read.delim("02_lifeExp.tsv")
le_dat %>% str
# 'data.frame':  3786 obs. of  4 variables:
# $ country  : Factor w/ 198 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ continent: Factor w/ 7 levels "","Africa","Americas",..: 4 4 4 4 4 4 4 4 4 4 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
## 2014: only difference with 2010 is order of the variables
le_dat %>% head
le_dat %>% tail           

gdp_dat <- read.delim("03_gdpPercap.tsv")
gdp_dat %>% str
# 'data.frame':  10911 obs. of  3 variables:
# $ country  : Factor w/ 229 levels "Afghanistan",..: 1 2 3 4 6 9 10 12 13 14 ...
# $ gdpPercap: num  757 1532 2429 4465 3363 ...
# $ year     : int  1950 1950 1950 1950 1950 1950 1950 1950 1950 1950 ...
## 2014: only difference with 2010 is order of the variables
## 'data.frame':	10911 obs. of  3 variables:
gdp_dat %>% head
le_dat %>% tail

## studying the overlap between countries in the different datasets
country_levels <- function(df) levels(df$country)
union_country <- country_levels(pop_dat) %>%
  union(country_levels(le_dat)) %>%
  union(country_levels(gdp_dat)) %>%
  sort
union_country %>% length # 271 (in 2010 and 2014)
union_country
## problems I see by eye
# Bahamas  Bahamas, The
# Central African Rep.	Central African Republic
# Congo, Dem. Rep.	Congo, Rep.
# Cook Is	    Cook Islands
# Czech Rep.  Czech Republic	Czechoslovakia
# Dominican Rep.	  Dominican Republic
# East Germany	  Germany   West Germany
# Egypt		  Egypt, Arab Rep.
# Eritrea		  Eritrea and Ethiopia	Ethiopia
# Falkland Is (Malvinas)	  Falkland Islands (Malvinas)
# Gambia	 Gambia, The
# Iran	 Iran, Islamic Rep.
# Korea, Dem. Rep.       Korea, Rep.	Korea, United
# Kyrgyz Republic	       Kyrgyzstan
# Lao PDR		       Laos
# Russia		       Russian Federation	USSR
# Serbia		       Serbia and Montenegro	Serbia excluding Kosovo
# Saint Kitts and Nevis  St. Kitts and Nevis
# Saint Lucia St. Lucia
# Saint Vincent and the Grenadines	St. Vincent and the Grenadines
# Syria Syrian Arab Republic
# Venezuela    Venezuela, RB
# Yemen Arab Republic (Former)	Yemen Democratic (Former)	Yemen, Rep.
# RECORDED THAT IN country-pain.txt!
c_dat <- data_frame(country = union_country,
                    pop = country %in% levels(pop_dat$country),
                    le = country %in% levels(le_dat$country),
                    gdp = country %in% levels(gdp_dat$country),
                    total = pop + le + gdp)
c_dat$total %>% table
##  1   2   3 
## 40  53 178

## Can I just ignore countries that appear in 1 or 2 datasets?
c_dat %>%
  filter(total < 3)
## No, I cannot.

## these are the ad hoc fixes I decided to make in 2010
## (country-pain.txt contains a more comprehensive collection of problems)
country_subs <- c("Bahamas, The" = "Bahamas",
                  "Central African Rep." = "Central African Republic",
                  "Cook Is" = "Cook Islands",
                  "Czech Rep." = "Czech Republic",
                  "Dominican Rep." = "Dominican Republic",
                  "Egypt, Arab Rep." = "Egypt",
                  "Gambia, The" = "Gambia",
                  "Iran, Islamic Rep." = "Iran",
                  "Russian Federation" = "Russia",
                  "Syrian Arab Republic" = "Syria",
                  "Venezuela, RB" = "Venezuela")
revalue_country <- function(x) revalue(x, country_subs)
pop_dat <- pop_dat %>%
  mutate(country = revalue_country(country))
le_dat <- le_dat %>%
  mutate(country = revalue_country(country))
gdp_dat <- gdp_dat %>%
  mutate(country = revalue_country(country))

## studying the overlap between countries in the different datasets
union_country <- country_levels(pop_dat) %>%
  union(country_levels(le_dat)) %>%
  union(country_levels(gdp_dat)) %>%
  sort
union_country %>% length # 260 (in 2010 and 2014), down from 271
c_dat <- data_frame(country = union_country,
                    pop = country %in% levels(pop_dat$country),
                    le = country %in% levels(le_dat$country),
                    gdp = country %in% levels(gdp_dat$country),
                    total = pop + le + gdp)
c_dat$total %>% table
## BEFORE revalues    AFTER revalues    
##  1   2   3         1   2   3 
## 40  53 178        28  44 188 

## Can I just ignore countries that appear in 1 or 2 datasets?
c_dat %>%
  filter(total < 3)
## Other than USSR, yes I will ignore countries that appear in 1 or 2 datasets.

pop_russia <- pop_dat %>%
  filter(country %in% c("Russia","USSR"))
(ggplot(pop_russia, aes(x = year, y = pop, color = country)) +
   geom_line())
xyplot(pop ~ year, type = "l", 
            groups = country[drop = TRUE], auto.key = TRUE))
## huh?
## pop data present for USSR *and* Russia, 1950 - 2008
## USSR pop >> Russia pop, USSR presumably includes Russia??

le_dat %>%
  filter(country %in% c("Russia","USSR"))
gdp_dat %>%
  filter(country %in% c("Russia","USSR"))
## lifeExp and gdpPercap only have data for Russia
## decision: keep Russia, discard USSR

## decision: keep countries found in all 3 datasets

## merge all three datasets!  then enforce countries to keep
gap_dat <- pop_dat %>%
  inner_join(gdp_dat, by = c("country", "year")) %>%
  inner_join(le_dat, by = c("country", "year")) %>%
  droplevels %>%
  arrange(country, year)
gap_dat %>% str
# 'data.frame':  3312 obs. of  6 variables:
# $ country  : Factor w/ 187 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ year     : int  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
# $ pop      : num  8425333 9240934 10267083 11537966 13079460 ...
# $ gdpPercap: num  779 821 853 836 740 ...
# $ continent: Factor w/ 7 levels "","Africa","Americas",..: 4 4 4 4 4 4 4 4 4 4 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...
## 2014: agrees with merged result in 2010, except for
##   * variable order
##   * pop is numeric now, was integer then
##   * at this point in 2010 cleaning, I had an unused level for the country
##     factor (Tokelau), which has no downstream effects

my_vars <- c('country', 'continent', 'year',
             'lifeExp', 'pop', 'gdpPercap')
gap_dat <- gap_dat[my_vars]

write.table(gap_dat,
            "04_gap-merged.tsv",
            quote = FALSE, sep = "\t", row.names = FALSE)
library(gdata)     # read.xls()
library(dplyr)
library(ggplot2)
library(stringr)   # str_detect()

## extract the life expectancy data

## this is the Excel file downloaded 2009-04-21 from gapminder.org
## Yes, it was painful coming up with all the argument values necessary to
## successfully import this data. See comments at end of file.
le_xls <-
  read.xls("life-expectancy-reference-spreadsheet-20090204-xls-format.xls",
           sheet = "Data and metadata",
           verbose = TRUE, quote = "", method = "tab",
           fileEncoding =  "ISO-8859-1",
           colClasses = c(rep("character", 4), rep("NULL", 5)))
## many instances of this warning:
#Wide character in print at /Users/jenny/resources/R/libraryCRAN/gdata/perl/xls2tab.pl line 270.
le_xls %>% str
# 'data.frame':  52419 obs. of  4 variables:
# $ X.Continent.average.used..see.documentation..                                                    : chr  "\"Asia\"" "\"Asia\"" "\"Asia\"" "\"Asia\"" ...
# $ X.Country.                                                                                       : chr  "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" ...
# $ X.Year.                                                                                          : chr  "\"1800\"" "\"1801\"" "\"1802\"" "\"1803\"" ...
# $ X.Life.expectancy.at.birth..including.Gapminder.model...not.to.be.used.for.statistical.analysis..: chr  "" "" "" "" ...

## rename vars
le_raw <- le_xls %>%
  select(country = contains("country"), continent = contains("continent"),
         year_raw = contains("year"), lifeExp_raw = contains("life.expectancy"))
le_raw %>% str
# 'data.frame':  52419 obs. of  4 variables:
# $ country    : chr  "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" "\"Abkhazia\"" ...
# $ continent  : chr  "\"Asia\"" "\"Asia\"" "\"Asia\"" "\"Asia\"" ...
# $ year_raw   : chr  "\"1800\"" "\"1801\"" "\"1802\"" "\"1803\"" ...
# $ lifeExp_raw: chr  "" "" "" "" ...

## 2014: 52419 obs. of  4 variables:
## 2010 cleaning code comment: # 52416 obs. of  9 variables: <-- huh?
## Note: I did not use gdata::read.xls() in 2010; rather, I exported a text file
## from Excel 'by hand'.
le_raw %>% head
le_raw %>% tail

## get rid of the escaped double quotes
remove_quotes <- function(x) gsub("\"", "", x)
le_raw <- le_raw %>%
  mutate_each(funs(remove_quotes))
le_raw %>% str
# 'data.frame':  52419 obs. of  4 variables:
# $ country    : chr  "Abkhazia" "Abkhazia" "Abkhazia" "Abkhazia" ...
# $ continent  : chr  "Asia" "Asia" "Asia" "Asia" ...
# $ year_raw   : chr  "1800" "1801" "1802" "1803" ...
# $ lifeExp_raw: chr  "" "" "" "" ...

## let's fix year enough to filter on it
n_distinct(le_raw$year_raw) #210
unique(le_raw$year_raw)
## eye-ball-o-metric inspection ...

## must investigate obviously invalid values for year
(needs_a_look <- which(le_raw$year_raw %in% c("", "5")))
le_raw[(min(needs_a_look) - 4):(max(needs_a_look) + 4), ]
## early 1800s, Pakistan
## this will never survive my year filter so just make this go away
## BTW nothing visible in Excel; I can see gaps in row numbers but 'unhide' does
## nothing ... Google tell me to "unset filters" from data menu, which does
## indeed reveal the hidden rows
le_raw$year_raw[needs_a_look] <- NA_character_

le_raw$year_raw %>% n_distinct #209
le_raw$year_raw %>% unique
## nothing obviously crazy remains

## convert year to integer
le_raw <- le_raw %>%
  mutate(year = year_raw %>% as.integer)
le_raw$year %>% n_distinct #209
le_raw$year %>% unique
all.equal(sort(unique(le_raw$year[!is.na(le_raw$year)])), 1800:2007)
## Integers between 1800 and 2007. Yay.

## drop year_raw, in favor of year
le_raw <- le_raw %>%
  mutate(year_raw = NULL)

le_raw$year %>% summary
#  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
#  1800    1852    1904    1904    1955    2007       3
## AHA! In 2010, this did not includee 3 NA's.
## 52419 - 3 = 52416
## Mystery of the rows solved.

## for which years do we have data?
year_freq <- le_raw %>%
  group_by(year) %>%
  tally
table(year_freq$n)
# 3 252
# 1 208
## this solves nothing, because even when year is present, life expectancy often
## is not
## very different structure from population data :(

## change of plan: let's fix lifeExp enough to filter on it
le_raw$lifeExp_raw %>% head(100)
sum(le_raw$lifeExp_raw == "") # 46510
# 'data.frame':  5909 obs. of  5 variables:
# $ country  : chr  "\"Afghanistan\"" "\"Afghanistan\"" "\"Afghanistan\"" "\"Afghanistan\"" ...
# $ continent: chr  "\"Asia\"" "\"Asia\"" "\"Asia\"" "\"Asia\"" ...
# $ year_raw : chr  "\"1800\"" "\"1952\"" "\"1957\"" "\"1962\"" ...
# $ lifeExp  : chr  "\"28.801\"" "\"28.801\"" "\"30.332\"" "\"31.997\"" ...
# $ year     : num  1800 1952 1957 1962 1967 ...

le_raw <- le_raw %>%
  filter(lifeExp_raw != "")
str(le_raw)
# 'data.frame':  5909 obs. of  4 variables:
# $ country    : chr  "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
# $ continent  : chr  "Asia" "Asia" "Asia" "Asia" ...
# $ lifeExp_raw: chr  "28.801" "28.801" "30.332" "31.997" ...
# $ year       : num  1800 1952 1957 1962 1967 ...

## while lifeExp_raw is still character, check to see if it contains only digits
## and the decimal sign
le_seems_ok <- le_raw$lifeExp_raw %>% str_detect("[0-9\\.]")
le_seems_ok %>% table
# TRUE
# 5909
## I am pleasantly shocked

## convert lifeExp to numeric
le_raw <- le_raw %>%
  mutate(lifeExp = lifeExp_raw %>% as.numeric)

le_raw$lifeExp %>% summary
#  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
# 11.60   45.21   61.17   58.02   70.90   82.67

## drop lifeExp_raw, in favor of lifeExp
le_raw <- le_raw %>%
  mutate(lifeExp_raw = NULL)

## is continent ok as is?
n_distinct(le_raw$continent) # 7
unique(le_raw$continent)
# [1] "Asia"     "Europe"   "Africa"   "Americas" ""         "FSU"      "Oceania"

## let's look further into empty continent and FSU
(empty_continent <- le_raw %>%
   filter(continent == "") %>%
   select(country) %>%
   unique)
str(empty_continent) ## 30 countries affected, eg Canada, Haiti
## wait to fix these after merging pop + lifeExp + gdpPercap

(fsu_continent <- le_raw %>%
   filter(continent == "FSU") %>%
   select(country) %>%
   unique)
#                country
# 1              Belarus
# 53          Kazakhstan
# 73              Latvia
# 128          Lithuania
# 181 Russian Federation
# 262            Ukraine
## handle this after merging pop + lifeExp + gdpPercap

## is country ok as is?
n_distinct(le_raw$country) # 198
unique(le_raw$country)
## no obvious problems

## return to year
n_distinct(le_raw$year) #208
unique(le_raw$year)
(p <- ggplot(le_raw, aes(x = year)) + geom_bar(binwidth = 1)) # 1950 -->
p + xlim(c(1945, 2010)) # spikes every five years
p + xlim(c(1950, 1960)) # 1952, 1957, ...
p + xlim(c(2000, 2010)) # ..., 2002, 2007

## keep data from 1950 to 2007
year_min <- 1950
year_max <- 2007
le_raw <- le_raw %>%
  filter(year >= year_min & year <= year_max)
le_raw %>% str
# 'data.frame':  3786 obs. of  4 variables:
# $ country  : chr  "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
# $ continent: chr  "Asia" "Asia" "Asia" "Asia" ...
# $ year     : num  1952 1957 1962 1967 1972 ...
# $ lifeExp  : num  28.8 30.3 32 34 36.1 ...

## save for now
write.table(le_raw,
            "02_lifeExp.tsv",
            quote = FALSE, sep = "\t", row.names = FALSE)


## EVERYTHING BELOW HERE IS COMMENTED OUT!
## NOTES ON HOW I WAS ABLE TO WRITE THE ABOVE CODE

## saving this saga for possible later demo and write-up

## initially tried a much simpler read.xls() call
# le_xls <-
#   read.xls("xls/life-expectancy-reference-spreadsheet-20090204-xls-format.xls",
#            verbose = TRUE, sheet = "Data and metadata",
#            stringsAsFactors = FALSE, fileEncoding =  "macintosh")

## technically it was successful but got these warnings:
## many instances of this:
# Wide character in print at /Users/jenny/resources/R/libraryCRAN/gdata/perl/xls2csv.pl line 270.
## and then also this:
# Warning message:
#   In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
#             EOF within quoted string

## the default intermediate file for read.xls() is comma delimited
## in the docs:
## "Caution: In the conversion to csv, strings will be quoted"

## ultimately, I followed more advice in the docs:

# If you have quotes in your data which confuse the process you may wish to use
# read.xls(..., quote = ''). This will cause the quotes to be regarded as data
# and you will have to then handle the quotes yourself after reading the file in

# http://stackoverflow.com/questions/17414776/read-csv-warning-eof-within-quoted-string-prevents-complete-reading-of-file

## initial read.xls() import created quotes within quotes, deriving from the
## extra fields I'm not using

## this created some very strange entries for cells and screwed around with the
## number of rows

# le_xls %>% str
## 41865 obs. of  9 variables:

## these next commands almost hung R/RStudio but I did eventually get the
## command prompt back.
# levels(le_raw$year)
# nlevels(le_raw$year) # 295
# summary(le_raw$year)

## I wrote that object to file for inspection
# write.table(le_raw,
#             "01_le.tsv",
#             sep = "\t", row.names = FALSE)

## and determined that I needed to figure out this file's encoding and deal with
## the embedded quotes problem --> that meant I should switch to tab-delimited
## as the intermediate file format

## so I tried making the intermediate file explicitly and then importing it with
## read.table()

## note: at this point, I was still confused about the encoding because
## TextWrangler had indicated the encoding was Western (Mac OS Roman)

# con <-
#   xls2tab("xls/life-expectancy-reference-spreadsheet-20090204-xls-format.xls",
#           verbose = TRUE, sheet = "Data and metadata",
#           fileEncoding =  "MACROMAN")

## usual warnings about "wide character" and "EOF within quoted string"

# (temp_file <- summary(con)$description)

## here is where I decide that I want to only read the first four
## columns/variables, since it's the other columns/variables causing all the
## problems

# http://stackoverflow.com/questions/2193742/ways-to-read-only-select-columns-from-a-file-into-r-a-happy-medium-between-re
# http://stackoverflow.com/questions/5788117/only-read-limited-number-of-columns-in-r

## trying and failing to learn the number columns programmatically
# max(count.fields(temp_file, sep = "\t"))
## NA ... never seems to work

## experimenting with only reading (or retaining?) the first 4 columns

## around now is where I also figure out the correct encoding: realized a
## curly equals sign or \305 was appearing instead of capital A with a circle on
## top, which I then googled
## the country affected: Åland
## http://www.ic.unicamp.br/~stolfi/EXPORT/www/ISO-8859-1-Encoding.html
## look into how to determine encoding more automatically?
# foo <- read.delim(temp_file, quote = "",
#                   fileEncoding =  "ISO-8859-1",
#                   colClasses = c(rep("character", 4), rep("NULL", 5)))

## lines where you can see evidence of encoding problems when using read.xls()
## ineptly:

## L12068
# " 2002; Andreev"  " and 1984; Johansen"	" 2002)"	" Denmark‚Äôs health transition began in the 1770s when"
# L37785 and beyond
# " Vladimir and Ilie Hristache. 1986. Demografia teritoriala a Rom√¢niei. Bucharest.,
# Europe,Romania,1933,,,,,,
# Europe,Romania,1934,,,,,,
# ...
# Europe,Romania,2007,72.476,UN:WPP,,medium variant projection,,
# FSU,Russian Federation,1800,31.9,Riley file extrapolation,,,,5

## lessons learned going in these circles eventually led to the functional
## read.xls() call used in the live code here
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # determine position index of rows
  
  n_data_rows <- nrow(tabular)
  
  table_start_r <- coords[1] # consider coords (r,c)
  caption_r <- table_start_r
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  
  # if caption, start the table two rows lower
  if (add.caption) { data_start_r <- data_start_r + 2 } # optional whiteline => 1 ipv 2?
  
  data_end_r <- data_start_r + n_data_rows
  col_margin_r <- data_end_r + 1  

  if ( add.comment == TRUE ) { comment_r <- data_end_r + 1 }
  if ( add.col.margin == TRUE ) { comment_r <- col_margin_r + 1 }
  
  # determine position index of cols
  
  n_data_cols <- ncol(tabular)
  table_start_c <- coords[2]
  data_start_c <- table_start_c

  # TODO: ook mogelijk maken dat er geen rownames zijn?
  row_margin_c <- 1 + ncol(tabular) + 1
  
  
  # TODO: ook mogelijk maken dat er geen colnames zijn?
  col_margin_c <- data_start_c + 1

  #n_total_cols <- 
  #n_total_rows <- 

  
  
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = caption_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # dimensions
  # ----------
  
  #   1 caption row       x   [spanning caption colums]
  #   2 white row         x   1 rownames col  + 3 ncol cols + 1 row margin col
  #   3 colnames row      x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   4 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   5 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   6 data row          x   1 rowname col   + 3 ncol rows + 1 row margin col
  #   7 col margin row    x   1 whitespace    + 3 ncol rows + 1 row margin col
  #   8 comment row       x   [spanning comment columns]
  
  # consider coords (r,c)
  table_start_r <- coords[1]
  table_start_c <- coords[2]
  
  # data includes rownames, colnames TODO: change to make option?
  data_start_r <- table_start_r
  data_start_c <- table_start_c
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 
  
  # if caption, start the table one row lower
  if (add.caption) { data_start_r <- data_start_r + 2 } # optional whiteline => 1 ipv 2?
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = data_start_c, startRow = data_start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "none")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is the most top one, i.e. table_start_r
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = table_start_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    caption_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:caption_merge_width, 
               rows = table_start_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen rownames zijn?
    row_margin_c <- 1 + ncol(tabular) + 1
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = data_start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen colnames zijn?
    col_margin_c <- data_start_c + 1
    col_margin_r <- data_start_r + nrow(tabular) + 1
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  if (add.comment) {
    comment.contents <- 'N = 1200 (NA = 100), chi^2 = 3, p 0.000. Gewogen steekproef ' # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen colnames zijn?
    comment_r <- data_start_r + n_data_rows + 1
    if (add.col.margin) { comment_r <- comment_r + 1 }
    
    writeData(
      wb = wb, sheet = sheet, startCol = table_start_c, startRow = comment_r,
      x = comment.contents, rowNames=FALSE, colNames=FALSE)  
    
    comment_merge_width <- ifelse(7 - table_start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = table_start_c:comment_merge_width, 
               rows = comment_r)
    
  } 
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args)
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        list(value = do.call(base::source, source_args)$value,
             preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param args list. Any additional arguments passed when calling \code{value()}.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
setClassUnion('listOrNULL', c('list', 'NULL'))

#' Representation of a director resource.
#'
#' @docType class
#' @name directorResource
#' @rdname directorResource
directorResource <- setRefClass('directorResource',
  fields = list(current = 'listOrNULL', cached = 'listOrNULL',
                modified = 'logical', resource_key = 'character',
                source_args = 'list', director = 'director',
                .dependencies = 'character', .compiled = 'logical',
                .value = 'ANY'),
  methods = list(
    initialize = function(current, cached, modified, resource_key,
                          source_args, director) {
      current      <<- current
      cached       <<- cached
      modified     <<- modified
      resource_key <<- resource_key
      source_args  <<- source_args
      director     <<- director
      .compiled    <<- FALSE
    },
    
    value = function(..., recompile. = FALSE) {
      if (isTRUE(recompile.)) recompile(...)
      else if (is_cached() && !any_dependencies_modified()) .value <<- cached$value
      else compile(...)
      .value
    },

    # Compile a resource using a resource handler.
    #
    # @param parse. logical. Whether or not to apply parsers. Note that
    #   it is impossible to not apply preprocessors, since it is
    #   the preprocessor's responsibility to source the file of the resource.
    # @param tracking logical. Whether or not to perform modification tracking
    #   by pushing accessed resources to the director's stack. The default is
    #   \code{TRUE}.
    compile = function(..., parse. = TRUE, tracking = TRUE) {
      if (isTRUE(.compiled)) return(TRUE) 

      if (!is.element('local', names(source_args)))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include ", dQuote('local'),
             " in the list of arguments to pass to base::source")
      else if (!is.environment(source_args$local))
        stop("To compile ", sQuote(source_args[[1]] %||% 'this resource'),
             " you must include an ", "environment in the ", dQuote('local'),
             " parameter to base::source.")

      # We will be tracking what dependencies (other resources) are loaded
      # during the compilation of this resource. We have a dependency nesting
      # level on the director object that counts how deep we are within 
      # resource compilation (i.e., if a resource needs another resource
      # which needs another resources, etc.).
      if (director$.dependency_nesting_level == 0) director$.stack$clear()
      director$.dependency_nesting_level <<- director$.dependency_nesting_level + 1L
      on.exit(director$.dependency_nesting_level <<- director$.dependency_nesting_level - 1L)
      local_nesting_level <- director$.dependency_nesting_level 
 
      # TODO: (RK) Better resource provision injection
      if (!base::exists('..director_inject', envir = parent.env(source_args$local), inherits = FALSE)) {
        injects <- new.env(parent = parent.env(source_args$local))
        injects$..director_inject <- TRUE
        injects$root <- function(x, ...) director$root()
        injects$resource <- function(x, ...) director$resource(x)$value(...)
        injects$resource_exists <- function(...) director$exists(...)
        injects$helper   <-
          function(...) director$resource(..., check.helpers = FALSE)$value(parse. = FALSE)
        parent.env(source_args$local) <<- injects
      }

      value <- evaluate(source_args)
      if (isTRUE(parse.)) .value <<- parse(value, source_args$local, list(...))
      else .value <<- value$value
      cache_value_if_necessary()

      # Cache dependencies.
      dependencies <- 
        Filter(function(dependency) dependency$level == local_nesting_level, 
               director$.stack$peek(TRUE))
      if (any(vapply(dependencies, function(d) d$resource$modified, logical(1))))
        modified <<- TRUE

      cached$dependencies <<- vapply(dependencies, getElement, character(1), name = 'key')
      cached$modified     <<- modified
      update_cache()

      while (!director$.stack$empty() && director$.stack$peek()$level == local_nesting_level)
        director$.stack$pop()

      .compiled <<- TRUE
    },
    recompile = function(...) { 
      .compiled <<- FALSE
      compile(...)
    },

    # Evaluate a resource's R file.
    # 
    # This is a straightforward call to \code{base::source}, although if a 
    # preprocessor was registered, this will be executed before the file is sourced.
    #
    # A preprocessor function has the same available locals as a parser,
    # although it also has an environment \code{preprocessor_output},
    # and the \code{source_args} that are meant to be passed to \code{base::source}.
    #
    # This is an environment in which the preprocessor
    # may place computations, which will be available in the parser via
    # the \code{preprocessor_output} provider. The return value of the
    # preprocessor will be the final resource vlaue (so a preprocessor must
    # call \code{base::source} manually).
    #
    # Preprocessors are useful for doing things like (1) parsing through a
    # resource's source code to extract documentation, and (2) injecting
    # information into the local environment prior to sourcing a resource.
    #
    # Note: If \code{base::source} is called in the preprocessor without
    # \code{local = source_args$local}, the parser will not be able to access
    # the \code{input} that was generated during sourcing.
    # 
    # TODO: (RK) Provide examples.
    #
    # @param source_args list. The parameters to pass to \code{base::source}
    #   when the file is evaluated.
    # @return a list with \code{value} and \code{preprocessor_output},
    #   the former the result of the preprocessor application, and the latter
    #   the environment that is made available to the parser later on.
    evaluate = function(source_args) {
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
        names(director$.preprocessors))

      if (is.null(route)) {
        list(value = do.call(base::source, source_args)$value,
             preprocessor_output = emptyenv())
      }
      else {
        fn <- director$.preprocessors[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource        <- resource_key
        environment(fn)$director        <- director
        environment(fn)$resource_body   <- current$body
        environment(fn)$modified        <- modified
        environment(fn)$resource_object <- .self
        environment(fn)$source_args     <- source_args
        environment(fn)$source  <-
          function() eval.parent(quote(do.call(base::source, source_args)$value))
        environment(fn)$preprocessor_output <-
          preprocessor_output <- new.env(parent = emptyenv())
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        list(value = fn(), preprocessor_output = preprocessor_output)
      }
    },

    # Parse a resource after it has been sourced.
    # 
    # @param value ANY. The return value of the resource file.
    # @param provides environment. The local environment it was sourced in.
    # @param the parsed object.
    parse = function(value, provides, args = list()) {
      # TODO: (RK) Resource parsers?
      route <- Find(function(x) substring(resource_key, 1, nchar(x)) == x,
                    names(director$.parsers))
      if (is.null(route)) value$value
      else {
        fn <- director$.parsers[[route]]
        env <- new.env(parent = environment(fn))
        environment(fn) <- env # TODO: (RK) Test this!
        environment(fn)$resource            <- resource_key
        environment(fn)$input               <- provides
        environment(fn)$output              <- value$value
        environment(fn)$preprocessor_output <- value$preprocessor_output
        environment(fn)$director            <- director
        environment(fn)$resource_body       <- current$body
        environment(fn)$modified            <- modified
        environment(fn)$resource_object     <- .self
        environment(fn)$args                <- args
        
        assign("%||%", function(x, y) if (is.null(x)) y else x, envir = environment(fn))
        fn()
      }
    },

    show = function() {
      cat("Resource", sQuote(resource_key), "under director: \n")
      director$show()
    },

    update_cache = function() {
      cache_key <- resource_cache_key(resource_key)
      director$.cache[[cache_key]]$dependencies <<- cached$dependencies
      director$.cache[[cache_key]]$modified     <<- cached$modified
    },

    dependencies = function() {
      get_dependencies <- function(key) {
        deps <- director$.cache[[resource_cache_key(key)]]$dependencies %||% character(0)
        as.character(c(deps, sapply(deps, get_dependencies), recursive = TRUE))
      }
      unique(c(recursive = TRUE, as.character(cached$dependencies),
        sapply(cached$dependencies, get_dependencies)))
    },

    # TODO: (RK) Test this method!
    dependencies_modified = function() {
      dependency_resources <- lapply(dependencies(), director$resource, soft = TRUE)
      # TODO: (RK) Do we need to worry about helpers v.s. non-helpers?

      those_modified <- vapply(dependency_resources,
        function(r) r$any_dependencies_modified(), logical(1))

      vapply(dependency_resources[those_modified],
             function(r) r$resource_key, character(1))
    },

    # TODO: (RK) Test this method!
    any_dependencies_modified = function() {
      modified || length(dependencies_modified()) > 0
    },

    cache_value_if_necessary = function() {
      if (!caching_enabled()) return()
      if (is(.value, 'uninitializedField')) {
        stop("directorResource$cache_value_if_necessary: Cannot cache resource ",
             "value because it has not been parsed.")
      }
      # We need to use `[` and not `$` or NULLs won't be cached.
      cached['value'] <<- list(value = .value)
      director$.cache[[resource_cache_key(resource_key)]]['value'] <<- list(value = .value)
    },

    caching_enabled = function() {
      any_is_substring_of(resource_key, director$.cached_resources)
    },
    is_cached = function() { is.element('value', names(cached)) }

  )
)


#' @docType function
#' @name director
#' @export
NULL
#' This R script will process all R mardown files (those with in_ext file extention,
#' .rmd by default) in the current working directory. Files with a status of
#' 'processed' will be converted to markdown (with out_ext file extention, '.markdown'
#' by default). It will change the published parameter to 'true' and change the
#' status parameter to 'publish'.
#' 
#' @param dir the directory to process R Markdown files.
#' @param images.dir the base directory where images will be generated.
#' @param images.url
#' @param out_ext the file extention to use for processed files.
#' @param in_ext the file extention of input files to process.
#' @param recursive should rmd files in subdirectories be processed.
#' @return nothing.
#' @author Jason Bryer <jason@bryer.org> edited by Andy South
rmd2md <- function( path_site = getwd(),
                              dir_rmd = "_rmd",
                              dir_md = "_posts",                              
                              #dir_images = "figures",
                              url_images = "figures/",
                              out_ext='.md', 
                              in_ext='.rmd', 
                              recursive=FALSE) {
  
  require(knitr, quietly=TRUE, warn.conflicts=FALSE)

  #files <- list.files(path=dir, pattern=in_ext, ignore.case=TRUE, recursive=recursive)
  #andy change to avoid path problems when running without sh on windows 
  #files <- list.files(path=pathSite, full.names=TRUE, pattern=in_ext, ignore.case=TRUE, recursive=recursive)
  files <- list.files(path=file.path(path_site,dir_rmd), pattern=in_ext, ignore.case=TRUE, recursive=recursive)
  
  for(f in files) {
    message(paste("Processing ", f, sep=''))
    content <- readLines(file.path(path_site,dir_rmd,f))
    frontMatter <- which(substr(content, 1, 3) == '---')
    if(length(frontMatter) >= 2 & 1 %in% frontMatter) {
      statusLine <- which(substr(content, 1, 7) == 'status:')
      publishedLine <- which(substr(content, 1, 10) == 'published:')
      if(statusLine > frontMatter[1] & statusLine < frontMatter[2]) {
        status <- unlist(strsplit(content[statusLine], ':'))[2]
        status <- sub('[[:space:]]+$', '', status)
        status <- sub('^[[:space:]]+', '', status)
        if(tolower(status) == 'process') {
          #This is a bit of a hack but if a line has zero length (i.e. a
          #black line), it will be removed in the resulting markdown file.
          #This will ensure that all line returns are retained.
          content[nchar(content) == 0] <- ' '
          message(paste('Processing ', f, sep=''))
          content[statusLine] <- 'status: publish'
          content[publishedLine] <- 'published: true'
          
          #outFile <- paste(substr(f, 1, (nchar(f)-(nchar(in_ext)))), out_ext, sep='')
          outFile <- file.path(path_site, dir_md, paste0(substr(f, 1, (nchar(f)-(nchar(in_ext)))), out_ext))
          
          
          #render_markdown(strict=TRUE)
          #andy added from elsewhere, does it do anything ?
          render_jekyll(highlight = "pygments")
          
          opts_knit$set(out.format='markdown') 
          
          # "base.dir is never used when composing the URL of the figures; it is 
          # only used to save the figures to a different directory. 
          # The URL of an image is always base.url + fig.path"
          # https://groups.google.com/forum/#!topic/knitr/18aXpOmsumQ
          
          #andy adding this to try to fix relative path problems
          #opts_knit$set(root.dir=path_site)  
          #opts_knit$set(verbose=TRUE)  
          
          #BEWARE don't set base.dir!! it seems not to do what you'd expect
          #opts_knit$set(base.dir=dir_images)
          #opts_knit$set(base.dir=file.path(path_site, dir_images))
          
          opts_knit$set(base.url = "/")
          opts_chunk$set(fig.path = url_images)                     

          #opts_knit$set(base.url=images.url)
          #opts_knit$set(base.url=file.path(path_site, dir_images))
          ##opts_knit$set(base.url="/")
          
          try(knit(text=content, output=outFile), silent=FALSE)
        } else {
          warning(paste("Not processing ", f, ", status is '", status, 
                        "'. Set status to 'process' to convert.", sep=''))
        }
      } else {
        warning("Status not found in front matter.")
      }
    } else {
      warning("No front matter found. Will not process this file.")
    }
  }
  invisible()
}#load and parse html tables

#load libraries
library(stringr)
library(stringi)
library(XML)
library(dplyr)
library(magrittr)

#function to clean up character vectors- removes punctuation.
get_real_words <- function(word) {
  word[!stringr::str_detect(word, "[^a-z ]")]
}

#Loads all the html tables into one list
table_dir <- "table"
files <- dir(table_dir, "*.html")
tbls <- file.path(table_dir, files) %>%
  lapply(., htmlParse) %>%
  lapply(., readHTMLTable, head = FALSE, stringsAsFactors = FALSE, which = 1) 

all_tbls <- do.call(rbind, tbls)

tbls_words<- gsub("\r", " ", all_tbls$V2)
tbls_words<- gsub("\t", " ", tbls_words) 
tbls_words<- gsub("\n", " ", tbls_words)
tbls_words<- gsub(",", " ", tbls_words)
tblwords.ls <- list(tbls_words)
tblwords.ls <- lapply(tblwords.ls, paste, collapse= " ") %>%
  lapply(., tolower) %>%
  lapply(., WordTokenizer) %>%
  lapply(., get_real_words) %>%
  lapply(., unique)
stopwords<- strsplit(" ", tbls_words)
stopwords <- unique(tblswords[1])


tbls %>%
  lapply(``[[`) %>%

#Currently This code isn't necessary #/
#According to Hadley Wickham, creating an empty dataset and populating it is drastically faster in R
"tbl.df <- data.frame((character(length = length(tbls))), stringsAsFactors = FALSE)

#iterate through the list of tables and parse the html structure
i <- 1
for(i in 1:length(tbls)){
  
  i.df <- readHTMLTable(tbls[i], head = FALSE, stringsAsFactors = FALSE)
  tbl.df <- cbind(tbl.df, i.df)

}

readHTMLTable(tbls[1])


stopwords <- unique(tbls)
"
#Parse a sample table, this is the path
doc <-"table/v02toc.html"

#Pull in html files
p <- htmlParse(doc)

 

#iccv02toc.df <- xmlToDataFrame(p, collectNames = FALSE, stringsAsFactors = FALSE, nodes= iccv02toc[4] )

iccv02toc <- readHTMLTable(p, header = FALSE, stringsAsFactors = FALSE)

#Turn the HtmlInternalDocument into a data.frame
iccv02toc.df <- as.data.frame(iccv02toc[4], stringsAsFactors = FALSE)

#Use dplyr to munge the data from 3 columns of information into several columns of information
#First is to move plaintiff tribe into a separate column.
#iccv02toc.df$table1.V2 <- str_replace_all(iccv02toc.df$table1.V2, "[\t]", "")

v02tocfinal.df <- 
  iccv02toc.df %>%
  mutate(tribe = str_match(table1.V2, "(.*?)\r\n")[,2]) %>%
  
  View()


v02tocfinal.df <- mutate(v02tocfinal.df, page1 = str_extract(v02tocfinal.df$table1.V3, ".*\r\n"))



str(iccv02toc)
write.csv(iccv02toc[4], file = "out/iccv02toc.csv")
#load and parse html tables

#load libraries
library(stringr)
library(stringi)
library(XML)
library(dplyr)
library(magrittr)

#Loads all the html tables into one list
table_dir <- "table"
files <- dir(table_dir, "*.html")
tbls <- file.path(table_dir, files) %>%
  lapply(., htmlParse) %>%
  lapply(., readHTMLTable, head = FALSE, stringsAsFactors = FALSE, which = 1) 

all_tbls <- do.call(rbind, tbls)
#   lapply(., )

tbls %>%
  lapply(``[[`) %>%

#Currently This code isn't necessary #/
#According to Hadley Wickham, creating an empty dataset and populating it is drastically faster in R
"tbl.df <- data.frame((character(length = length(tbls))), stringsAsFactors = FALSE)

#iterate through the list of tables and parse the html structure
i <- 1
for(i in 1:length(tbls)){
  
  i.df <- readHTMLTable(tbls[i], head = FALSE, stringsAsFactors = FALSE)
  tbl.df <- cbind(tbl.df, i.df)

}

readHTMLTable(tbls[1])


stopwords <- unique(tbls)
"
#Parse a sample table, this is the path
doc <-"table/v02toc.html"

#Pull in html files
p <- htmlParse(doc)

 

#iccv02toc.df <- xmlToDataFrame(p, collectNames = FALSE, stringsAsFactors = FALSE, nodes= iccv02toc[4] )

iccv02toc <- readHTMLTable(p, header = FALSE, stringsAsFactors = FALSE)

#Turn the HtmlInternalDocument into a data.frame
iccv02toc.df <- as.data.frame(iccv02toc[4], stringsAsFactors = FALSE)

#Use dplyr to munge the data from 3 columns of information into several columns of information
#First is to move plaintiff tribe into a separate column.
#iccv02toc.df$table1.V2 <- str_replace_all(iccv02toc.df$table1.V2, "[\t]", "")

v02tocfinal.df <- 
  iccv02toc.df %>%
  mutate(tribe = str_match(table1.V2, "(.*?)\r\n")[,2]) %>%
  
  View()


v02tocfinal.df <- mutate(v02tocfinal.df, page1 = str_extract(v02tocfinal.df$table1.V3, ".*\r\n"))



str(iccv02toc)
write.csv(iccv02toc[4], file = "out/iccv02toc.csv")
adios.read.init.method <-function(adios.read.method, comm = .SPMD.CT$comm,
                                  params){
    .Call(R_adios_read_init_method, as.character(adios.read.method),
          comm.c2f(comm), as.character(params))
}

adios.read.open <- function(adios.filename, adios.read.method,
                            comm= .SPMD.CT$comm, adios.lockmode,
                            adios.timeout.sec){  
    .Call(R_adios_read_open, as.character(adios.filename),
          as.character(adios.read.method),comm.c2f(comm),
          as.character(adios.lockmode),as.numeric(adios.timeout.sec))
}

adios.read.close <- function(adios.file.ptr){
    invisible(.Call(R_adios_read_close, adios.file.ptr))
}

adios.read.finalize.method<- function(adios.read.method){
    invisible(.Call(R_adios_read_finalize_method,
                    as.character(adios.read.method)))
}

adios.inq.var <- function(adios.file.ptr, adios.varname){
    .Call(R_adios_inq_var, adios.file.ptr, as.character(adios.varname))
}

custom.inq.var.ndim <- function(adios.varinfo){
    .Call(R_custom_inq_var_ndim, adios.varinfo)
}

custom.inq.var.dims <- function(adios.varinfo){
    .Call(R_custom_inq_var_dims, adios.varinfo)
}

adios.inq.var.blockinfo <- function(adios.file.ptr, adios.varinfo){
    .Call(R_adios_inq_var_blockinfo,adios.file.ptr, adios.varinfo)
}

adios.selection.boundingbox <- function(adios.ndim, adios.start, adios.count){
    .Call(R_adios_selection_bounding_box, as.integer(adios.ndim),
          as.integer(adios.start), as.integer(adios.count))
}

adios.schedule.read <- function(adios.varinfo, adios.start, adios.count,
                                adios.file.ptr, adios.selection, adios.varname,
                                adios.from.steps, adios.nsteps){
    .Call(R_adios_schedule_read, adios.varinfo, as.integer(adios.start),
          as.integer(adios.count), adios.file.ptr, adios.selection,
          as.character(adios.varname), as.integer(adios.from.steps),
          as.integer(adios.nsteps))
}

custom.data.access <- function(adios.data, adios.selection, adios.varinfo){
    .Call(R_custom_data_access, adios.data, adios.selection,adios.varinfo)
}

adios.perform.reads <- function(adios.file.ptr, adios.blocking){
    .Call(R_adios_perform_reads,adios.file.ptr, as.integer(adios.blocking))
}

adios.advance.step <- function(adios.file.ptr, adios.last, adios.timeout.sec){
    invisible(.Call(R_adios_advance_step,adios.file.ptr,
                    as.integer(adios.last), as.numeric(adios.timeout.sec)))
}

adios.errno <- function(){
    .Call(R_adios_errno)
}


REBOL [
	Title:   "Red compiler"
	Author:  "Nenad Rakocevic"
	File: 	 %compiler.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

do-cache %system/compiler.r

red: context [
	verbose:	   0									;-- logs verbosity level
	job: 		   none									;-- reference the current job object	
	script-name:   none
	script-path:   none
	main-path:	   none
	runtime-path:  %runtime/
	include-stk:   make block! 3
	included-list: make block! 20
	symbols:	   make hash! 1000
	globals:	   make hash! 1000						;-- words defined in global context
	aliases: 	   make hash! 100
	contexts:	   make hash! 100						;-- storage for statically compiled contexts
	ctx-stack:	   make block! 8						;-- contexts access path
	shadow-funcs:  make block! 1000						;-- shadow functions contexts [symbol object! ctx...]
	objects:	   make block! 600						;-- shadow objects contexts [name object! ctx...]
	obj-stack:	   to path! 'objects					;-- current object access path
	container-obj?: none								;-- closest wrapping object
	func-objs:	   none									;-- points to 'objects first in-function object
	paths-stack:   make block! 4						;-- stack of generated code for handling dual codepaths for paths
	rebol-gctx:	   bind? 'rebol
	expr-stack:	   make block! 8
	
	lexer: 		   do bind load-cache %lexer.r 'self
	extracts:	   do bind load-cache %utils/extractor.r 'self ;-- @@ to be removed once we get redbin loader.
	sys-global:    make block! 1
	lit-vars: 	   reduce [
		'block	   make hash! 1000
		'string	   make hash! 1000
		'context   make hash! 1000
	]
	 
	pc: 		   none
	locals:		   none
	locals-stack:  make block! 32
	output:		   make block! 100
	sym-table:	   make block! 1000
	literals:	   make block! 1000
	declarations:  make block! 1000
	bodies:		   make block! 1000
	ssa-names: 	   make block! 10						;-- unique names lookup table (SSA form)
	last-type:	   none
	return-def:    to-set-word 'return					;-- return: keyword
	s-counter:	   0									;-- series suffix counter
	depth:		   0									;-- expression nesting level counter
	max-depth:	   0
	booting?:	   none									;-- YES: compiling boot script
	no-global?:	   no									;-- YES: put global code in a function
	nl: 		   newline
 
	unboxed-set:   [integer! char! float! float32! logic!]
	block-set:	   [block! paren! path! set-path! lit-path!]	;@@ missing get-path!
	string-set:	   [string! binary!]
	series-set:	   union block-set string-set
	
	actions: 	   make block! 100
	op-actions:	   make block! 20
	keywords: 	   make block! 10
	
	actions-prefix: to path! 'actions
	natives-prefix: to path! 'natives
	
	intrinsics:   [
		if unless either any all while until loop repeat
		foreach forall break func function does has
		exit return switch case routine set get reduce
		context object construct
	]
	
	logic-words:  [true false yes no on off]
	
	word-iterators: [repeat foreach forall]				;-- only ones that use word(s) as counter
	
	iterators: [loop until while repeat foreach forall]

	func-constructors: [
		'func | 'function | 'does | 'has | 'routine | 'make 'function!
	]

	functions: make hash! [
	;---name--type--arity----------spec----------------------------refs--
		make [action! 2 [type [datatype! word!] spec [any-type!]] #[none]]	;-- must be pre-defined
	]
	
	make-keywords: does [
		foreach [name spec] functions [
			if spec/1 = 'intrinsic! [
				repend keywords [name reduce [to word! join "comp-" name]]
			]
		]
		bind keywords self
	]

	set-last-none: does [copy [stack/reset none/push-last]]	;-- copy required for R/S line counting injection

	--not-implemented--: does [print "Feature not yet implemented!" halt]
	
	quit-on-error: does [
		clean-up
		if system/options/args [quit/return 1]
		halt
	]

	throw-error: func [err [word! string! block!]][
		print [
			"*** Compilation Error:"
			either word? err [
				join uppercase/part mold err 1 " error"
			][reform err]
			"^/*** in file:" mold script-name
			;either locals [join "^/*** in function: " func-name][""]
		]
		if pc [
			print [
				;"*** at line:" calc-line lf
				"*** near:" mold copy/part pc 8
			]
		]
		quit-on-error
	]
	
	dispatch-ctx-keywords: func [original [any-word! none!] /with alt-value][
		if path? alt-value [alt-value: alt-value/1]
		
		switch/default any [alt-value pc/1][
			func	  [comp-func]
			function  [comp-function]
			has		  [comp-has]
			does	  [comp-does]
			routine	  [comp-routine]
			construct [comp-construct]
			object
			context	  [
				either obj: is-object? pc/2 [
					comp-context/with/extend original obj
				][
					comp-context/with original
				]
			]
		][no]
	]
	
	relative-path?: func [file [file!]][
		not find "/~" first file
	]
	
	process-include-paths: func [code [block!] /local rule file][
		parse code rule: [
			some [
				#include file: (
					script-path: any [script-path main-path]
					if all [script-path relative-path? file/1][
						file/1: clean-path join script-path file/1
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	process-calls: func [code [block!] /global /local rule pos mark][
		parse code rule: [
			some [
				#call pos: (
					mark: tail output
					process-call-directive pos/1 to logic! global
					change/part back pos mark 2
					clear mark
				)
				| into rule
				| skip
			]
		]
	]
	
	preprocess-strings: func [code [block!] /local rule s][  ;-- re-encode strings for Red/System
		parse code rule: [
			any [
				s: string! (lexer/decode-UTF8-string s/1)
				into rule
				| skip
			]
		]
	]
	
	convert-to-block: func [mark [block!]][
		change/part/only mark copy/deep mark tail mark	;-- put code between [...]
		clear next mark									;-- remove code at "upper" level
	]
	
	any-function?: func [value [word!]][
		find [native! action! op! function! routine!] value
	]
	
	scalar?: func [expr][
		find [
			unset!
			none!
			logic!
			datatype!
			char!
			integer!
			tuple!
			decimal!
			refinement!
			issue!
			lit-word!
			word! 
			get-word!
			set-word!
		] type?/word :expr
	]
	
	local-bound?: func [original [any-word!] /local obj][
		all [
			not empty? locals-stack
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		]
	]
	
	local-word?: func [name [word!]][
		all [not empty? locals-stack find last locals-stack name]
	]
	
	unicode-char?: func [value][
		all [issue? value value/1 = #"'"]
	]
	
	float-special?: func [value][
		all [issue? value value/1 = #"."]
	]
	
	insert-lf: func [pos][
		new-line skip tail output pos yes
	]
	
	emit: func [value][
		either block? value [append output value][append/only output value]
	]
		
	emit-src-comment: func [pos [block! paren! none!] /with cmt [string!]][
		unless cmt [
			cmt: trim/lines mold/only/flat clean-lf-deep copy/deep/part pos offset? pos pc
		]
		if 50 < length? cmt [cmt: append copy/part cmt 50 "..."]
		emit reduce [
			'------------| (cmt)
		]
	]
	
	find-ssa: func [name [word!]][find/skip ssa-names name 2]
	
	select-ssa: func [name [word!] /local pos][
		all [pos: find/skip ssa-names name 2 pos/2]
	]
	
	parent-object?: func [obj [object!]][
		all [not empty? locals-stack (next first obj) = container-obj?]
	]
	
	find-binding: func [original [any-word!] /local ctx idx obj][
		all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				any [select objects obj select shadow-funcs obj]
			]
			attempt [idx: get-word-index/with to word! original ctx]
			reduce [ctx idx]
		]
	]
	
	bind-function: func [body [block!] shadow [object!] /local self* rule pos][
		bind body shadow
		if 1 < length? obj-stack [
			self*: in do obj-stack 'self				;-- rebing SELF to the wrapping object
			
			parse body rule: [
				any [pos: 'self (pos/1: self*) | into rule | skip]
			]
		]
	]
	
	get-word-index: func [name [word!] /with c [word!] /local ctx pos list][
		if with [
			ctx: select contexts c
			return (index? find ctx name) - 1
		]
		list: tail ctx-stack
		until [											;-- search backward in parent contexts
			list: back list
			ctx: select contexts list/1
			if pos: find ctx name [
				return (index? pos) - 1					;-- 0-based access in context table
			]
			head? list
		]
		throw-error ["Should not happen: not found context for word: " mold name]
	]
	
	emit-push-from: func [
		name [any-word!] original [any-word!] type [word!] actions [block!]
		/local ctx obj idx
	][
		either all [
			ctx: all [
				rebol-gctx <> obj: bind? original
				select objects obj
			]
			attempt [idx: get-word-index/with name ctx]
		][
			emit append to path! type actions/1
			emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
			emit idx
			insert-lf -3
		][
			emit append to path! type actions/2
			emit prefix-exec name
			insert-lf -2
		]
	]
	
	emit-push-word: func [name [any-word!] original [any-word!] /local type ctx obj][
		type: to word! form type? name
		name: to word! :name
		
		either all [
			rebol-gctx <> obj: bind? original
			ctx: select shadow-funcs obj
		][
			emit append to path! type 'push-local
			emit ctx
			emit get-word-index name					;@@ replace that 
			insert-lf -3
		][
			emit-push-from name original type [push-local push]
		]
	]
	
	emit-get-word: func [name [word!] original [any-word!] /any? /literal /local new obj][
		either all [
			rebol-gctx <> obj: bind? original
			find shadow-funcs obj
		][
			emit 'stack/push							;-- local word
		][
			if new: select-ssa name [name: new]			;@@ add a check for function! type
			emit case [									;-- global word
				literal ['get-word/get]
				any?	['word/get-any]
				'else	[
					emit-push-from name name 'word [get-local get]
					exit
				]
			]
		]
		emit decorate-symbol name
		insert-lf -2
	]
	
	emit-load-string: func [buffer [string! file! url!]][
		emit to path! reduce [to word! form type? buffer 'load]
		emit form buffer
		emit 1 + length? buffer							;-- account for terminal zero
		emit 'UTF-8
	]
	
	emit-open-frame: func [name [word!] /local type][
		unless find symbols name [add-symbol name]
		emit case [
			'function! = all [
				type: find functions name
				first first next type
			]['stack/mark-func]
			name = 'try	  ['stack/mark-try]
			name = 'catch ['stack/mark-catch]
			'else		  ['stack/mark-native]
		]
		emit prefix-exec name
		insert-lf -2
	]
	
	emit-close-frame: func [/last][
		emit pick [stack/unwind-last stack/unwind] to logic! last
		insert-lf -1
	]
	
	emit-stack-reset: does [
		emit 'stack/reset
		insert-lf -1
	]
	
	emit-dyn-check: does [
		emit 'stack/check-call
		insert-lf -1
	]
	
	emit-action: func [name [word!] /with options [block!]][
		emit join actions-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-native: func [name [word!] /with options [block!]][
		emit join natives-prefix to word! join name #"*"
		insert-lf either with [
			emit options
			-1 - length? options
		][
			-1
		]
	]
	
	emit-exit-function: does [
		emit [
			stack/unwind-last
			stack/unroll stack/FLAG_FUNCTION
			ctx/values: as node! pop
			exit
		]
		insert-lf -5
	]
	
	emit-deep-check: func [path [series!] /local list check check2 obj top? parent-ctx][
		check:  [
			'object/unchanged?
				prefix-exec path/1
				third obj: find objects do obj-stk
		]
		check2: [
			'object/unchanged2?
				parent-ctx
				get-word-index/with path/1 parent-ctx
				third obj: find objects do obj-stk
		]
		obj-stk: copy obj-stack
		obj-stk/1: either find-contexts path/1 ['func-objs]['objects]

		either 2 = length? path [
			append obj-stk path/1
			reduce check
		][
			list: make block! 3 * length? path
			while [not tail? next path][
				append obj-stk path/1
				repend list get pick [check check2] head? path
				parent-ctx: obj/2
				path: next path
			]
			new-line list on
			new-line skip list 3 on
			new-line/all/skip skip list 3 on 4
			reduce ['all list]
		]
	]
	
	get-counter: does [s-counter: s-counter + 1]
	
	clean-lf-deep: func [blk [block! paren!] /local pos][
		blk: copy/deep blk
		parse blk rule: [
			pos: (new-line/all pos off)
			into rule | skip
		]
		blk
	]

	clean-lf-flag: func [name [word! lit-word! set-word! get-word! refinement!]][
		mold/flat to word! name
	]
	
	prefix-func: func [word [word!] /with path][
		if 1 < length? obj-stack [
			path: any [obj-func-call? word next any [path obj-stack]]
			word: decorate-obj-member word path
		]
		word
	]
	
	prefix-exec: func [word [word!]][
		either any [empty? locals-stack not find-contexts word][
			decorate-symbol word
		][
			decorate-exec-ctx decorate-symbol word ;-- 'exec prefix to access the word! and not the local value
		]
	]
	
	generate-anon-name: has [name][
		add-symbol name: to word! rejoin ["<anon" get-counter #">"]
		name
	]
	
	decorate-obj-member: func [word [word!] path /local value][
		parse value: mold path [some [p: #"/" (p/1: #"~") | skip]]
		to word! rejoin [value #"~" word]
	]
	
	decorate-type: func [type [word!]][
		to word! join "red-" mold/flat type
	]
	
	decorate-exec-ctx: func [name [word!]][
		append to path! 'exec name
	]
	
	decorate-symbol: func [name [word!] /local pos][
		if pos: find/case/skip aliases name 2 [name: pos/2]
		to word! join "~" clean-lf-flag name
	]
	
	decorate-func: func [name [word!] /strict /local new][
		if all [not strict new: select-ssa name][name: new]
		to word! join "f_" clean-lf-flag name
	]
	
	decorate-series-var: func [name [word!] /local new list][
		new: to word! join name get-counter
		list: select lit-vars select [blk block str string ctx context] name
		if all [list not find list new][append list new]
		new
	]
	
	declare-variable: func [name [string! word!] /init value /local var set-var][
		set-var: to set-word! var: to word! name

		unless find declarations set-var [
			repend declarations [set-var any [value 0]]	;-- declare variable at root level
			new-line skip tail declarations -2 yes
		]
		reduce [var set-var]
	]
	
	add-symbol: func [name [word!] /local sym id alias][
		unless find/case symbols name [
			if find symbols name [
				if find/case/skip aliases name 2 [exit]
				alias: decorate-series-var name
				repend aliases [name alias]
			]
			sym: decorate-symbol name
			id: 1 + ((length? symbols) / 2)
			repend symbols [name reduce [sym id]]
			repend sym-table [
				to set-word! sym 'word/load mold name
			]
			new-line skip tail sym-table -3 on
		]
	]
	
	get-symbol-id: func [name [word!]][
		second select symbols name
	]
	
	add-global: func [name [word!]][
		unless any [
			local-word? name
			find globals name
		][
			repend globals [name 'unset!]
		]
	]
	
	push-call: func [name [word! tag!]][
		append expr-stack name
	]
	
	pop-call: does [
		remove back tail expr-stack
	]
	
	add-context: func [ctx [block!] /local name][
		append contexts name: decorate-series-var 'ctx
		append/only contexts ctx
		name
	]
	
	push-context: func [ctx [block!] /local name][
		append ctx-stack name: add-context ctx
		name
	]
	
	pop-context: does [
		clear back tail ctx-stack
	]
	
	find-contexts: func [name [word!]][
		ctx: tail ctx-stack
		while [not head? ctx][
			ctx: back ctx
			if find select contexts ctx/1 name [return ctx/1]
		]
		none
	]
	
	to-context-spec: func [spec [block!]][
		spec: copy spec
		forall spec [spec/1: to set-word! spec/1]
		append spec none
		make object! spec
	]
	
	iterator-pending?: does [
		not empty? intersect expr-stack iterators
	]
	
	get-obj-base: func [name [any-word!]][
		either local-word? name [func-objs][objects]
	]
	
	get-obj-base-word: func [name [any-word!]][
		either local-word? name ['func-objs]['objects]
	]
	
	find-proto: func [obj [block!] fun [word!] /local proto o multi?][
		if proto: obj/4 [
			all [
				multi?: 2 = length? proto				;-- multiple inheritance case
				in proto/1 fun
				in proto/2 fun
				return obj/1							;-- method redefined in spec
			]
			if in proto/1 fun [return obj/1]			;-- check <spec> prototype
			if o: find-proto find objects proto/1 fun [return o] ;-- recurse into previous prototypes
			
			unless proto/2 [return none]				;-- finish if simple inheritance case
			if in proto/2 fun [return proto/2]			;-- check <base> prototype
			if o: find-proto find objects proto/2 fun [return o] ;-- recurse into previous prototypes
		]
		none
	]
	
	object-access?: func [path [series!]][
		either path/1 = 'self [
			bind? path/1
		][
			attempt [do head insert copy/part to path! path (length? path) - 1 get-obj-base-word path/1]
		]
	]
	
	is-object?: func [expr][
		unless find [word! get-word! path!] type?/word expr [return none]
		attempt [do join obj-stack expr]
	]
	
	obj-func-call?: func [name [any-word!] /local obj][
		if any [rebol-gctx = obj: bind? name find shadow-funcs obj][return no]
		select objects obj
	]
	
	obj-func-path?: func [path [path!] /local search base fpath symbol found? fun origin name obj][
		either path/1 = 'self [
			found?: bind? path/1
			path: copy path
			path/1: pick find objects found? -1
			fun: head insert copy path 'objects 
			fpath: head clear next copy path
		][
			search: [
				fpath: head insert copy path base
				until [									;-- evaluate nested paths from longer to shorter
					remove back tail fpath
					any [
						tail? next fpath
						object? found?: attempt [do fpath]	;-- path evaluates to an object: found!
					]
				]
			]

			base: get-obj-base-word path/1
			do search									;-- check if path is an absolute object path

			if all [not found? 1 < length? obj-stack][
				base: obj-stack
				do search								;-- check if path is a relative object path
				unless found? [return none]				;-- not an object access path
			]

			fun: append copy fpath either base = obj-stack [ ;-- extract function access path without refinements
				pick path 1 + (length? fpath) - (length? obj-stack)
			][
				pick path length? fpath
			]
			unless function! = attempt [do fun][return none] ;-- not a function call
			remove fpath								;-- remove 'objects prefix
		]

		obj: 	find objects found?
		origin: find-proto obj last fun
		name:	either origin [select objects origin][obj/2]
		symbol: decorate-obj-member first find/tail fun fpath name

		either find functions symbol [
			fpath: next find path last fpath			;-- point to function name
			reduce [
				either 1 = length? fpath [fpath/1][copy fpath]
				symbol
				obj/2 									;-- object instance ctx name
			]
		][
			none
		]
	]
	
	push-locals: func [symbols [block!]][
		append/only locals-stack symbols
	]

	pop-locals: does [
		also
			last locals-stack
			remove back tail locals-stack
	]
	
	literal-first-arg?: func [spec [block!]][
		parse spec [
			any [
				word! 		(return no)
				| lit-word! (return yes)
				| /local	(return no)
				| skip
			]
		]
		no
	]
	
	infix?: func [pos [block! paren!] /local specs][
		all [
			not tail? pos
			word? pos/1
			specs: select functions pos/1
			'op! = specs/1
			not all [									;-- check if a literal argument is not expected
				word? pos/-1
				specs: select functions pos/-1
				literal-first-arg? specs/3				;-- literal arg needed, disable infix mode
			]
		]
	]
	
	convert-types: func [spec [block!] /local value][
		forall spec [
			if spec/1 = /local [break]					;-- avoid processing local variable
			if all [
				block? value: spec/1
				not find [integer! logic!] value/1 
			][
				value/1: decorate-type either value/1 = 'any-type! ['value!][value/1]
			]
		]
	]
	
	rewrite-locals: func [code [block!] /local rule pos word ctx][
		parse code rule: [
			some [
				'stack/push pos: skip (
					if #"~" = first word: form pos/1 [
						if ctx: find-contexts word: to word! next word [
							change/part back pos reduce [
								'word/get-local ctx get-word-index word
							] 2
							new-line back pos yes
						]
					]
				)
				| into rule
				| skip
			]
		]
	]
	
	check-invalid-call: func [name [word!]][
		if all [
			find [exit return] name
			empty? locals-stack
		][
			pc: back pc
			throw-error "EXIT or RETURN used outside of a function"
		]
	]
	
	check-redefined: func [name [word!] /local pos][
		if pos: find functions name [
			remove/part pos 2							;-- remove previous function definition
		]
		if pos: find get-obj-base name name [
			pos/1: none
		]
	]
	
	check-func-name: func [name [word!] /local new pos][
		if find functions name [
			new: to word! append mold/flat name get-counter
			either pos: find-ssa name [
				pos/2: new
			][
				repend ssa-names [name new]
			]
			name: new
		]
		name
	]
	
	check-cloned-function: func [new [word!] /local name alter entry pos][
		if all [
			get-word? pc/1
			name: to word! pc/1	
			all [
				alter: get-prefix-func name
				entry: find functions alter
				name: alter
			]
		][
			if alter: select-ssa name [
				entry: find functions alter
			]
			repend functions [new entry/2]
			
			either pos: find-ssa new [					;-- add the real function name as alias
				pos/2: name
			][
				repend ssa-names [new name]
			]
		]
	]
	
	check-new-func-name: func [path [path!] symbol [word!] ctx [word!] /local name][
		if any [
			set-word? name: pc/-1
			all [lit-word? name 'set = pc/-2]
		][
			name: to word! name
			repend functions [name append select functions symbol ctx]
			
			either pos: find-ssa name [					;-- add the real function name as alias
				pos/2: symbol
			][
				repend ssa-names [name symbol]
			]
		]
	]
	
	check-spec: func [spec [block!] /local symbols value pos stop locals return?][
		symbols: make block! length? spec
		locals:  0
		
		unless parse spec [
			opt string!
			any [
				pos: /local (append symbols 'local) some [
					pos: word! (
						append symbols to word! pos/1
						locals: locals + 1
					)
					pos: opt block! pos: opt string!
				]
				| set-word! (
					if any [return? pos/1 <> return-def][stop: [end skip]]
					return?: yes						;-- allow only one return: statement
				) stop pos: block! opt string!
				| [
					[word! | lit-word! | get-word!] opt block! opt string!
					| refinement! opt string!
				] (append symbols to word! pos/1)
			]
		][
			throw-error ["invalid function spec block:" mold pos]
		]
		forall spec [
			if all [
				word? spec/1
				find next spec spec/1
			][
				pc: skip pc -2
				throw-error ["duplicate word definition:" spec/1]
			]
		]
		reduce [symbols locals]
	]
	
	make-refs-table: func [spec [block!] /local mark pos arity arg-rule list ref args][
		arity: 0
		arg-rule: [word! | lit-word! | get-word!]
		parse spec [
			any [
				arg-rule (arity: arity + 1)
				| mark: refinement! (pos: mark) break
				| skip
			]
		]
		if all [pos pos/1 <> /local][
			list: make block! 8
			ref: 0
			parse pos [
				some [
					pos: refinement! opt string! (
						ref: ref + 1
						if pos/1 = /local [return reduce [list arity]]
						repend list [pos/1 ref 0]
						args: 0
					)
					| arg-rule opt block! opt string! (
						change back tail list args: args + 1	;@@ one argument by refinement max!!
					)
					| set-word! break
				]
			]
		]
		reduce [list arity]
	]
	
	get-prefix-func: func [name [word!] /local path word ctx][
		if 1 < length? obj-stack [
			path: copy obj-stack
			while [1 < length? path][
				if all [word: in do path name function! = get word][
					return prefix-func/with name path
				]
				remove back tail path
			]
		]
		if all [										;-- check for method case during function compilation stage
			container-obj?
			ctx: obj-func-call? name
		][
			return decorate-obj-member name ctx
		]
		name
	]
	
	add-function: func [name [word!] spec [block!] /type kind [word!] /local refs arity][
		set [refs arity] make-refs-table spec
		repend functions [name reduce [any [kind 'function!] arity spec refs]]
	]
	
	fetch-functions: func [pos [block!] /local name type spec refs arity][
		name: to word! pos/1
		if find functions name [exit]					;-- mainly intended for 'make (hardcoded)

		switch type: pos/3 [
			native! [if find intrinsics name [type: 'intrinsic!]]
			action! [append actions name]
			op!     [repend op-actions [name to word! pos/4]]
		]
		spec: either pos/3 = 'op! [
			third select functions to word! pos/4
		][
			clean-lf-deep pos/4/1
		]
		set [refs arity] make-refs-table spec
		repend functions [name reduce [type arity spec refs]]
	]
	
	emit-block: func [
		blk [any-block!] /sub level [integer!] /bind ctx [word!]
		/local class name item value word action type binding
	][
		if path? blk [class: 'path]
		
		unless sub [
			emit-open-frame 'append
			emit to set-word! name: decorate-series-var any [class 'blk]
			emit append to path! any [class 'block] 'push*
			emit max 1 length? blk
			insert-lf -3
		]
		level: 0
		
		forall blk [
			item: blk/1
			either any-block? :item [
				type: either all [path? item get-word? item/1][
					item/1: to word! item/1 ;this is workaround of missing get-path! in R2
					'get-path
				][type? :item]
				
				emit-open-frame 'append
				emit to lit-path! reduce [to word! form type 'push*]
				emit max 1 length? item
				insert-lf -2
				
				level: level + 1
				either bind [
					emit-block/sub/bind to block! item level ctx
				][
					emit-block/sub to block! item level
				]
				level: level - 1
				
				emit-close-frame
				emit 'block/append*
				insert-lf -1
				emit 'stack/keep						;-- reset stack, but keep block as last value
				insert-lf -1
			][
				if :item = #get-definition [			;-- temporary directive
					value: select extracts/definitions blk/2
					change/only/part blk value 2
					item: blk/1
				]
				action: 'push
				value: case [
					unicode-char? :item [
						value: item
						item: #"_"						;-- placeholder just to pass the char! type to item
						to integer! next value
					]
					any-word? :item [
						add-symbol word: to word! clean-lf-flag item
						value: decorate-symbol word
						either all [bind local-word? to word! :item][
							action: 'push-local
							reduce [ctx get-word-index/with to word! :item ctx]
						][
							either binding: find-binding :item [
								action: 'push-local
								binding
							][
								value
							]
						]
					]
					issue? :item [
						add-symbol word: to word! form item
						decorate-symbol word
					]
					find [string! file! url!] type?/word :item [
						emit [tmp:]
						insert-lf -1
						emit-load-string item
						new-line back tail output off
						'tmp
					]
					find [logic! unset! datatype!] type?/word :item [
						to word! form :item
					]
					none? :item [
						[]								;-- no argument
					]
					'else [
						item
					]
				]
				either float-special? :item [
					emit 'float/push64
					emit-fp-special item
					insert-lf -3
				][
					either decimal? :item [
						emit 'float/push64
						emit-float item
						insert-lf -3
					][
						emit to path! reduce [to word! form type? :item action]
						emit value
						insert-lf -1 - either block? value [length? value][1]
					]
				]
				
				emit 'block/append*
				insert-lf -1
				unless tail? next blk [
					emit 'stack/keep					;-- reset stack, but keep block as last value
					insert-lf -1
				]
			]
		]
		unless sub [emit-close-frame]
		name
	]
	
	emit-eval-path: func [/set][
		emit 'actions/eval-path*
		emit either set ['true]['false]
		insert-lf -2
	]
	
	emit-path: func [
		path [path! set-path!] set? [logic!] alt? [logic!]
		/local value mark assign original
	][
		value: path/1
		
		assign: [
			either alt? [								;-- object path (fallback case)
				emit [stack/push stack/arguments - 1]	;-- get arguments just below the stack record
				insert-lf -4
			][
				comp-expression							;-- fetch assigned value (normal case)
			]
			emit-eval-path/set
			emit-close-frame
		]
		
		switch type?/word original: value [
			word! [
				add-symbol value: to word! clean-lf-flag value
				case [
					head? path [
						emit-get-word value original
					]
					all [set? tail? next path][
						emit-open-frame 'eval-set-path
						emit-path back path set? alt?
						emit-push-word value value
						do assign
					]
					'else [
						emit-open-frame 'select
						emit-path back path set? alt?
						emit-push-word value value
						emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
						emit-close-frame
					]
				]
			]
			get-word! [
				either all [set? tail? next path][
					emit-open-frame 'poke
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [unless stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- SELECT action
					emit [stack/pop 1]					;-- overwrite the get-word on stack top
					insert-lf -2
					emit-open-frame 'find
					emit-path back path set? alt?
					emit-get-word to word! value original
					emit-action/with 'find [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
					emit-action 'index?
					emit [stack/pop 2]
					insert-lf -2
					emit [integer/push 1]
					insert-lf -2
					emit-action 'add
					emit-close-frame
					convert-to-block mark
					do assign
				][
					emit-open-frame 'pick-select
					emit-path back path set? alt?
					emit-get-word to word! value original
					
					emit copy/deep [either stack/top-type? = TYPE_INTEGER] ;-- choose action at run-time
					insert-lf -4
					
					mark: tail output					;-- PICK action
					emit-action 'pick
					convert-to-block mark
					
					mark: tail output					;-- SELECT action
					emit-action/with 'select [-1 -1 -1 -1 -1 -1 -1 -1]
					convert-to-block mark
					
					emit-close-frame
				]
			]
			integer! [
				either all [set? tail? next path][
					emit-open-frame 'eval-set-path
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					do assign
				][
					emit-open-frame 'pick
					emit-path back path set? alt?
					emit compose [integer/push (value)]
					insert-lf -2
					emit-action 'pick
					emit-close-frame
				]
			]
			string!	[
				--not-implemented--
			]
		]
	]
	
	emit-path-func: func [body [block!] octx [word!] cnt [integer!] /local pos f-name rule arity name][
		pos: body
		body: copy pos
		clear pos
		
		if all [1 = length? body body/1 = 'stack/reset][clear body]
		rewrite-locals body
		
		name: either pos: find body 'pos [
			either body = [
				stack/push pos
				stack/reset
			][
				clear body
				2
			][
				insert body [
					pos: stack/arguments
				]
				4
			]
		][2]
		if #"~" <> first form name: pick body name [
			name: [words/_anon]
		]
		
		if all [not empty? body 'stack/unwind = last body][
			change/only back tail body 'stack/unwind-last
			new-line back tail body yes
		]
		unless any [empty? body 1 = length? body][
			arity: 0
			parse body rule: [
				some [
					'stack/push 'pos pos: '+ (
						arity: arity + 1
						either arity = 1 [pos: remove/part pos 2][pos/2: arity - 1]
					) :pos
					| into rule
					| skip
				]
			]
			redirect-to declarations [
				f-name: decorate-func to word! join "~path" cnt
				emit reduce [to set-word! f-name 'func [octx [node!] /local pos] body]
				insert-lf -4
			]
			emit compose [
				stack/defer-call (name) as-integer (to get-word! f-name) (arity) (octx)
			]
			f-name
		]
	]
	
	emit-dynamic-path: func [
		body [block!]
		/local path pname idx mark saved cnt frame? octx
	][
		octx: pick [octx null] to logic! all [
			not empty? locals-stack
			container-obj?
		]
		path: first paths-stack
		redirect-to literals [pname: emit-block path]
		
		if frame?: all [
			not emit-path-func body octx cnt: get-counter
			not empty? expr-stack
			find [<infix> switch case] last expr-stack
		][
			emit-open-frame 'dyn-path					;-- wrap it in a stack frame in this case
		]
		emit-get-word path/1 path/1
		insert-lf -2
		saved: output
		
		forall path [
			emit [either stack/func?]
			insert-lf -2
			idx: (index? path) - 1
			emit compose/deep [[stack/push-call (pname) (idx) 0 (octx)]]

			either tail? next path [
				emit compose/deep [[
					stack/top: stack/top - 1
					copy-cell stack/top stack/top - 1
					stack/check-call
				]]
			][
				mark: tail output
				unless head? path [
					emit compose/deep [
						stack/top: stack/top - 1
						copy-cell stack/top stack/top - 1
					]
				]
				emit-open-frame 'eval-path
				emit [stack/push stack/arguments - 1]
				insert-lf -4
				emit append to path! to word! form type? path/2 'push
				emit prefix-exec path/2
				insert-lf -2
				emit-eval-path no
				emit 'stack/unwind-part
				insert-lf -1
				change/only/part mark mark: copy mark tail output
				output: mark
			]
		]
		remove paths-stack
		output: saved
		if frame? [emit-close-frame]
	]
	
	emit-routine: func [name [word!] spec [block!] /local type cnt offset alter][
		emit [stack/reset]

		declare-variable/init 'r_arg to paren! [as red-value! 0]
		emit [r_arg: stack/arguments]
		insert-lf -2

		offset: 0
		if all [
			type: select spec return-def
			find [integer! logic!] type/1 
		][
			offset: 1
			append/only output append to path! form get type/1 'box
		]
		if alter: select-ssa name [name: alter]
		emit name
		cnt: 0

		forall spec [
			if string? spec/1 [
				if tail? remove spec [break]
			]
			if any [spec/1 = /local set-word? spec/1][
				spec: head spec
				break									;-- avoid processing local variable	
			]
			unless block? spec/1 [
				unless block? spec/2 [
					insert/only next spec [red-value!]
				]
				either find [integer! logic!] spec/2/1 [
					append/only output append to path! form get spec/2/1 'get
				][
					emit reduce ['as spec/2/1]
				]
				emit 'r_arg
				unless head? spec [emit reduce ['+ cnt]]
				cnt: cnt + 1
			]
		]
		insert-lf negate cnt * 2 + offset + 1
	]
	
	redirect-to: func [out [block!] body [block!] /local saved][
		saved: output
		output: out
		also
			do body
			output: saved
	]

	emit-float: func [value [decimal!] /local bin][
		bin: IEEE-754/to-binary64 value
		emit to integer! copy/part bin 4
		emit to integer! skip bin 4
	]

	emit-fp-special: func [value [issue!]][
		switch next value [
			#INF  [emit to integer! #{7FF00000} emit 0]
			#INF- [emit to integer! #{FFF00000} emit 0]
			#NaN  [emit to integer! #{7FF80000} emit 0]			;-- smallest quiet NaN
			#0-	  [emit to integer! #{80000000} emit 0]
		]
	]
	
	comp-literal: func [/inactive /with val /local value char? special? name w make-block type][
		value: either with [val][pc/1]					;-- val can be NONE
		either any [
			char?: unicode-char? value
			special?: float-special? value
			scalar? :value
		][			
			case [
				char? [
					emit 'char/push
					emit to integer! next value
					insert-lf -2
				]
				special? [
					emit 'float/push64
					emit-fp-special value
					insert-lf -3
				]
				decimal? :value [
					emit 'float/push64
					emit-float value
					insert-lf -3
				]
				find [refinement! issue! lit-word!] type?/word :value [
					add-symbol w: to word! form value
					type: to word! form type? :value
					if all [lit-word? :value not inactive][type: 'word]
					
					either all [not issue? :value local-word? w][
						emit append to path! type 'push-local
						emit last ctx-stack
						emit get-word-index w
						insert-lf -3
					][
						emit to path! reduce [type 'push]
						emit to path! reduce ['exec decorate-symbol w]	;@@ replace by prefix-exec
						insert-lf -2
					]
				]
				none? :value [
					emit 'none/push
					insert-lf -1
				]
				any-word? :value [
					add-symbol to word! :value
					emit-push-word :value :value
				]
				'else [
					emit to path! reduce [to word! form type? :value 'push]
					emit load mold :value
					insert-lf -2
				]
			]
		][
			make-block: [
				redirect-to literals [
					value: to block! value
					either empty? ctx-stack [
						emit-block value
					][
						emit-block/bind value last ctx-stack
					]
				]
			]
			switch/default type?/word value [
				block!	[
					name: do make-block
					emit 'block/push
					emit name
					insert-lf -2
				]
				paren!	[
					name: do make-block
					emit 'paren/push
					emit name
					insert-lf -2
				]
				path! set-path!	[
					name: do make-block
					case [
						inactive [
							either get-word? pc/1/1 [
								emit 'get-path/push
							][
								emit to path! reduce [to word! form type? pc/1 'push]
							]
						]
						lit-path? pc/1 [
							emit 'path/push
						]
						true [
							emit to path! reduce [to word! form type? pc/1 'push]
						]
					]
					emit name
					insert-lf -2
				]
				string!	file! url! [
					redirect-to literals [
						emit to set-word! name: decorate-series-var 'str
						insert-lf -1
						emit-load-string value
					]	
					emit to path! reduce [to word! form type? value 'push]
					emit name
					insert-lf -2
				]
				binary!	[]
			][
				throw-error ["comp-literal: unsupported type" mold value]
			]
		]
		unless with [pc: next pc]
		name
	]
	
	inherit-functions: func [new [object!] extend [object!] /local symbol name][ ;-- multiple inheritance case
		foreach word next first extend [
			if function! = get in extend word [
				symbol: decorate-obj-member word select objects extend
				
				repend functions [
					name: decorate-obj-member word select objects new
					select functions symbol
				]
				
				append bodies name
				append bodies bind/copy copy/part next find bodies symbol 8 new
				add-symbol name
			]
		]
	]
	
	comp-context: func [
		/with word
		/extend proto [object!]
		/passive only? [logic!]
		/locals
			words ctx spec name id func? obj original body pos entry symbol
			body? ctx2 new blk list path on-set-info values w defer mark
	][
		either set-path? original: pc/-1 [
			path: original
		][
			name: to word! original: any [word original]
		]
		words: any [all [proto third proto] make block! 8] ;-- start from existing ctx or fresh
		list:  clear any [list []]
		values: make block! 8
		
		if proto [proto: reduce [proto]]
		
		either body?: block? pc/2 [
			parse body: pc/2 [							;-- collect words from body block
				some [
					(clear list)
					pos: set-word! (
						append list pos/1			;-- store new word
						value: pos
						until [
							value: next value
							any [tail? value not set-word? value/1]
						]
						value: value/1
						if all [not only? word? value][
							if find logic-words value [value: get value]
						]
						w: to word! pos/1
						either entry: find/skip values w 2 [ ;-- store first following value (CONSTRUCT)
							entry/2: value
						][
							repend values [w value]
						]
						func?: no
					)
					[func-constructors (func?: yes) | none] (
						foreach word list [
							either entry: find words word [
								if func? [entry/2: function!]
							][
								append words word
								append words either func? [function!][none]
							]
						]
					) | skip
				]
			]

			spec: make block! (length? words) / 2
			forskip words 2 [append spec to word! words/1]
		][
			unless extend [
				blk: redirect-to literals [
					blk: copy/part pc 2
					either empty? ctx-stack [
						emit-block blk
					][
						emit-block/bind blk last ctx-stack
					]
				]
				pos: tail output
				emit-open-frame 'do						;-- defer it to runtime evaluation
				emit reduce ['block/push blk]
				insert-lf -2
				emit-native 'do
				emit-close-frame

				pc: skip pc 2
				defer: copy pos
				clear pos
				return defer
			]
			obj:    find objects proto/1				;-- simple inheritance case
			spec:   next first obj/1
			words:  third obj/1
			
			unless find [context object object!] pc/1 [
				unless new: is-object? pc/2 [
					comp-call 'make select functions 'make ;-- fallback to runtime creation
					exit
				]
				
				ctx2: select objects new				;-- multiple inheritance case
				spec: union spec next first new
				insert proto new
				
				forskip words 2 [
					if word: in new words/1 [words/2: get in new words/1]
				]
				foreach [name value] third new [
					unless find words name [repend words [name value]]
				]
			]
		]

		redirect-to literals [							;-- store spec and body blocks
			ctx: add-context spec
			emit compose [
				(to set-word! ctx) _context/make (blk: emit-block spec) no yes	;-- build context
			]
			insert-lf -5
		]
		
		symbol: either path [ctx][
			if pos: find get-obj-base name name [pos/1: none] ;-- unbind word with previous object
			
			get pick [name ctx] to logic! any [			;-- ctx for object's word, else name
				rebol-gctx = obj: bind? original
				find shadow-funcs obj
			]
		]
		
		repend objects [								;-- register shadow object	
			symbol										;-- object access word
			obj: make object! words						;-- shadow object
			ctx											;-- object's context name
			id: get-counter								;-- unique object ID
			proto										;-- optional prototype object
			none										;-- [index locals] for on-word-set
		]
		on-set-info: back tail objects
		
		either path [
			do reduce [to set-path! join obj-stack to path! path obj] ;-- set object in shadow tree
		][
			unless tail? next obj-stack [				;-- set object in shadow tree (if sub-object)
				do reduce [to set-path! join obj-stack name obj]
			]
		]
		if body? [bind body obj]
		

		unless all [empty? locals-stack not iterator-pending?][	;-- in a function or iteration block
			emit compose [
				(to set-word! ctx) _context/make (blk) no yes	;-- rebuild context
			]
			insert-lf -5
		]

		if proto [
			if body? [inherit-functions obj last proto]
			emit reduce ['object/duplicate select objects last proto ctx]
			insert-lf -3
		]
		if all [not body? not passive][
			inherit-functions obj new
			emit reduce ['object/transfer ctx2 ctx]
			insert-lf -3
		]

		emit-src-comment/with none rejoin [mold pc/-1 " context " mold spec]

		emit-open-frame 'body
		case [
			passive [									;-- CONSTRUCT support
				bind values obj
				foreach [name value] values [
					emit-open-frame 'set
					emit-push-word name name
					comp-literal/with value
					
					emit-native/with 'set [-1]
					emit-close-frame
				]
				pc: skip pc 2
			]
			all [body? not empty? pc/2][
				append obj-stack any [path name]
				pc: next pc
				comp-next-block
				clear skip tail obj-stack either path [negate length? path][-1]
			]
			'else [
				pc: skip pc 2
			]
		]
		pos: none
		
		defer: reduce ['object/init-push ctx id]		;-- deferred emission
		new-line defer yes
		
		if any [path pos: find spec 'on-word-set*][
			if pos [
				pos: (index? pos) - 1					;-- 0-based contexts arrays
				entry: find functions decorate-obj-member 'on-word-set* ctx
				unless zero? locals: second check-spec entry/2/3 [
					locals: locals + 1					;-- account for /local
				]
				change/only on-set-info reduce [pos locals]	;-- cache values
				repend defer ['object/init-on-set ctx pos locals]
				new-line skip defer 3 yes
			]
		]
		emit 'stack/revert
		insert-lf -1
		
		defer
	]
	
	comp-object: :comp-context
	
	comp-construct: has [only? with? obj][
		only?: with?: no
		
		if all [
			path? pc/1
			not parse pc/1 [skip 2 ['only (only?: yes) | 'with (with?: yes)]] ;@@ handle duplicates
		][
			throw-error "Invalid CONSTRUCT refinement"
		]
		either with? [
			unless obj: is-object? pc/3 [--not-implemented--]
			also 
				comp-context/passive/extend only? obj
				pc: next pc
		][
			comp-context/passive only?
		]												;-- return object deferred block
	]
	
	comp-boolean-expressions: func [type [word!] test [block!] /local list body][
		list: back tail comp-chunked-block
		
		if empty? head list [
			emit set-last-none
			insert-lf -1
			exit
		]
		bind test 'body
		
		;-- most nested test first (identical for ANY and ALL)
		body: compose/deep [if logic/false? [(set-last-none)]]
		new-line body yes
		insert body list/1
		
		;-- emit expressions tree from leaf to root
		while [not head? list][
			list: back list
			
			insert/only body 'stack/reset
			new-line body yes
			
			body: reduce test
			new-line body yes
			
			insert body list/1
		]
		emit-open-frame type
		emit body
		emit-close-frame
	]
	
	comp-any: does [
		either block? pc/1 [
			comp-boolean-expressions 'any ['if 'logic/false? body]
		][
			emit-open-frame 'any
			comp-expression
			emit-native 'any
			emit-close-frame
		]
	]
	
	comp-all: does [
		either block? pc/1 [
			comp-boolean-expressions 'all [
				'either 'logic/false? set-last-none body
			]
		][
			emit-open-frame 'all
			comp-expression
			emit-native 'all
			emit-close-frame
		]
	]
		
	comp-if: does [
		emit-open-frame 'if
		comp-expression/close-path
		emit compose/deep [
			either logic/false? [(set-last-none)]
		]
		comp-sub-block 'if-body							;-- compile TRUE block
		emit-close-frame
	]
	
	comp-unless: does [
		emit-open-frame 'unless
		comp-expression/close-path
		emit [
			either logic/false?
		]
		comp-sub-block 'unless-body						;-- compile FALSE block
		append/only output set-last-none
		emit-close-frame
	]

	comp-either: does [
		emit-open-frame 'either
		comp-expression/close-path
		emit [
			either logic/true?
		]
		comp-sub-block 'either-true						;-- compile TRUE block
		comp-sub-block 'either-false					;-- compile FALSE block
		emit-close-frame
	]
	
	comp-loop: has [name set-name mark][
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		set [name set-name] declare-variable join "i" depth
		
		comp-expression/close-path						;@@ optimize case for literal counter
		
		emit compose [(set-name) integer/get*]
		insert-lf -2
		emit compose/deep [
			either (name) <= 0 [(set-last-none)]
		]
		mark: tail output
		emit [
			until
		]
		new-line skip tail output -3 off
		
		push-call 'loop
		comp-sub-block 'loop-body						;-- compile body
		pop-call
		
		repend last output [
			set-name name '- 1
			name '= 0
		]
		new-line skip tail last output -3 on
		new-line skip tail last output -7 on
		depth: depth - 1
		
		convert-to-block mark
	]
	
	comp-until: does [
		emit [
			until
		]
		push-call 'until
		comp-sub-block 'until-body						;-- compile body
		pop-call
		append/only last output 'logic/true?
		new-line back tail last output on
	]
	
	comp-while: does [
		emit [
			while
		]
		push-call 'while
		comp-sub-block 'while-condition					;-- compile condition
		append/only last output 'logic/true?
		new-line back tail last output on
		comp-sub-block 'while-body						;-- compile body
		pop-call
	]
	
	comp-repeat: has [name word cnt set-cnt lim set-lim action][
		add-symbol word: pc/1
		add-global word
		name: decorate-symbol word
		action: either local-word? word [
			'natives/repeat-set							;-- set the value slot on stack
		][
			'_context/set-integer						;-- set the word value in global context
		]
		
		depth: depth + 1
		if depth > max-depth [max-depth: depth]

		emit-stack-reset
		
		pc: next pc
		comp-expression/close-path						;-- compile 2nd argument
		
		set [cnt set-cnt] declare-variable join "r" depth		;-- integer counter
		set [lim set-lim] declare-variable join "rlim" depth	;-- counter limit
		emit reduce either local-word? word [					;@@ only integer! argument supported
			[
				set-lim 'natives/repeat-init* name
				set-cnt 0
			]
		][
			[
				set-lim 'integer/get*
				'_context/set-integer name lim
				set-cnt 0
			]
		]
		insert-lf -2
		insert-lf -5
		insert-lf -7
		emit-stack-reset
		
		emit-open-frame 'repeat
		emit compose/deep [
			while [
				;-- set word 1 + get word
				;-- TBD: set word next get word
				(set-cnt) (cnt) + 1
				;-- (get word) < value
				;-- TBD: not tail? get word
				(cnt) <= (lim)
			]
		]
		new-line last output on
		new-line skip tail last output -3 on
		new-line skip tail last output -6 on
		
		push-call 'repeat
		comp-sub-block 'repeat-body
		pop-call
		insert last output reduce [action name cnt]
		new-line last output on
		emit-close-frame
		depth: depth - 1
	]
		
	comp-foreach: has [word blk name cond ctx][
		either block? pc/1 [
			;TBD: raise error if not a block of words only
			foreach word blk: pc/1 [
				add-symbol word
				add-global word
			]
			name: redirect-to literals [
				either ctx: find-contexts to word! blk/1 [
					emit-block/bind blk ctx
				][
					emit-block blk
				]
			]
		][
			add-symbol word: pc/1
			add-global word
		]
		pc: next pc
		
		comp-expression/close-path						;-- compile series argument
		;TBD: check if result is any-series!
		emit 'stack/keep
		insert-lf -1
		
		either blk [
			cond: compose [natives/foreach-next-block (length? blk)]
			emit compose [block/push (name)]			;-- block argument
		][
			cond: compose [natives/foreach-next]
			emit-push-word word	word					;-- word argument
		]
		insert-lf -2
		
		emit-open-frame 'foreach
		emit compose/deep [
			while [(cond)]
		]
		push-call 'foreach
		comp-sub-block 'foreach-body					;-- compile body
		pop-call
		emit-close-frame
	]
	
	comp-forall: has [word name][
		;TBD: check if word argument refers to any-series!
		name: pc/1
		word: decorate-symbol name
		emit-get-word name name							;-- save series (for resetting on end)
		emit-push-word name name						;-- word argument
		pc: next pc
		
		emit-open-frame 'forall
		emit copy/deep [								;-- copy/deep required for R/S lines injection
			while [natives/forall-loop]
		]
		push-call 'forall
		comp-sub-block 'forall-body						;-- compile body
		pop-call
		
		append last output [							;-- inject at tail of body block
			natives/forall-next							;-- move series to next position
		]
		emit [
			natives/forall-end							;-- reset series
			stack/unwind
		]
	]
	
	comp-func-body: func [
		name [word!] spec [block!] body [block!] symbols [block!] locals-nb [integer!]
		/local init locals blk
	][
		push-locals copy symbols						;-- prepare compiled spec block
		forall symbols [symbols/1: decorate-symbol symbols/1]
		locals: append copy [/local ctx] symbols
		blk: either container-obj? [head insert copy locals [octx [node!]]][locals]
		emit reduce [to set-word! decorate-func/strict name 'func blk]
		insert-lf -3

		comp-sub-block/with 'func-body body				;-- compile function's body

		;-- Function's prolog --
		pop-locals
		init: make block! 4 * length? symbols
		
		append init compose [							;-- point context values series to stack
			ctx: TO_CTX(to paren! last ctx-stack)
			push ctx/values								;-- save previous context values pointer
			ctx/values: as node! stack/arguments
		]
		new-line skip tail init -4 on
		
		forall symbols [								;-- assign local variable to Red arguments
			append init to set-word! symbols/1
			new-line back tail init on
			either head? symbols [
				append/only init 'stack/arguments
			][
				repend init [symbols/-1 '+ 1]
			]
		]
		unless zero? locals-nb [						;-- init local words on stack
			append init compose [
				_function/init-locals (1 + locals-nb)
			]
		]
		name: decorate-symbol name
		if find symbols name [name: decorate-exec-ctx name]
		
		append init compose [							;-- body stack frame
			stack/mark-native (name)	;@@ make a unique name for function's body frame
		]
		
		;-- Function's epilog --
		append last output compose [
			stack/unwind-last							;-- closing body stack frame, and propagating last value
			ctx/values: as node! pop					;-- restore context values pointer
		]
		new-line skip tail last output -4 yes
		
		insert last output init
	]
	
	collect-words: func [spec [block!] body [block!] /local pos end ignore words word rule][
		if pos: find spec /extern [
			either end: find next pos refinement! [
				ignore: copy/part next pos end
				remove/part spec pos end
			][
				ignore: copy next pos
				clear pos
			]
			unless empty? intersect ignore spec [
				pc: skip pc -2
				throw-error ["duplicate word definition in function:" pc/1]
			]
		]
		foreach item spec [								;-- add all arguments to ignore list
			if find [word! lit-word! get-word!] type?/word item [
				unless ignore [ignore: make block! 1]
				append ignore to word! :item
			]
		]
		words: make block! 1
		
		make-local: [
			unless any [
				all [ignore	find ignore word]
				find words word
			][
				append words word
			]
		]
		parse body rule: [
			any [
				pos: set-word! (
					word: to word! pos/1
					do make-local
				)
				| pos: word! (
					if all [
						find word-iterators pos/1
						pos/2
					][
						foreach word any [
							all [block? pos/2 pos/2]
							reduce [pos/2]
						] make-local
					]
				)
				| path! | lit-path! | set-path!
				| into rule
				| skip
			]
		]
		unless empty? words [
			unless find spec /local [append spec /local]
			append spec words
		]
	]
	
	comp-func: func [
		/collect /does /has
		/local
			name word spec body symbols locals-nb spec-blk body-blk ctx
			src-name original global? path obj shadow defer
	][
		original: pc/-1
		case [
			set-path? original [
				path: original
				either obj: object-access? path [
					do reduce [join to set-path! get-obj-base-word path/1 path 'function!] ;-- update shadow object info
					obj: find objects obj
					name: to word! rejoin [any [obj/-1 obj/2] #"~" last path] 
					add-symbol name
				][
					name: generate-anon-name			;-- undetermined function assignment case
				]
			]
			find [set-word! lit-word!] type?/word :original [
				src-name: to word! original
				unless global?: all [lit-word? :original pc/-2 = 'set][
					src-name: get-prefix-func src-name
				]
				name: check-func-name src-name
				add-symbol word: to word! clean-lf-flag name
				unless any [
					local-word? name
					1 < length? obj-stack
				][
					add-global word
				]
			]
			'else [name: generate-anon-name]			;-- unassigned function case
		]
		
		pc: next pc
		set [spec body] pc
		case [
			collect [collect-words spec body]
			does	[body: spec spec: make block! 1 pc: back pc]
			has		[spec: head insert copy spec /local]
		]
		set [symbols locals-nb] check-spec spec
		add-function name spec
		
		redirect-to literals [							;-- store spec and body blocks
			push-locals symbols
			spec-blk: emit-block spec
			ctx: push-context copy symbols
			emit compose [
				(to set-word! ctx) _context/make (spec-blk) yes no	;-- build context with value on stack
			]
			insert-lf -4
			body-blk: either job/red-store-bodies? [emit-block/bind body ctx]['null]
			pop-locals
		]
		repend shadow-funcs [							;-- register a new shadow context
			decorate-func/strict name
			shadow: to-context-spec symbols
			ctx
		]
		bind-function body shadow

		defer: reduce [
			'_function/push spec-blk body-blk ctx
			'as 'integer! to get-word! decorate-func/strict name
			either 1 < length? obj-stack [select objects do obj-stack]['null]
		]
		new-line defer yes
		new-line skip tail defer -4 no
		repend bodies [									;-- save context for deferred function compilation
			name spec body symbols locals-nb 
			copy locals-stack copy ssa-names copy ctx-stack
			all [not global? 1 < length? obj-stack next first do obj-stack] ;-- save optional wrapping object
		]
		pop-context
		pc: skip pc 2
		defer
	]
	
	comp-function: does [
		comp-func/collect
	]
	
	comp-does: does [
		comp-func/does
	]
	
	comp-has: does [
		comp-func/has
	]
	
	comp-routine: has [name word spec spec* body spec-blk body-blk original][
		name: check-func-name to word! original: pc/-1
		add-symbol word: to word! clean-lf-flag name
		add-global word
		
		pc: next pc
		set [spec body] pc

		preprocess-strings body							;-- encode strings for Red/System
		check-spec spec
		add-function/type name spec 'routine!
		
		process-calls body								;-- process #call directives
		
		clear find spec*: copy spec /local
		spec-blk: redirect-to literals [emit-block spec*]
		body-blk: either job/red-store-bodies? [
			redirect-to literals [emit-block body]
		][
			'null
		]
		convert-types spec
		either no-global? [
			repend bodies [								;-- saved for deferred inclusion
				name spec body none none none none none none
			]
		][
			emit reduce [to set-word! name 'func]
			insert-lf -2
			append/only output spec
			append/only output body
		]
		
		pc: skip pc 2
		compose [
			routine/push (spec-blk) (body-blk) as integer! (to get-word! name)
		]
	]
	
	comp-exit: does [
		pc: next pc
		emit [
			copy-cell unset-value stack/arguments
		]
		emit-exit-function
	]

	comp-return: does [
		comp-expression
		emit-exit-function
	]
	
	comp-self: func [original [any-word!] /local obj][
		either rebol-gctx = obj: bind? original [
			pc: back pc									;-- backtrack and process word again
			comp-word/thru
		][
			obj: find objects obj
			either obj/5 [
				emit reduce ['object/push obj/2 obj/3 obj/5/1 obj/5/2] ;-- on-set present case
				insert-lf -5
			][
				emit reduce ['object/init-push obj/2 obj/3]
				insert-lf -3
			]
		]
	]
	
	comp-switch: has [mark name arg body list cnt pos default? value][
		if path? pc/-1 [
			foreach ref next pc/-1 [
				switch/default ref [
					default [default?: yes]
					;all []
				][throw-error ["SWITCH has no refinement called" ref]]
			]
		]
		push-call 'switch
		emit-open-frame 'switch
		mark: tail output								;-- pre-compile the SWITCH argument
		comp-expression/close-path
		arg: copy mark
		clear mark
		
		body: pc/1
		unless block? body [
			throw-error "SWITCH expects a block as second argument"
		]
		list: make block! 4
		cnt: 1
		parse body [									;-- build a [value index] pairs list
			any [
				value: skip (repend list [value/1 cnt])
				to block! skip (cnt: cnt + 1)
			]
		]
		name: redirect-to literals [emit-block list]
		
		emit-open-frame 'select							;-- SWITCH lookup frame
		emit compose [block/push (name)]
		insert-lf -2
		emit arg
		emit [integer/push 2]							;-- /skip 2
		insert-lf -2
		emit-action/with 'select [-1 0 -1 -1 -1 2 -1 -1] ;-- select/only/skip
		emit-close-frame
		
		emit [switch integer/get-any*]
		insert-lf -2
		
		clear list
		cnt: 1
		parse body [									;-- build SWITCH cases
			any [skip to block! pos: (
				mark: tail output
				comp-sub-block/with 'switch-body pos/1
				pc: back pc			;-- restore PC position (no block consumed)
				repend list [cnt mark/1]
				clear mark
				cnt: cnt + 1
			) skip]
		]
		unless empty? body [pc: next pc]
		
		append list 'default							;-- process default case
		either default? [
			comp-sub-block 'switch-default				;-- compile default block
			append/only list last output
			clear back tail output
		][
			append/only list copy [0]					;-- placeholder for keeping R/S compiler happy
		]
		append/only output list
		emit-close-frame
		pop-call
	]
	
	comp-case: has [all? path saved list mark body chunk][
		if path? path: pc/-1 [
			either path/2 = 'all [all?: yes][
				throw-error ["CASE has no refinement called" path/2]
			]
		]
		unless block? pc/1 [
			throw-error "CASE expects a block as argument"
		]
		
		saved: pc
		pc: pc/1
		list: make block! length? pc
		push-call 'case
		
		while [not tail? pc][							;-- precompile all conditions and cases
			mark: tail output
			comp-expression/close-path					;-- process condition
			append/only list copy mark
			clear mark
			case [
				tail? pc [
					throw-error "CASE is missing a value"
				]
				block? pc/1 [
					append/only list comp-sub-block 'case	;-- process case block
					clear back tail output
				]
				'else [
					chunk: tail output
					comp-expression/no-infix/root
					all [								;-- fixes #512
						not empty? chunk
						chunk/1 <> 'stack/reset
						insert/only chunk 'stack/reset
					]
					append/only list copy chunk
					clear chunk
				]
			]
		]
		pc: next saved
		
		either all? [
			foreach [test body] list [					;-- /all mode
				emit-open-frame 'case
				emit test
				emit compose/deep [
					either logic/false? [(set-last-none)]
				]
				append/only output body
				emit-close-frame
			]
		][												;-- default single selection mode
			list: skip tail list -2
			body: reduce ['either 'logic/true? list/2 set-last-none]
			new-line body yes
			insert body list/1
			
			;-- emit expressions tree from leaf to root
			while [not head? list][
				list: skip list -2
				
				insert/only body 'stack/reset
				new-line body yes
				
				body: reduce ['either 'logic/true? list/2 body]
				new-line body yes
				insert body list/1
			]
			
			emit-open-frame 'case
			emit body
			emit-close-frame
		]
		pop-call
	]
	
	comp-reduce: has [list into?][
		push-call 'reduce
		
		into?: path? pc/-1
		unless block? pc/1 [
			emit-open-frame 'reduce
			comp-expression							;-- compile not-literal-block argument
			if into? [comp-expression]				;-- optionally compile /into argument
			emit-native/with 'reduce reduce [pick [1 -1] into?]
			emit-close-frame
			pop-call
			exit
		]
		
		list: either empty? pc/1 [
			pc: next pc								;-- pass the empty source block
			make block! 1
		][
			comp-chunked-block						;-- compile literal block
		]
		
		either path? pc/-2 [						;-- -2 => account for block argument
			comp-expression							;-- compile /into argument
		][
			emit 'block/push-only*					;-- create a fresh new block on stack only
			emit max 1 length? list
			insert-lf -2
		]
		emit-open-frame 'reduce
		foreach chunk list [
			emit chunk
			either into? [
				emit 'block/insert-thru
				insert-lf -1
			][
				emit 'block/append-thru
				insert-lf -1
			]
			emit-stack-reset
		]
		emit-close-frame
		pop-call
	]
	
	comp-set: has [name][
		either lit-word? pc/1 [
			name: to word! pc/1
			either local-bound? pc/1 [
				pc: next pc
				comp-local-set name
			][
				comp-set-word/native
			]
		][
			if block? pc/1 [						;-- if words are literals, register them
				foreach w pc/1 [
					add-symbol w: to word! w
					unless local-word? w [
						add-global w				;-- register it as global
					]
				]
			]
			emit-open-frame 'set
			comp-expression
			comp-expression
			emit-native/with 'set [-1]
			emit-close-frame
		]
	]
	
	comp-get: has [symbol original][
		either lit-word? original: pc/1 [
			add-symbol symbol: to word! original
			either path? pc/-1 [						;@@ add check for validaty of refinements		
				emit-get-word/any? symbol original
			][
				emit-get-word symbol original
			]
			pc: next pc
		][
			emit-open-frame 'get
			comp-expression
			emit-native/with 'get [-1]
			emit-close-frame
		]
	]
	
	comp-path: func [
		root? [logic!]
		/set?
		/local 
			path value emit? get? entry alter saved after dynamic? ctx mark obj?
			fpath symbol obj self? true-blk defer
	][
		path:  copy pc/1
		emit?: yes
		set?:  to logic! set?
		
		if dynamic?: find path paren! [					;-- fallback to interpreter if parens found
			emit-open-frame 'body
			if set? [
				saved: pc
				pc: next pc
				comp-expression
				after: pc
				pc: saved
			]
			comp-literal
			pc: back pc
			
			unless set? [emit [stack/mark-native words/_body]]	;@@ not clean...
			emit compose [
				interpreter/eval-path stack/top - 1 null null (to word! form set?) no (to word! form root?)
			]
			unless set? [emit [stack/unwind-last]]
			
			emit-close-frame
			pc: either set? [after][next pc]
			exit
		]
		
		if all [not set? defer: dispatch-ctx-keywords/with pc/1/1 path/1][
			if block? defer [emit defer]
			exit
		]
		
		forall path [									;-- preprocessing path
			switch/default type?/word value: path/1 [
				word! [
					if all [not set? not get? entry: find functions value][
						if alter: select-ssa value [
							entry: find functions alter
						]
						if head? path [
							pc: next pc
							comp-call path entry/2		;-- call function with refinements
							exit
						]
					]
				]
				get-word! [
					if head? path [
						get?: yes
						change path to word! path/1
					]
				]
				integer! paren! string!	[
					if head? path [path-head-error]
				]
			][
				throw-error ["cannot use" mold type? value "value in path:" pc/1]
			]
		]
		self?: path/1 = 'self

		if all [
			not any [set? dynamic? find path integer!]
			set [fpath symbol ctx] obj-func-path? path
		][
			either get? [
				check-new-func-name path symbol ctx
			][
				pc: next pc
				comp-call/with fpath functions/:symbol symbol ctx
				exit
			]
		]
		
		obj?: all [
			not any [dynamic? find path integer!]
			obj: object-access? path
		]
		
		if set? [
			pc: next pc
			either obj? [									;-- fetch assigned value earlier
				unless defer: dispatch-ctx-keywords none [	;-- detect function/object declaration
					comp-expression
				]
			][
				defer: dispatch-ctx-keywords none
			]
			if block? defer [emit defer]
		]

		if obj? [
			ctx: second obj: find objects obj
			
			true-blk: compose/deep pick [
				[[word/set-in    (ctx) (get-word-index/with last path ctx)]]
				[[word/get-local (ctx) (get-word-index/with last path ctx)]]
			] set?
			
			either self? [
				emit first true-blk
			][
				emit compose [
					either (emit-deep-check path) (true-blk)
				]
			]
			if all [set? obj/5][						;-- detect on-set callback 
				insert last output reduce [				;-- save old value
					'word/get-local ctx get-word-index/with last path ctx
				]
				repend last output [
					'object/fire-on-set*
						decorate-symbol first back back tail path
						decorate-symbol last path
				]
				foreach pos [-9 -6 -3][new-line skip tail last output pos yes]
			]
		]
		mark: tail output
		
		either any [obj? set? get? dynamic? not parse path [some word!]][
			unless self? [
				obj?: to logic! obj?
				emit-path back tail path set? obj?		;-- emit code recursively from tail
			]
		][
			append/only paths-stack path				;-- defer path generation
		]
		
		if obj? [change/only/part mark copy mark tail output]
		unless set? [pc: next pc]
	]
	
	comp-arguments: func [spec [block!] nb [integer!] /ref name [refinement!] /local word paths type][
		if ref [spec: find/tail spec name]
		paths: length? paths-stack
		
		repeat i nb [
			while [not any-word? spec/1][				;-- skip attributs and docstrings
				spec: next spec
			]
			switch type?/word spec/1 [
				lit-word! [
					either all [
						tail? pc
						all [spec/2 find spec/2 'any-type!]
					][
						emit 'unset/push				;-- provide unset as placeholder
						insert-lf -1
					][
						type: either all [path? pc/1 get-word? pc/1/1][
							'get-path!
						][type?/word pc/1]
						switch/default type [
							get-word! [
								add-symbol to word! pc/1
								comp-expression
							]
							lit-word! [
								add-symbol word: to word! pc/1
								emit 'lit-word/push
								emit decorate-symbol word
								insert-lf -2
								pc: next pc
							]
							word! [
								add-symbol word: to word! pc/1
								emit-push-word word	word	;@@ add specific type checking
								pc: next pc
							]
							lit-path! [comp-literal/inactive]
							paren! get-path! [comp-expression]
						][
							comp-literal
						]
					]
				]
				get-word! [comp-literal/inactive]
				word!     [comp-expression]
			]
			if paths < length? paths-stack [
				if 'stack/unwind = last output [i: i + 1] ;-- count nested argument with path
				repeat n nb - i + 1 [
					emit [stack/push pos +]
					emit n - 1
					insert-lf -4
				]
				return true								;-- stop compiling new arguments
			]
			spec: next spec
		]
		false
	]
		
	comp-call: func [
		call [word! path!]
		spec [block!]
		/with symbol ctx-name [word!]
		/local 
			item name compact? refs ref? cnt pos ctx mark list offset emit-no-ref
			args option stop?
	][
		either spec/1 = 'intrinsic! [
			switch any [all [path? call call/1] call] keywords
		][
			compact?: spec/1 <> 'function!				;-- do not push refinements on stack
			refs: make block! 1							;-- refinements storage in compact mode
			cnt: 0
			
			name: either path? call [call/1][call]
			name: to word! clean-lf-flag name
			either all [with not empty? locals-stack][	;-- only if in a function's body
				emit reduce [							;-- special case for path-generated wrapper functions
					'stack/mark-func 
					decorate-exec-ctx decorate-symbol name
				]
				insert-lf -2
			][
				emit-open-frame name
			]
			comp-arguments spec/3 spec/2				;-- fetch arguments
			
			either compact? [
				refs: either spec/4 [
					head insert/dup make block! 8 -1 (length? spec/4) / 3	;-- init with -1
				][
					[]									;-- function with no refinements
				]
				if path? call [
					cnt: spec/2							;-- function base arity
					foreach ref next call [
						ref: to refinement! ref
						unless pos: find/skip spec/4 ref 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						poke refs pos/2 cnt				;-- set refinement's arguments base offset
						unless stop? [
							stop?: comp-arguments/ref spec/3 pos/3 ref ;-- fetch refinement arguments
						]
						cnt: cnt + pos/3				;-- increase by nb of arguments
					]
				]
			][											;-- prepare function! stack layout
				emit-no-ref: [							;-- populate stack for unused refinement
					emit [logic/push false]				;-- unused refinement is set to FALSE
					insert-lf -2
					loop args [
						emit 'none/push					;-- unused arguments are set to NONE
						insert-lf -1
					]
				]
				either path? call [						;-- call with refinements?
					ctx: copy spec/4					;-- get a new context block
					foreach ref next call [
						option: to refinement! either integer? ref [form ref][ref]
						
						unless pos: find/skip spec/4 option 3 [
							throw-error [call/1 "has no refinement called" ref]
						]
						offset: 2 + index? pos
						poke ctx index? pos true		;-- switch refinement to true in context
						unless zero? args: pos/3 [		;-- process refinement's arguments
							list: make block! 1
							ctx/:offset: list 			;-- compiled refinement arguments storage
							mark: tail output
							unless stop? [
								stop?: comp-arguments/ref spec/3 args option
							]
							append/only list copy mark
							clear mark
						]
					]
					forall ctx [						;-- push context values on stack
						switch type?/word ctx/1 [
							refinement! [				;-- unused refinement
								args: ctx/3
								do emit-no-ref
							]
							logic! [					;-- used refinement
								emit [logic/push true]
								insert-lf -2
								if block? ctx/3 [
									foreach code ctx/3 [emit code] ;-- emit pre-compiled arguments
								]
							]
						]
					]
				][										;-- call with no refinements
					if spec/4 [
						foreach [ref offset args] spec/4 emit-no-ref
					]
				]
			]
			
			switch spec/1 [
				native! 	[emit-native/with name refs]
				action! 	[emit-action/with name refs]
				op!			[]
				routine!	[emit-routine any [symbol name] spec/3]
				function! 	[
					emit decorate-func any [symbol name]
					insert-lf either with [emit ctx-name -2][-1]
				]
				
			]
			emit-close-frame
		]
	]
	
	comp-local-set: func [name [word!]][
		emit-open-frame 'set
		comp-expression
		emit [copy-cell stack/arguments]
		emit decorate-symbol name
		insert-lf -3
		emit-close-frame
	]
	
	comp-set-word: func [
		/native
		/local 
			name value ctx original obj bound? deep? inherit? proto
			defer mark start take-frame
	][
		name: original: pc/1
		pc: next pc
		unless local-word? name: to word! clean-lf-flag name [
			add-symbol name
			add-global name
		]
		
		if infix? pc [
			throw-error "invalid use of set-word as operand"
		]
		if all [not booting? find intrinsics name][
			throw-error ["attempt to redefine a keyword:" name]
		]
		
		bound?: all [
			rebol-gctx <> obj: bind? original
			not find shadow-funcs obj
		]
		deep?: 1 < length? obj-stack
		mark: tail output
		take-frame: [start: copy mark clear mark]
		
		emit-open-frame 'set
		
		either native [									;-- 1st argument
			pc: back pc
			comp-expression								;-- fetch a value
		][
			unless any [bound? deep?][
				emit-push-word name	original 			;-- push set-word
			]
		]
		
		push-call 'set
		case [
			all [
				pc/1 = 'make
				any [pc/2 = 'object! proto: is-object? pc/2]
			][
				do take-frame
				check-redefined name
				pc: next pc
				defer: either proto [
					comp-context/with/extend original proto
				][
					comp-context/with original
				]
			]
			all [
				any [word? pc/1 path? pc/1]
				do take-frame
				defer: dispatch-ctx-keywords/with original pc/1
			][]											;-- processing done in dispatch function
			'else [
				if start [emit start]
				unless bound? [check-redefined name]
				check-cloned-function name
				comp-substitute-expression				;-- fetch a value (2nd argument)
			]
		]
		pop-call
		
		if block? defer [								;-- object or function case
			emit start
			emit defer
		]

		either native [
			emit-native/with 'set [-1]					;@@ refinement not handled yet
		][
			either all [bound? ctx: select objects obj][
				emit 'word/set-in
				emit either parent-object? obj ['octx][ctx] ;-- optional parametrized context reference (octx)
				emit get-word-index/with name ctx
				insert-lf -3
			][
				emit 'word/set
				insert-lf -1
			]
		]
		emit-close-frame
	]

	comp-word: func [/literal /final /thru /local name local? alter emit-word original new ctx defer][
		name: to word! original: pc/1
		local?: local-bound? original
		
		emit-word: [
			either lit-word? original [					;@@
				emit-push-word name original
			][
				either literal [
					emit-get-word/literal name original
				][
					emit-get-word name original
				]
			]
		]
		
		if defer: dispatch-ctx-keywords original [
			if block? defer [emit defer]
			exit
		]
		pc: next pc										;@@ move it deeper
		
		case [
			all [not thru name = 'exit]	 [comp-exit]
			all [not thru name = 'return][comp-return]
			all [not thru name = 'self]  [comp-self original]
			all [
				not final
				not local?
				name = 'make
				any-function? pc/1
			][
				fetch-functions skip pc -2				;-- extract functions definitions
				pc: back pc
				comp-word/final
			]
			all [
				not literal
				not local?
				all [
					alter: get-prefix-func original
					entry: find functions alter
					name: alter
				]
			][
				if alter: select-ssa name [entry: find functions alter]
				check-invalid-call name
				
				either ctx: any [
					obj-func-call? original
					pick entry/2 5
				][
					comp-call/with name entry/2 name ctx
				][
					comp-call name entry/2
				]
			]
			any [
				find globals name
				find-contexts name
			][
				do emit-word
			]
			'else [
				either job/red-strict-check? [
					pc: back pc
					throw-error ["undefined word" pc/1]
				][
					do emit-word
				]
			]
		]
	]
	
	search-expr-end: func [pos [block! paren!]][
		if infix? next pos [pos: search-expr-end skip pos 2]
		pos
	]
	
	make-func-prefix: func [name [word!]][
		load rejoin [									;@@ cache results locally
			head remove back tail form functions/:name/1 "s/"
			name #"*"
		]
	]
	
	check-infix-operators: func [
		root? [logic!]
		/local name op pos end ops spec substitute cnt paths single?
	][
		if infix? pc [return false]						;-- infix op already processed,
														;-- or used in prefix mode.
		if infix? next pc [
			substitute: [
				if paths < length? paths-stack [
					emit [stack/push pos +]
					emit cnt
					insert-lf -4
					cnt: cnt + 1
				]
			]
			cnt: 0
			pos: pc
			end: search-expr-end pos					;-- recursive search of expression end
			
			ops: make block! 1
			pos: end									;-- start from end of expression
			until [
				op: pos/-1			
				name: any [select op-actions op op]
				insert ops name							;-- remember ops in left-to-right order
				emit-open-frame name
				pos: skip pos -2						;-- process next previous op
				pos = pc								;-- until we reach the beginning of expression
			]
			paths: length? paths-stack
			comp-expression/no-infix					;-- fetch first left operand
			do substitute
			pc: next pc

			forall ops [
				paths: length? paths-stack
				single?: path? pc/1
				comp-expression/no-infix					;-- fetch right operand
				if single? [do substitute]
				
				name: ops/1
				spec: functions/:name
				switch/default spec/1 [
					function! [emit decorate-func name insert-lf -1]
					routine!  [emit-routine name spec/3]
				][
					emit make-func-prefix name
					insert-lf -1
				]
				
				emit-close-frame
				unless tail? next ops [pc: next pc]		;-- jump over op word unless last operand
			]
			return true									;-- infix expression processed
		]
		false											;-- not an infix expression
	]
	
	process-call-directive: func [body [block!] global? /local name spec cmd types type arg][
		name: to word! clean-lf-flag body/1
		if any [
			not spec: select functions name
			not spec/1 = 'function!
		][
			throw-error ["invalid #call function name:" name]
		]
		either global? [
			emit 'red/stack/mark-func
			emit decorate-exec-ctx decorate-symbol name
			insert-lf -2
		][
			emit-open-frame name
		]
		
		types: spec/3
		body: next body
		
		loop spec/2 [									;-- process arguments
			types: find/tail types word!
			unless block? types/1 [
				throw-error ["type undefined for" types/1 "in function" name]
			]
			either 1 = length? types/1 [
				type: types/1/1
			][
				arg: body/1
				if word? arg [arg: get arg]
				type: none
				foreach value types/1 [
					if value = type?/word arg [type: value break]
				]
				unless type [
					throw-error ["cannot determine #call argument type:" arg]
				]
			]
			cmd: to path! reduce [to word! form get type 'push]
			if global? [insert cmd 'red]
			emit cmd
			insert-lf -1
			case [
				none? body/1 [
					throw-error ["missing argument(s) in #call body"]
				]
				body/1 = 'as [
					emit copy/part body 3
					body: skip body 3
				]
				body/1 = 'none [
					body: next body
				]
				'else [
					emit body/1
					body: next body
				]
			]
		]
		
		types: next types								;-- process refinements
		while [not tail? types][
			switch type?/word types/1 [
				refinement! [
					if types/1 = /local [break]
					emit [red/logic/push false]
					insert-lf -2
				]
				word! [
					emit 'red/none/push
					insert-lf -1
				]
				set-word! [break]
			]
			types: next types
		]
		
		name: decorate-func name						;-- function call
		if global? [name: decorate-exec-ctx name]
		emit name
		insert-lf -1
		
		either global? [
			emit 'red/stack/unwind-last
			insert-lf -1
			emit 'red/stack/reset
		][
			emit-close-frame
			emit 'stack/reset
		]
		insert-lf -1
	]

	comp-directive: has [file saved version mark][
		switch pc/1 [
			#include [
				unless file? file: pc/2 [
					throw-error ["#include requires a file argument:" pc/2]
				]
				append include-stk script-path
				
				script-path: either all [not booting? relative-path? file][
					file: clean-path join any [script-path main-path] file
					first split-path file
				][
					none
				]
				unless any [booting? exists? file][
					throw-error ["include file not found:" pc/2]
				]
				either find included-list file [
					script-path: take/last include-stk
					remove/part pc 2
				][
					saved: script-name
					insert skip pc 2 #pop-path
					change/part pc load-source file 2
					script-name: saved
					append included-list file
				]
				true
			]
			#pop-path [
				script-path: take/last include-stk
				pc: next pc
			]
			#system [
				unless block? pc/2 [
					throw-error "#system requires a block argument"
				]
				process-include-paths pc/2
				process-calls pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				mark: tail output
				emit pc/2
				new-line mark on
				pc: skip pc 2
				true
			]
			#system-global [
				unless block? pc/2 [
					throw-error "#system-global requires a block argument"
				]
				process-include-paths pc/2
				preprocess-strings pc/2					;-- encode strings for Red/System
				unless sys-global/1 = 'Red/System [
					append sys-global copy/deep [Red/System []]
				]
				append sys-global pc/2
				pc: skip pc 2
				true
			]
			#get-definition [							;-- temporary directive
				either value: select extracts/definitions pc/2 [
					change/only/part pc value 2
					comp-expression						;-- continue expression fetching
				][
					pc: next pc
				]
				true
			]
			#load [										;-- temporary directive
				change/part/only pc to do pc/2 pc/3 3
				comp-expression							;-- continue expression fetching
				true
			]
			#version [
				change pc rejoin [load-cache %version.r ", " now]
				comp-expression
				true
			]
		]
	]
	
	comp-substitute-expression: has [paths mark][
		paths: length? paths-stack
		mark: tail output
		
		comp-expression
		
		if all [
			paths < length? paths-stack
			not find mark [stack/push pos]
		][
			emit [stack/push pos + 0]
			insert-lf -4
		]
		mark: none
	]
	
	comp-expression: func [/no-infix /root /close-path /local out paths][
		root: to logic! root 
		if any [root close-path][out: tail output]
		paths: length? paths-stack
		
		unless no-infix [
			if check-infix-operators root [
				if all [any [root close-path] paths < length? paths-stack][
					emit-dynamic-path out
					push-call <infix>
					loop length? paths-stack [
						emit-dynamic-path make block! 0
					]
					pop-call
					if tail? pc [emit-dyn-check]
				]
				exit
			]

		]
		if tail? pc [
			pc: back pc
			throw-error "missing argument"
		]
		
		switch/default type?/word pc/1 [
			issue!		[
				either any [
					unicode-char?  pc/1
					float-special? pc/1
				][
					comp-literal						;-- special encoding for Unicode char!
				][
					unless comp-directive [comp-literal]
				]
			]
			;-- active datatypes with specific literal form
			set-word!	[comp-set-word]
			word!		[comp-word]
			get-word!	[comp-word/literal]
			paren!		[comp-next-block]
			set-path!	[comp-path/set? root]
			path! 		[comp-path root]
		][
			comp-literal
		]
		if root [
			either tail? pc	[
				unless find/only [stack/reset stack/unwind] last output [
					emit-dyn-check
				]
			][
				emit-stack-reset						;-- clear stack from last root expression result
			]
		]
		if any [root close-path][
			if paths < length? paths-stack [
				emit-dynamic-path out
				if tail? pc [emit-dyn-check]
			]
		]
	]
	
	comp-next-block: func [/with blk /local saved][
		saved: pc
		pc: any [blk pc/1]
		comp-block
		pc: next saved
	]
	
	comp-chunked-block: has [list mark saved][
		list: make block! 10
		saved: pc
		pc: pc/1										;-- dive in nested code
		mark: tail output
		
		comp-block/with [
			mold mark									;-- black magic, fixes #509, R2 internal memory corruption
			append/only list copy mark
			clear mark
		]
		
		pc: next saved
		list
	]
	
	comp-sub-block: func [origin [word!] /with body /local mark saved][
		unless any [with block? pc/1][
			throw-error [
				"expected a block for" uppercase form origin
				"instead of" mold type? pc/1 "value"
			]
		]
		
		mark: tail output
		saved: pc
		pc: any [body pc/1]								;-- dive in nested code
		comp-block
		pc: next saved									;-- step over block in source code				

		convert-to-block mark
		head insert last output [
			stack/reset
		]
	]
	
	comp-block: func [
		/with body [block!]
		/no-root
		/local expr size
	][
		if tail? pc [
			emit 'unset/push
			insert-lf -1
			exit
		]
		while [not tail? pc][
			expr: pc
			either no-root [comp-expression][comp-expression/root]
			
			if all [verbose > 3 positive? size: offset? expr pc][probe copy/part expr size]
			if verbose > 0 [emit-src-comment expr]
			
			if with [do body]
		]
	]
	
	comp-bodies: does [
		obj-stack: to path! 'func-objs
		
		foreach [name spec body symbols locals-nb stack ssa ctx obj?] bodies [
			either none? symbols [						;-- routine in no-global? mode
				emit reduce [to set-word! name 'func]
				insert-lf -2
				append/only output spec
				append/only output body
			][
				locals-stack: stack
				ssa-names: ssa
				ctx-stack: ctx
				container-obj?: obj?
				func-objs: tail objects
				depth: max-depth

				comp-func-body name spec body symbols locals-nb
			]
		]
		clear locals-stack
		clear ssa-names
		func-objs: none
	]
	
	comp-init: does [
		add-symbol 'datatype!
		add-global 'datatype!
		foreach [name specs] functions [
			add-symbol name
			add-global name
		]

		;-- Create datatype! datatype and word
		emit compose [
			stack/mark-native ~set
			word/push (decorate-symbol 'datatype!)
			datatype/push TYPE_DATATYPE
			word/set
			stack/unwind
			stack/reset
		]
	]
	
	comp-source: func [code [block!] /local user main][
		output: make block! 10000
		comp-init
		
		pc: load-source/hidden %boot.red				;-- compile Red's boot script
		unless job/red-help? [clear-docstrings pc]
		booting?: yes
		comp-block
		make-keywords									;-- register intrinsics functions
		booting?: no
		
		pc: code										;-- compile user code
		user: tail output
		comp-block
		
		main: output
		output: make block! 1000
		
		comp-bodies										;-- compile deferred functions
		
		reduce [user main]
	]
	
	comp-as-lib: func [code [block!] /local user main defs pos][
		out: copy/deep [
			Red/System [
				type:   'dll
				origin: 'Red
			]
			
			with red [
				exec: context [
					<declarations>
					init: func [/local tmp] <script>
				]
			]
			on-load: does [
				red/init
				exec/init
			]
		]
		
		set [user main] comp-source code
		
		defs: make block! 10'000
		
		foreach [type cast][
			block	red-block!
			string	red-string!
			context node!
		][
			foreach name lit-vars/:type [
				repend defs [to set-word! name 'as cast 0]
				new-line skip tail defs -4 on
			]
		]
		foreach [name spec] symbols [
			repend defs [to set-word! spec/1 'as 'red-word! 0]
			new-line skip tail defs -4 on
		]
		append defs [
			------------| "Declarations"
		]
		append defs declarations
		pos: tail defs
		append defs [
			------------| "Functions"
		]
		append defs output
;		if verbose = 2 [probe pos]
		
		script: make block! 10'000
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Main program"
		]
		append script main
;		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]
		
		pos: third pick tail out -4
		change/only find pos <script> script
		remove pos: find pos <declarations>
		insert pos defs
		
		output: out
		if verbose > 2 [?? output]
	]
	
	comp-as-exe: func [code [block!] /local out user main][
		out: copy/deep [
			Red/System [origin: 'Red]

			red/init
			
			with red [
				exec: context <script>
			]
		]
		
		set [user main] comp-source code
		
		;-- assemble all parts together in right order
		script: make block! 100'000
		
		append script [
			------------| "Symbols"
		]
		append script sym-table
		append script [
			------------| "Literals"
		]
		append script literals
		append script [
			------------| "Declarations"
		]
		append script declarations
		pos: tail script
		append script [
			------------| "Functions"
		]
		append script output
		if verbose = 2 [probe pos]
		
		append script [
			------------| "Main program"
		]
		append script main
		if find [1 2] verbose [probe user]
		
		unless empty? sys-global [
			process-calls/global sys-global				;-- lazy #call processing
		]

		change/only find last out <script> script		;-- inject compilation result in template
		output: out
		if verbose > 2 [?? output]
	]
	
	clear-docstrings: func [script [block!] /local clean rule pos][
		clean: [any [pos: string! (remove pos) | skip]]
		
		parse script rule: [
			some [
				['action! | 'native!] into [into clean]
				| ['func | 'function | 'routine] into clean
				| into rule
				| skip
			]
		]
	]
	
	load-source: func [file [file! block!] /hidden /local src][
		either file? file [
			unless hidden [script-name: file]
			src: lexer/process read-binary-cache file
		][
			unless hidden [script-name: 'memory]
			src: file
		]
		next src										;-- skip header block
	]
	
	clean-up: does [
		clear include-stk
		clear included-list
		clear symbols
		clear aliases
		clear globals
		clear sys-global
		clear contexts
		clear ctx-stack
		clear objects
		obj-stack: to path! 'objects					;-- reset it to original value
		clear paths-stack
		clear output
		clear sym-table
		clear literals
		clear declarations
		clear bodies
		clear actions
		clear op-actions
		clear keywords
		clear skip functions 2							;-- keep MAKE definition
		clear lit-vars/block
		clear lit-vars/string
		clear lit-vars/context
		s-counter: 0
		depth:	   0
		max-depth: 0
		container-obj?: none
	]

	compile: func [
		file [file! block!]								;-- source file or block of code
		opts [object!]
		/local time src
	][
		verbose: opts/verbosity
		job: opts
		clean-up
		main-path: first split-path file
		no-global?: job/type = 'dll
		
		time: dt [
			src: load-source file
			job/red-pass?: yes
			either no-global? [comp-as-lib src][comp-as-exe src]
		]
		reduce [output time]
	]
]
parse_documentation = function (module) {
    module_path = module_path(module)
    parsed = list(env = module,
                  blocks = roxygen2:::parse_file(module_path, module))
    roclet = roxygen2:::rd_roclet()
    rdfiles = roxygen2:::roc_process(roclet, parsed, dirname(module_path))

    # Due to aliases, documentation entries may have more than one name.
    # Duplicate the relevant documentation entries to get around this.
    # Unfortunately this makes the relevant code ~7x longer.
    aliases = lapply(rdfiles, function (rd) unique(rd[[1]]$alias$value))
    doc_for_name = function (name, aliases)
        sapply(aliases, function (.) rdfiles[[name]], simplify = FALSE)
    docs = mapply(doc_for_name, names(aliases), aliases, SIMPLIFY = FALSE)
    formatted = lapply(unlist(docs, recursive = FALSE, use.names = FALSE),
                       roxygen2:::format.rd_file, wrap = FALSE)
    setNames(formatted, unlist(lapply(docs, names)))
}

#' Display module documentation
#'
#' \code{module_help} displays help on a module’s objects and functions in much
#' the same way \code{\link[utils]{help}} does for package contents.
#'
#' @param topic fully-qualified name of the object or function to get help for,
#'  in the format \code{module$function}
#' @param help_type character string specifying the output format; currently,
#'  only \code{'text'} is supported
#' @note Help is only available if \code{\link{import}} loaded the help stored
#' in the module file(s). By default, this happens only in interactive sessions.
#' @rdname help
#' @export
#' @examples
#' \dontrun{
#' mod = import('mod')
#' module_help(mod$func)
#' }
module_help = function (topic, help_type = getOption('help_type', 'text')) {
    if (help_type != 'text')
        warning('Only help_type == ', sQuote('text'), ' supported for now.')

    topic = substitute(topic)

    if (! is_module_help_topic(topic, parent.frame()))
        stop(sQuote(deparse(topic)), ' is not a valid module help topic',
             call. = FALSE)

    module = get(as.character(topic[[2]]), parent.frame())
    module_name = module_name(module)
    object = as.character(topic[[3]])

    doc = attr(module, 'doc')[[object]]
    if (is.null(doc))
        stop('No documentation available for ', sQuote(object),
             ' in module ', sQuote(module_name), call. = FALSE)

    rd = tools::parse_Rd(textConnection(doc))

    # Taken from utils:::print.help_files_with_topic
    temp = tools::Rd2txt(rd, out = tempfile('Rtxt'), package = module_name)

    # Patch header line.
    doc_text = readLines(temp)
    doc_text[1] = sub('package:', ' module:', doc_text[1])
    writeLines(doc_text, temp)

    file.show(temp,
              title = gettextf('R Help on %s', sQuote(as.character(topic))),
              delete.file = TRUE)
}

is_module_help_topic = function (topic, parent)
    is.call(topic) && topic[[1]] == '$' &&
    exists(as.character(topic[[2]]), parent) &&
    ! is.null(module_name(get(as.character(topic[[2]]), parent)))

#' @usage
#' ?module$function
#' @inheritParams utils::`?`
#' @rdname help
#' @export
#' @examples
#' \dontrun{
#' ?mod$func
#' }
`?` = function (e1, e2) {
    topic = substitute(e1)
    if (missing(e2) && is_module_help_topic(topic, parent.frame()))
        eval(call('module_help', topic), envir = parent.frame())
    else
        eval(`[[<-`(match.call(), 1, utils::`?`), envir = parent.frame())
}

#' @usage
#' help(module$function)
#' @inheritParams utils::help
#' @export
#' @examples
#' \dontrun{
#' help(mod$func)
#' }
help = function (topic, ...) {
    topic = substitute(topic)
    delegate = if (! missing(topic) &&
                   is_module_help_topic(topic, parent.frame()))
        module_help
    else
        utils::help
    eval(`[[<-`(match.call(), 1, delegate), envir = parent.frame())
}
# Diffuse_fraction_of_solar_radiation.R
#
# Pieter Beck (psabeck@gmail.com)
# 09-12-2013
# 
# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation
#
#
# Changelog:
#   VERS  | DATE  		 | CHANGES				| BY
#   ------|------------|----------------|---- 
#		1.0.0	|	09-12-2013 | Wrote script		| PB

#Id is diffuse radiation
#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)
#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation 
#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)


#kt is the clearness index
#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)
#reaching the surface.
#it is defined as kt = I / (Io cos solarzen).
#DSWRF = Downward short wave radiation flux 


IdoverI.calc <- function(kt,solarzen){
  #calculate the fraction of diffuse radiation in global radiation
  #using the Reindl* method (Helbig 2009)
  #
  # Args: 
  #  kt: The clearness index (sensu Liu and Jordan 1960)
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #   the fraction of diffuse radiation (Id) in global radiation (I)
  #  
  if (kt <= 0.3) {IdoverI <- 0.1020 - 0.248*kt}
  else{
  if(kt < 0.78){
    solar.elev <- pi/2 - solarzen
    IdoverI <- 1.4 - 1.749*kt + 0.177*sin(solar.elev)}
  else{
    IdoverI <- 0.147}
  }
  return(IdoverI)
}

SpSd.calc <- function(Rsurface,R_extra_terr,solarzen){
  #calculate direct (Sp) and diffuse (Sd) radiation from global radiation
  #and horizontal extraterrestrial radiation 
  #
  # Args: 
  #  Rsurface: incoming shortwave radiation at the surface
  #  R_extra_terr: horizontal extraterrestrial radiation 
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #  A two-column matrix giving incoming direct [,1], and diffuse [,2] radiationd at the surface
  # 
  if (solarzen > 2*pi){cat("STOP STOP STOP provide solarzenith in radiance to SpSd.calc\n");browser()}
  kt <- Rsurface/R_extra_terr
  #the formula in Lanini 2010 p1 is
  #kt <- Rsurface/(Io*cos(solarzen))
  #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation
  #and thus is adjusted for latitude/solarzen before comparison with Rsurface
  #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation
  IdoverI <- IdoverI.calc(kt,solarzen)
  IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1
  SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)
  return(SpSd)
}

solarzen.calc <- function(coords,datetimePOSIXct){
  #calculate solar zenith based on lat, lon & time of day
  #
  # Args: 
  #  coords: coordinates
  #  datetimePOSIXct: a POSIXct object giving date and time
  #
  # Returns:
  #  solar zenith angle
  #
  require(maptools)
  solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)
  solarelv <- solarelv[,2]
  #convert to radians
  solarelv <- pi*solarelv/180
  #convert to solar zenith (0 when sun is overhead) in radians
  solarzen <- pi/2 - solarelv
  #set below-horizon zeniths to pi/2
  solarzen[solarzen > pi/2] <- pi/2
  cat("in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\n
      while 0 represents directly over-head\n")
  return(solarzen)  
}

R_extra_terr.calc<-function(thisdate,lat.in.deg){
  #calculate hourly extraterrestrial irradiance in W/m2 using sirad package
  #
  # Args: 
  #  thisdate: string object giving date, e.g. "2011-12-31"
  #  lat.in.deg: lattitude in degrees
  #
  # Returns:
  #  hourly extraterrestrial radiation
  #
  # Example:
  #  R_extra_terr.calc(thisdate=c("2012-01-19","2012-01-19"),lat.in.deg=c(-69))
  #
  require(sirad)
  JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear("2011-01-01")
  lat.in.rad <- lat.in.deg*pi/180
  R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]
  #extrat[[1]] uses MJ/(day m^2) units
  #extrat[[2]] uses MJ/(hr m^2) units
  #convert output to W/m2
  conv.fac.daily <- (1000000/ 86400)
  conv.fac.hourly <- (1000000/ 86400)*24
  R_extra_terr[[1]] <- conv.fac.daily *  R_extra_terr[[1]]
  R_extra_terr[[2]] <- conv.fac.hourly *  R_extra_terr[[2]]
  #set negative hourly extrat irrad to 0
  #R_exta_terr <- R_exta_terr[[2]]
  R_extra_terr[[2]][R_extra_terr[[2]]<0]<-0
  R_extra_terr <- R_extra_terr[[2]]
  R_extra_terr <- matrix(R_extra_terr,ncol=24)
  cat("calculated 24hrs of extraterrestrial irradiance for\n"
      ,nrow(R_extra_terr)," latitude-date combinations\n")
  #output is hourly starting at solar midning
  return(R_extra_terr)
}

shift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){
  # Shift a vector over by n spots
  #
  #Args: 
  #  vec: vector to be shifted
  #  n: number of spots to shift the vector over
  #
  #  Wrap adds the entry at the beginning to the end
  # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs
  #
  # Returns:
  #  the vector vec, shifted over n sots
  # 
  # Source:
  #  http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions
  #
  if(length(vec)<abs(n)) { 
    #stop("Length of vector must be greater than the magnitude of n \n") 
  }
  if(n==0) { 
    return(vec) 
  } else if(length(vec)==n) { 
    # return empty
    length(vec) <- 0
    return(vec)
  } else if(n>0) {
    returnvec <- vec[seq(n+1,length(vec) )]
    if(wrap) {
      returnvec <- c(returnvec,vec[seq(n)])
    } else if(pad) {
      returnvec <- c(returnvec,rep(NA,n))
    }
  } else if(n<0) {
    returnvec <- vec[seq(1,length(vec)-abs(n))]
    if(wrap) {
      returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )
    } else if(pad) {
      returnvec <- c( rep(NA,abs(n)), returnvec )
    }
    
  }
  return(returnvec)
}

shift_to_UTC <- function(hourly_tser,original.zone){
  #shift an hourly vector starting at midnight to start at midnight UTC
  #
  #Args: 
  #  hourly_tser: an hourly vector starting at midnight local time
  #  original.zone: the local time zone
  #
  # Returns:
  #  an hourly vector, starting at midnight UTC
  # 
  # Example:
  #  shift_to_UTC(hourly_tser=1:24,original.zone="America/Mexico_City")
  require(timeDate)
  tt1<-timeDate("2010-01-01 00:00:00",zone=original.zone)
  tt2<-timeDate("2010-01-01 00:00:00",zone="UTC")
  shift.by <- as.numeric(tt2-tt1)
  cat("the 24 hour series will be shifted earlier hrs by ",shift.by," hours to match UTC\n")
  if (is.matrix(hourly_tser)){
    shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))
    }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}
  return(shifted_tser)
}

R_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){
  #given a date, latitude, and time zone, calculate extraterrestrial radiation
  #for that latitude
  #
  #Args:
  #  thisdate: date
  #  lat.in.deg: latitude in degrees
  #  original.zone: timezone
  #
  # Returns:
  #  Extraterrestrial radiation for the given latitude and day, in 6 hour steps
  #
  if(length(thisdate)!=length(lat.in.deg)){
    cat("Please provide thisdate and lat.in.deg of equal length\n");browser()}
  #get the 24 R_extra_terr values for this lat & date
  R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)
  #determine by how many hours the series need to be shifted
  R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)
  #convert the R_extra_terr values from 24 hour to epoch
  epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}
  R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))
  cat("all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\n")
  rm(R_extra_terr_24,R_extra_terr_24UTC)
  return(R_extra_terr_epochUTC)
}

# Diffuse_fraction_of_solar_radiation.R
#
# Pieter Beck (psabeck@gmail.com)
# 09-12-2013
# 
# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation
#
#
# Changelog:
#   VERS  | DATE  		 | CHANGES				| BY
#   ------|------------|----------------|---- 
#		1.0.0	|	09-12-2013 | Wrote script		| PB

#Id is diffuse radiation
#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)
#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation 
#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)


#kt is the clearness index
#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)
#reaching the surface.
#it is defined as kt = I / (Io cos solarzen).
#DSWRF = Downward short wave radiation flux 


IdoverI.calc <- function(kt,solarzen){
  #calculate the fraction of diffuse radiation in global radiation
  #using the Reindl* method (Helbig 2009)
  #
  # Args: 
  #  kt: The clearness index (sensu Liu and Jordan 1960)
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #   the fraction of diffuse radiation (Id) in global radiation (I)
  #  
  if (kt <= 0.3) {IdoverI <- 0.1020 - 0.248*kt}
  else{
  if(kt < 0.78){
    solar.elev <- pi/2 - solarzen
    IdoverI <- 1.4 - 1.749*kt + 0.177*sin(solar.elev)}
  else{
    IdoverI <- 0.147}
  }
  return(IdoverI)
}

SpSd.calc <- function(Rsurface,R_extra_terr,solarzen){
  #calculate direct (Sp) and diffuse (Sd) radiation from global radiation
  #and horizontal extraterrestrial radiation 
  #
  # Args: 
  #  Rsurface: incoming shortwave radiation at the surface
  #  R_extra_terr: horizontal extraterrestrial radiation 
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #  A two-column matrix giving incoming direct [,1], and diffuse [,2] radiationd at the surface
  # 
  if (solarzen > 2*pi){cat("STOP STOP STOP provide solarzenith in radiance to SpSd.calc\n");browser()}
  kt <- Rsurface/R_extra_terr
  #the formula in Lanini 2010 p1 is
  #kt <- Rsurface/(Io*cos(solarzen))
  #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation
  #and thus is adjusted for latitude/solarzen before comparison with Rsurface
  #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation
  IdoverI <- IdoverI.calc(kt,solarzen)
  IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1
  SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)
  return(SpSd)
}

solarzen.calc <- function(coords,datetimePOSIXct){
  #calculate solar zenith based on lat, lon & time of day
  #
  # Args: 
  #  coords: coordinates
  #  datetimePOSIXct: a POSIXct object giving date and time
  #
  # Returns:
  #  solar zenith angle
  #
  require(maptools)
  solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)
  solarelv <- solarelv[,2]
  #convert to radians
  solarelv <- pi*solarelv/180
  #convert to solar zenith (0 when sun is overhead) in radians
  solarzen <- pi/2 - solarelv
  #set below-horizon zeniths to pi/2
  solarzen[solarzen > pi/2] <- pi/2
  cat("in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\n
      while 0 represents directly over-head\n")
  return(solarzen)  
}

R_extra_terr.calc<-function(thisdate,lat.in.deg){
  #calculate hourly extraterrestrial irradiance in W/m2 using sirad package
  #
  # Args: 
  #  thisdate: string object giving date, e.g. "2011-12-31"
  #  lat.in.deg: lattitude in degrees
  #
  # Returns:
  #  hourly extraterrestrial radiation
  #
  # Example:
  #  R_extra_terr.calc(thisdate=c("2012-01-19","2012-01-19"),lat.in.deg=c(-69))
  #
  require(sirad)
  JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear("2011-01-01")
  lat.in.rad <- lat.in.deg*pi/180
  R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]
  #extrat[[1]] uses MJ/(day m^2) units
  #extrat[[2]] uses MJ/(hr m^2) units
  #convert output to W/m2
  conv.fac.daily <- (1000000/ 86400)
  conv.fac.hourly <- (1000000/ 86400)*24
  R_extra_terr[[1]] <- conv.fac.daily *  R_extra_terr[[1]]
  R_extra_terr[[2]] <- conv.fac.hourly *  R_extra_terr[[2]]
  #set negative hourly extrat irrad to 0
  #R_exta_terr <- R_exta_terr[[2]]
  R_extra_terr[[2]][R_extra_terr[[2]]<0]<-0
  R_extra_terr <- R_extra_terr[[2]]
  R_extra_terr <- matrix(R_extra_terr,ncol=24)
  cat("calculated 24hrs of extraterrestrial irradiance for\n"
      ,nrow(R_extra_terr)," latitude-date combinations\n")
  #output is hourly starting at solar midning
  return(R_extra_terr)
}

shift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){
  # Shift a vector over by n spots
  #
  #Args: 
  #  vec: vector to be shifted
  #  n: number of spots to shift the vector over
  #
  #  Wrap adds the entry at the beginning to the end
  # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs
  #
  # Returns:
  #  the vector vec, shifted over n sots
  # 
  # Source:
  #  http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions
  #
  if(length(vec)<abs(n)) { 
    #stop("Length of vector must be greater than the magnitude of n \n") 
  }
  if(n==0) { 
    return(vec) 
  } else if(length(vec)==n) { 
    # return empty
    length(vec) <- 0
    return(vec)
  } else if(n>0) {
    returnvec <- vec[seq(n+1,length(vec) )]
    if(wrap) {
      returnvec <- c(returnvec,vec[seq(n)])
    } else if(pad) {
      returnvec <- c(returnvec,rep(NA,n))
    }
  } else if(n<0) {
    returnvec <- vec[seq(1,length(vec)-abs(n))]
    if(wrap) {
      returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )
    } else if(pad) {
      returnvec <- c( rep(NA,abs(n)), returnvec )
    }
    
  }
  return(returnvec)
}

shift_to_UTC <- function(hourly_tser,original.zone){
  #shift an hourly vector starting at midnight to start at midnight UTC
  #
  #Args: 
  #  hourly_tser: an hourly vector starting at midnight local time
  #  original.zone: the local time zone
  #
  # Returns:
  #  an hourly vector, starting at midnight UTC
  # 
  # Example:
  #  shift_to_UTC(hourly_tser=1:24,original.zone="America/Mexico_City")
  require(timeDate)
  tt1<-timeDate("2010-01-01 00:00:00",zone=original.zone)
  tt2<-timeDate("2010-01-01 00:00:00",zone="UTC")
  shift.by <- as.numeric(tt2-tt1)
  cat("the 24 hour series will be shifted earlier hrs by ",shift.by," hours to match UTC\n")
  if (is.matrix(hourly_tser)){
    shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))
    }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}
  return(shifted_tser)
}

R_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){
  #given a date, latitude, and time zone, calculate extraterrestrial radiation
  #for that latitude
  #
  #Args:
  #  thisdate: date
  #  lat.in.deg: latitude in degrees
  #  original.zone: timezone
  #
  # Returns:
  #  Extraterrestrial radiation for the given latitude and day, in 6 hour steps
  #
  if(length(thisdate)!=length(lat.in.deg)){
    cat("Please provide thisdate and lat.in.deg of equal length\n");browser()}
  #get the 24 R_extra_terr values for this lat & date
  R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)
  #determine by how many hours the series need to be shifted
  R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)
  #convert the R_extra_terr values from 24 hour to epoch
  epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}
  R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))
  cat("all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\n")
  rm(R_extra_terr_24,R_extra_terr_24UTC)
  return(R_extra_terr_epochUTC)
}

# Diffuse_fraction_of_solar_radiation.R
#
# Pieter Beck (psabeck@gmail.com)
# 09-12-2013
# 
# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation
#
#
# Changelog:
#   VERS  | DATE  		 | CHANGES				| BY
#   ------|------------|----------------|---- 
#		1.0.0	|	09-12-2013 | Wrote script		| PB

#Id is diffuse radiation
#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)
#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation 
#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)


#kt is the clearness index
#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)
#reaching the surface.
#it is defined as kt = I / (Io cos solarzen).
#DSWRF = Downward short wave radiation flux 


IdoverI.calc <- function(kt,solarzen){
  #calculate the fraction of diffuse radiation in global radiation
  #using the Reindl* method (Helbig 2009)
  #
  # Args: 
  #  kt: The clearness index (sensu Liu and Jordan 1960)
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #   the fraction of diffuse radiation (Id) in global radiation (I)
  #  
  if (kt <= 0.3) {IdoverI <- 0.1020 - 0.248*kt}
  else{
  if(kt < 0.78){
    solar.elev <- pi/2 - solarzen
    IdoverI <- 1.4 - 1.749*kt + 0.177*sin(solar.elev)}
  else{
    IdoverI <- 0.147}
  }
  return(IdoverI)
}

SpSd.calc <- function(Rsurface,R_extra_terr,solarzen){
  #calculate direct (Sp) and diffuse (Sd) radiation from global radiation
  #and horizontal extraterrestrial radiation 
  #
  # Args: 
  #  Rsurface: incoming shortwave radiation at the surface
  #  R_extra_terr: horizontal extraterrestrial radiation 
  #  solarzen: solar zenith angle in radians
  #
  # Returns:
  #  A two-column matrix giving incoming direct [,1], and diffuse [,2] radiationd at the surface
  # 
  if (solarzen > 2*pi){cat("STOP STOP STOP provide solarzenith in radiance to SpSd.calc\n");browser()}
  kt <- Rsurface/R_extra_terr
  #the formula in Lanini 2010 p1 is
  #kt <- Rsurface/(Io*cos(solarzen))
  #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation
  #and thus is adjusted for latitude/solarzen before comparison with Rsurface
  #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation
  IdoverI <- IdoverI.calc(kt,solarzen)
  IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1
  SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)
  return(SpSd)
}

solarzen.calc <- function(coords,datetimePOSIXct){
  #calculate solar zenith based on lat, lon & time of day
  #
  # Args: 
  #  coords: coordinates
  #  datetimePOSIXct: a POSIXct object giving date and time
  #
  # Returns:
  #  solar zenith angle
  #
  require(maptools)
  solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)
  solarelv <- solarelv[,2]
  #convert to radians
  solarelv <- pi*solarelv/180
  #convert to solar zenith (0 when sun is overhead) in radians
  solarzen <- pi/2 - solarelv
  #set below-horizon zeniths to pi/2
  solarzen[solarzen > pi/2] <- pi/2
  cat("in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\n
      while 0 represents directly over-head\n")
  return(solarzen)  
}

R_extra_terr.calc<-function(thisdate,lat.in.deg){
  #calculate hourly extraterrestrial irradiance in W/m2 using sirad package
  #
  # Args: 
  #  thisdate: string object giving date, e.g. "2011-12-31"
  #  lat.in.deg: lattitude in degrees
  #
  # Returns:
  #  hourly extraterrestrial radiation
  #
  # Example:
  #  R_extra_terr.calc(thisdate=c("2012-01-19","2012-01-19"),lat.in.deg=c(-69))
  #
  require(sirad)
  JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear("2011-01-01")
  lat.in.rad <- lat.in.deg*pi/180
  R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]
  #extrat[[1]] uses MJ/(day m^2) units
  #extrat[[2]] uses MJ/(hr m^2) units
  #convert output to W/m2
  conv.fac.daily <- (1000000/ 86400)
  conv.fac.hourly <- (1000000/ 86400)*24
  R_extra_terr[[1]] <- conv.fac.daily *  R_extra_terr[[1]]
  R_extra_terr[[2]] <- conv.fac.hourly *  R_extra_terr[[2]]
  #set negative hourly extrat irrad to 0
  #R_exta_terr <- R_exta_terr[[2]]
  R_extra_terr[[2]][R_extra_terr[[2]]<0]<-0
  R_extra_terr <- R_extra_terr[[2]]
  R_extra_terr <- matrix(R_extra_terr,ncol=24)
  cat("calculated 24hrs of extraterrestrial irradiance for\n"
      ,nrow(R_extra_terr)," latitude-date combinations\n")
  #output is hourly starting at solar midning
  return(R_extra_terr)
}

shift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){
  # Shift a vector over by n spots
  #
  #Args: 
  #  vec: vector to be shifted
  #  n: number of spots to shift the vector over
  #
  #  Wrap adds the entry at the beginning to the end
  # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs
  #
  # Returns:
  #  the vector vec, shifted over n sots
  # 
  # Source:
  #  http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions
  #
  if(length(vec)<abs(n)) { 
    #stop("Length of vector must be greater than the magnitude of n \n") 
  }
  if(n==0) { 
    return(vec) 
  } else if(length(vec)==n) { 
    # return empty
    length(vec) <- 0
    return(vec)
  } else if(n>0) {
    returnvec <- vec[seq(n+1,length(vec) )]
    if(wrap) {
      returnvec <- c(returnvec,vec[seq(n)])
    } else if(pad) {
      returnvec <- c(returnvec,rep(NA,n))
    }
  } else if(n<0) {
    returnvec <- vec[seq(1,length(vec)-abs(n))]
    if(wrap) {
      returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )
    } else if(pad) {
      returnvec <- c( rep(NA,abs(n)), returnvec )
    }
    
  }
  return(returnvec)
}

shift_to_UTC <- function(hourly_tser,original.zone){
  #shift an hourly vector starting at midnight to start at midnight UTC
  #
  #Args: 
  #  hourly_tser: an hourly vector starting at midnight local time
  #  original.zone: the local time zone
  #
  # Returns:
  #  an hourly vector, starting at midnight UTC
  # 
  # Example:
  #  shift_to_UTC(hourly_tser=1:24,original.zone="America/Mexico_City")
  require(timeDate)
  tt1<-timeDate("2010-01-01 00:00:00",zone=original.zone)
  tt2<-timeDate("2010-01-01 00:00:00",zone="UTC")
  shift.by <- as.numeric(tt2-tt1)
  cat("the 24 hour series will be shifted earlier hrs by ",shift.by," hours to match UTC\n")
  if (is.matrix(hourly_tser)){
    shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))
    }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}
  return(shifted_tser)
}

R_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){
  #given a date, latitude, and time zone, calculate extraterrestrial radiation
  #for that latitude
  #
  #Args:
  #  thisdate: date
  #  lat.in.deg: latitude in degrees
  #  original.zone: timezone
  #
  # Returns:
  #  Extraterrestrial radiation for the given latitude and day, in 6 hour steps
  #
  if(length(thisdate)!=length(lat.in.deg)){
    cat("Please provide thisdate and lat.in.deg of equal length\n");browser()}
  #get the 24 R_extra_terr values for this lat & date
  R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)
  #determine by how many hours the series need to be shifted
  R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)
  #convert the R_extra_terr values from 24 hour to epoch
  epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}
  R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))
  cat("all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\n")
  rm(R_extra_terr_24,R_extra_terr_24UTC)
  return(R_extra_terr_epochUTC)
}

`%||%` <- function(x, y) if (is.null(x)) y else x

#' Merge two lists and overwrite latter entries with former entries
#' if names are the same.
#'
#' For example, \code{list_merge(list(a = 1, b = 2), list(b = 3, c = 4))}
#' will be \code{list(a = 1, b = 3, c = 4)}.
#' @param list1 list
#' @param list2 list
#' @return the merged list.
#' @examples
#' stopifnot(identical(syberiaStages:::list_merge(list(a = 1, b = 2), list(b = 3, c = 4)),
#'                     list(a = 1, b = 3, c = 4)))
#' stopifnot(identical(syberiaStages:::list_merge(NULL, list(a = 1)), list(a = 1)))
# TODO: (RK) This is a duplicate of the function in mungebits -- is there
# any way to pull them out into one place? Maybe Ramd?
list_merge <- function(list1, list2) {
  list1 <- list1 %||% list()
  # Pre-allocate memory to make this slightly faster.
  list1[Filter(function(x) nchar(x) > 0, names(list2) %||% c())] <- NULL
  for (i in seq_along(list2)) {
    name <- names(list2)[i]
    if (!identical(name, NULL) && !identical(name, "")) list1[[name]] <- list2[[i]]
    else list1 <- append(list1, list(list2[[i]]))
  }
  list1
}

#' Parse functions out of a custom resource.
#'
#' @param functions character. The names of functions to parse out.
#' @param provided_env environment. The environment the resource was loaded from.
#' @param type character. The keyword for the resource.
#' @param resource_type character. The type of the resource (e.g., "classifier",
#'   "adapter", etc.). This will be used to generate error messages.
#' @param strict logical. Whether or not to error if the functions are not found.
#' @return a list containing keys same as the \code{functions} argument.
#'    and predict functions.
parse_custom_functions <- function(functions, provided_env, type,
                                   resource_type = 'classifier', strict = TRUE) {
  provided_fns <- setNames(vector('list', length(functions)), functions)
  for (function_type in names(provided_fns)) {
    fn <- Filter(
      function(x) is.function(provided_env[[x]]),
      grep(function_type, ls(provided_env), value = TRUE)
    )
    # TODO: (RK) Refactor this to be more careful about idempotent resources.
    error <- function(snip = 'a') paste0("The custom ", resource_type, " in ",
      "lib/", resource_type, "s/", type, ".R should define ", snip, " '",
      testthat::colourise(function_type, 'green'), "' function.")
    if (length(fn) == 0 && identical(strict, TRUE)) stop(error(), call. = FALSE)
    else if (length(fn) > 1)
      stop(error('only one'), " Instead, you defined ", length(fn), ", namely: ",
           paste0(fn, collapse = ', '), call. = FALSE)
    else if (length(fn) == 1)
      provided_fns[[function_type]] <- provided_env[[fn]]
  }
  provided_fns
}

# Helper function to serialize a tundraContainer of xgboost model object
#
# TODO: (RK) Refactor this function out of the package.
serialize_xgb_object <- function(object) {
	file_save <- tempfile()
  on.exit(unlink(file_save))
  xgboost::xgb.save(object$output$model, file_save)
  stopifnot(!is.na(as.integer(file.info(file_save)$size)))
  object$output$model <- NULL
  con <- file(file_save, 'rb')
  on.exit(close(con), add = TRUE)
  invisible(structure(
    class = 'special_serialized_object', 
    list(
      deserialize = function(x) {
        file_load <- tempfile()
        on.exit(unlink(file_load))
        con <- file(file_load, 'wb')
        on.exit(close(con), add = TRUE)
        writeBin(x$xgb.bin, con, useBytes = TRUE)
        close(con)
        x$container$output$model <- xgboost::xgb.load(file_load)
        invisible(x$container)
      }, 
      object = list(
       container = object, 
       xgb.bin = readBin(con, raw(), n = file.info(file_save)$size)
      )
    )
  ))
}

library(pbdMPI, quiet = TRUE)
library(pbdDMAT, quiet = TRUE)
library(pbdADIOS, quiet = TRUE)

## begin function definitions
adios.init <- function(method="ADIOS_READ_METHOD_BP", par="verbose=3")
{
    invisible(adios.read.init.method("ADIOS_READ_METHOD_BP",
                                     params="verbose=3"))
}

adios.open <- function(file, timeout=1, method="ADIOS_READ_METHOD_BP",
                       lockmode="ADIOS_LOCKMODE_NONE")
{
    ## timeout default is 1 sec
    pt <- adios.read.open(file, adios.timeout=timeout, "ADIOS_READ_METHOD_BP",
                          adios.lockmode="ADIOS_LOCKMODE_NONE")
    if(comm.rank() == 0) bpls <- system(paste("bpls", file), intern=TRUE)
    else bpls <- NULL
    bpls <- bcast(bpls)
    list(pt=pt, bpls=bpls)
}

## end function definitions

gctorture(TRUE)
init()
adios.init()

## specify and open file for reading
dir.data <- "/lustre/atlas/scratch/ost/stf006/heat"
file <- paste(dir.data, "heat.bp", sep="/")
file.ptr <- adios.open(file)

## select variable to read
variable <- "T"

## get variable dimensions
varinfo = adios.inq.var(file.ptr$pt, variable)
block <- adios.inq.var.blockinfo(file.ptr$pt, varinfo)
ndim <- custom.inq.var.ndim(varinfo)
dims <- custom.inq.var.dims(varinfo)

## get dimensions and split
source("/ccs/home/ost/adios/partition.r")
g.dim <- dims
split <- c(TRUE, FALSE)
my.data.partition <- data.partition(seq(0, 0, along.with=g.dim), g.dim, split)
my.dim <- my.count <- my.data.partition$my.dim
my.start <- my.data.partition$my.start
my.grid <- my.data.partition$my.grid

## partition across first dimension (expects at least 2d)
slice_size0 <- as.integer(dims[1] %/% comm.size())
slice_size <- slice_size0
if(comm.rank() == (comm.size() - 1))
    slice_size <- as.integer(slice_size + (dims[1] %% comm.size()))
start <- c(as.integer(comm.rank() * slice_size0), rep(0, ndim - 1))
count <- c(slice_size, as.integer(dims[2:ndim]))

errno <- 0 # Default value 0
steps <- 0
retval <- 0

while(errno != -21) { ## This is hard-coded for now. -21=err_end_of_stream
    steps = steps + 1 ## Double check with Norbert. Should it start with 1 or 2

    ## set reading bounding box
    adios.selection  <- adios.selection.boundingbox(ndim, my.start, my.count)
    comm.print("Selection.boundingbox complete ...")
    
    ## schedule the read
    adios.data <- adios.schedule.read(varinfo, my.start, my.count, file.ptr$pt,
                                      adios.selection, variable, 0, 1)
    comm.print("Schedule read complete ...")
    
    ## perform the read
    adios.perform.reads(file.ptr$pt, 1)
    comm.print("Perform read complete ...")

    data_chunk <- custom.data.access(adios.data, adios.selection, varinfo)
    comm.print("Data access complete ...")

    ## print a few to verify
    comm.cat("first 5:", head(data_chunk, 5),"\n")
    comm.cat("last 5:", tail(data_chunk, 5),"\n")

    ## shape into matrix with first dim as rows
    ## local reshape dimensions
    my.ncol <- prod(my.dim[2])
    my.nrow <- my.dim[1]
    ldim <- c(my.nrow, my.ncol)

    ## global reshape dimensions
    g.ncol <- prod(g.dim[2])
    g.nrow <- g.dim[1]
    gdim <- c(g.nrow, g.ncol)
    
    ## now glue into a ddmatrix
    x <- matrix(data_chunk, nrow=my.nrow, ncol=my.ncol, byrow=FALSE)
    ## continue with analysis here!!
    ## X <- new("ddmatrix", Data=x, dim=gdim, ldim=ldim, bldim=ldim, ICTXT=2)
    ## comm.print(X)

    s <- sum(data_chunk)
    n <- length(data_chunk)
    sa <- allreduce(s)
    na <- allreduce(n)
    comm.cat(comm.rank(), "mean =", sa/na, "lmean =", s/n, "ln =", n, "\n",
             quiet=TRUE, all.rank=TRUE)

    ##
    ## Here, write out the results of the analysis
    ## For testing purposes, write the data.chunk back.
    ##
    
    ## try to get more data
    adios.advance.step(file.ptr$pt, 0, adios.timeout.sec=1)
    comm.print(paste("Done advance.step", steps, "..."))
     
    ## check errors
    errno <- adios.errno()
    comm.cat("Error Num",errno, "\n")

    ## if error is timeout (or EOF)
    if(errno == -22){ #-22 = err_step_notready
        comm.cat(comm.rank(), "Timeout waiting for more data. Quitting ...\n")
        break
    }
if(steps > 2) break
} # While end 

comm.print("Broke out of loop ...")
adios.read.close(file.ptr$pt)
comm.print("File closed")
adios.read.finalize.method("ADIOS_READ_METHOD_BP")
comm.print("Finalized adios ...")
finalize() # pbdMPI finalize

Kernel <- setRefClass("Kernel",
                fields = c("connection_info", "zmqctx", "sockets", "executor"),
                methods= list(

hb_reply = function() {
    data <- receive.socket(sockets$hb, unserialize = FALSE)
    send.socket(sockets$hb, data, serialize = FALSE)
},

#'<brief desc>
#'
#'<full description>
#' @param msg_lst <what param does>
#' @export
sign_msg = function(msg_lst) {
    concat <- unlist(msg_lst)
    return(hmac(connection_info$key, concat, "sha256"))
},
#'<brief desc>
#'
#'<full description>
#' @param parts <what param does>
#' @import rjson
#' @export
wire_to_msg = function(parts) {
    i <- 1
    #print(parts)
    while (any(parts[[i]] != charToRaw("<IDS|MSG>"))) {
        i <- i + 1
    }
    signature <- rawToChar(parts[[i + 1]])
    expected_signature <- sign_msg(parts[(i + 2):(i + 5)])
    stopifnot(identical(signature, expected_signature))
    header <- fromJSON(rawToChar(parts[[i + 2]]))
    parent_header <- fromJSON(rawToChar(parts[[i + 3]]))
    metadata <- fromJSON(rawToChar(parts[[i + 4]]))
    content <- fromJSON(rawToChar(parts[[i + 5]]))
    if (i > 1) {
        identities <- parts[1:(i - 1)]
    } else {
        identities <- NULL
    }
    return(list(header = header, parent_header = parent_header, metadata = metadata, 
        content = content, identities = identities))
},
#'<brief desc>
#'
#'<full description>
#' @param msg <what param does>
#' @export
msg_to_wire = function(msg) {
    #print(msg)
    bodyparts <- list(charToRaw(toJSON(msg$header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$parent_header, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$metadata, auto_unbox=TRUE)),
                      charToRaw(toJSON(msg$content, auto_unbox=TRUE))
                     )
    signature <- sign_msg(bodyparts)
    return(c(msg$identities, list(charToRaw("<IDS|MSG>")), list(charToRaw(signature)), bodyparts))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @export
new_reply = function(msg_type, parent_msg) {
    header <- list(msg_id = UUIDgenerate(), username = parent_msg$header$username, 
        session = parent_msg$header$session, msg_type = msg_type)
    return(list(header = header, parent_header = parent_msg$header, identities = parent_msg$identities, 
        metadata = namedlist()  # Ensure this is {} in JSON, not []
        ))
},
#'<brief desc>
#'
#'<full description>
#' @param msg_type <what param does>
#' @param  parent_msg <what param does>
#' @param  socket <what param does>
#' @param  content <what param does>
#' @export
send_response = function(msg_type, parent_msg, socket_name, content) {
    msg <- new_reply(msg_type, parent_msg)
    msg$content <- content
    socket <- sockets[socket_name][[1]]
    send.multipart(socket, msg_to_wire(msg))
},
#'<brief desc>
#'
#'<full description>
#' @param  <what param does>
#' @export
handle_shell = function() {
    parts <- receive.multipart(sockets$shell)
    msg <- wire_to_msg(parts)
    if (msg$header$msg_type == "execute_request") {
        executor$execute(msg)
    } else if (msg$header$msg_type == "kernel_info_request") {
        kernel_info(msg)
    } else if (msg$header$msg_type == "history_request") {
        history(msg)
    } else {
        print(c("Got unhandled msg_type:", msg$header$msg_type))
    }
},

history = function(request) {
  send_response("history_reply", request, 'shell', list(history=list()))
},

kernel_info = function(request) {
  send_response("kernel_info_reply", request, 'shell',
                list(protocol_version=c(4, 0), language="R",
                     language_info=list(name="R", codemirror_mode="r",
                                pygments_lexer="r", mimetype="text/x-r-source",
                                file_extension="r"
                                )
                    )
                )
},

handle_control = function() {
  parts = receive.multipart(sockets$control)
  msg = wire_to_msg(parts)
  if (msg$header$msg_type == "shutdown_request") {
    shutdown(msg)
  } else {
    print(c("Unhandled control message, msg_type:", msg$header$msg_type))
  }
},

shutdown = function(request) {
  send_response('shutdown_reply', request, 'control',
                list(restart=request$content$restart))
  stop("Shut down by frontend.")
},

initialize = function(connection_file) {
    connection_info <<- fromJSON(connection_file)
    print(connection_info)
    url <- paste(connection_info$transport, "://", connection_info$ip, sep = "")
    url_with_port <- function(port_name) {
        return(paste(url, ":", connection_info[port_name], sep = ""))
    }

    # ZMQ Socket setup
    zmqctx <<- init.context()
    sockets <<- list(
        hb = init.socket(zmqctx, "ZMQ_REP"),
        iopub = init.socket(zmqctx, "ZMQ_PUB"),
        control = init.socket(zmqctx, "ZMQ_ROUTER"),
        stdin = init.socket(zmqctx, "ZMQ_ROUTER"),
        shell = init.socket(zmqctx, "ZMQ_ROUTER")
    )
    bind.socket(sockets$hb, url_with_port("hb_port"))
    bind.socket(sockets$iopub, url_with_port("iopub_port"))
    bind.socket(sockets$control, url_with_port("control_port"))
    bind.socket(sockets$stdin, url_with_port("stdin_port"))
    bind.socket(sockets$shell, url_with_port("shell_port"))

    executor <<- Executor$new(kernel=.self)
},

run = function() {
    while (1) {
        events <- poll.socket(list(sockets$hb, sockets$shell, sockets$control),
                              list("read", "read", "read"), timeout = -1L)
        if (events[[1]]$read) {
            # heartbeat
            hb_reply()
        }
        if (events[[2]]$read) {
            # Shell socket
            handle_shell()
        }

        if (events[[3]]$read) {  # Control socket
            handle_control()
        }
    }
})
)

#'Initialise and run the kernel
#'
#'@param connection_file The path to the IPython connection file, written by the frontend
#'@export 
main <- function(connection_file="") {
    if (connection_file == "") {
        # On Windows, passing the connection file in as a string literal fails,
        # because the \U in C:\Users looks like a unicode escape. So, we have to
        # pass it as a separate command line argument.
        connection_file = commandArgs(T)[1]
    }
    kernel <- Kernel$new(connection_file=connection_file)
    kernel$run()
}

#'Install the kernelspec to tell IPython (>= 3) about IRkernel
#'
#'@export
installspec <- function() {
    srcdir = system.file("kernelspec", package="IRkernel")
    cmd = paste("ipython kernelspec install --replace --name ir", srcdir, sep=" ")
    system(cmd, wait=TRUE)
}
mapBMatNames <- function(in.names, aa.names, model = "roc", as.delta.eta = T){
  ### Make a copy
  out.names <- in.names

  ### Get number of coefs and their names.
  ncoef <- get.my.ncoef(model, assign.Env = FALSE)
  coefnames <- get.my.coefnames(model, assign.Env = FALSE, as.delta.eta)

  ### Get synonymous codons.
  if("Z" %in% aa.names){
    synonymous.codon <- .CF.GV$synonymous.codon.split
  } else{
    synonymous.codon <- .CF.GV$synonymous.codon
  }

  ### Drop the last reference codon.
  synonymous.codon <- lapply(synonymous.codon, function(x) x[-length(x)])

  if(model == "roc" || model == "nse"){
    codon.count <- lapply(synonymous.codon, length)
    id.intercept <- grep("Intercept", in.names)
    id.slope <- 1:length(in.names)
    id.slope <- id.slope[-id.intercept]

    start <- 1
    for(aa in aa.names){
      ncodons <- codon.count[[aa]] * ncoef
      if(ncodons == 0) next # for M and W
      aa.codon.names <- paste(aa, synonymous.codon[[aa]], sep = ".")
      out.names[start:(start+ncodons-1)] <- rep(aa.codon.names, ncoef)
      start <- start + ncodons
    }

    ### Paste by amino acids, synonymous codons, and coefficient names.
    out.names[id.intercept] <- paste(out.names[id.intercept],
                                     coefnames[1], sep = ".")
    out.names[id.slope] <- paste(out.names[id.slope],
                                 coefnames[2], sep = ".")
  }

  ### Return.
  return(out.names)
} # End of mapBMatNames().
# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = as.array(map(X, along, function(x) FUN(x), subsets)) #FIXME: map should have drop=T/F
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll, drop=F) {
    abind::asub(X, ll, drop=drop)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    else if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along]), drop=F) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)!=dim(X)[along] || !is.numeric(subsets))
        lnames = usubsets
    else
        lnames = base::dimnames(X)[[along]]
    setNames(lapply(idxList, function(ll) subset(X, ll, drop=drop)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
REBOL [
	Title:   "Red source files preprocessor"
	Author:  "Nenad Rakocevic"
	File: 	 %includes.r
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2013 Nenad Rakocevic. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/master/BSD-3-License.txt"
]

change-dir %..
do %system/utils/encap-fs.r

write %build/bin/sources.r set-cache [
	%version.r
	%usage.txt
	%boot.red
	%lexer.red
	%compiler.r
	%lexer.r
	%runtime/ [
		%actions.reds
		%allocator.reds
		%debug-tools.reds
		%interpreter.reds
		%macros.reds
		%natives.reds
		%parse.reds
		%random.reds
		%red.reds
		%stack.reds
		%stack.reds
		%tools.reds
		%unicode.reds
		%simple-io.reds
		%datatypes/ [
			%action.reds
			%block.reds
			%bitset.reds
			%char.reds
			%common.reds
			%context.reds
			%datatype.reds
			%file.reds
			%float.reds
			%function.reds
			%get-path.reds
			%get-word.reds
			%integer.reds
			%issue.reds
			%lit-path.reds
			%lit-word.reds
			%logic.reds
			%native.reds
			%none.reds
			%op.reds
			%object.reds
			%paren.reds
			%path.reds
			%point.reds
			%refinement.reds
			%routine.reds
			%set-path.reds
			%set-word.reds
			%string.reds
			%structures.reds
			%symbol.reds
			%unset.reds
			%url.reds
			%word.reds
		]
		%platform/ [
			%android.reds
			%darwin.reds
			%linux.reds
			%POSIX.reds
			%syllable.reds
			%win32.reds
		]
		%console/ [
			%console.red
			%help.red
			%input.red
		]
	]
	%utils/ [
		%extractor.r
	]
	%system/ [
		%compiler.r
		%config.r
		%emitter.r
		%linker.r
		%loader.r
		%runtime/ [
			%android.reds
			%common.reds
			%darwin.reds
			%debug.reds
			%freebsd.reds
			%libc.reds
			%lib-names.reds
			%lib-natives.reds
			%linux.reds
			%linux-sigaction.reds
			%POSIX.reds
			%POSIX-signals.reds
			%start.reds
			%syllable.reds
			%system.reds
			%utils.reds
			%win32.reds
			%win32-driver.reds
		]
		%formats/ [
			%ELF.r
			%Mach-O.r
			%PE.r
		]
		%targets/ [
			%ARM.r
			%IA-32.r
			%target-class.r
		]
		%utils/ [
			%IEEE-754.r
			%int-to-bin.r
			%r2-forward.r
			%secure-clean-path.r
			%virtual-struct.r
			%profiler.r
		]
	]
]

change-dir %build/
MGRAST_preprocessing <<- function(
                                  data_in,     # name of the input file (tab delimited text with the raw counts) or R matrix
                                  data_type             ="file",  # c(file, r_matrix)
                                  output_object         ="default", # output R object (matrix)
                                  output_file           ="default", # output flat file                       
                                  removeSg              = TRUE, # boolean to remove singleton counts
                                  removeSg_valueMin     = 2, # lowest retained value (lower converted to 0)
                                  removeSg_rowMin       = 4, # lowest retained row sum (lower, row is removed)
                                  log_transform         = FALSE,
                                  norm_method           = "DESeq_blind", #c("standardize", "quantile", "DESeq_blind", "DESeq_per_condition", "DESeq_pooled", "DESeq_pooled_CR", "none"), # USE blind if not replicates -- use pooled to get DESeq default
                                  pseudo_count          = 1, # has to be integer for DESeq
                                  DESeq_metadata_table  = NA, # only used if method is other than "blind"
                                  DESeq_metadata_column = 1, # only used if method is other than "blind"
                                  DESeq_metadata_type   = "file",           # c( "file", "r_matrix" )
                                  #DESeq_method          = "blind",  # c( "pooled", "pooled-CR", "per-condition", "blind" ) # blind, treat everything as one group
                                  DESeq_sharingMode     = "maximum",  # c( "maximum", "fit-only", "gene-est-only" ) # maximum is the most conservative choice
                                  DESeq_fitType         = "local",          # c( "parametric", "local" )
                                  DESeq_image           = TRUE, # create dispersion vs mean plot indicate DESeq regression
                                  scale_0_to_1          = FALSE,
                                  produce_boxplots      = FALSE,
                                  boxplot_height_in     = "default", # 11,
                                  boxplot_width_in      = "default", #"8.5,
                                  boxplot_res_dpi       = 300,
                                  create_log            = TRUE,
                                  debug                 = FALSE                                  
                                  )

  {
    
    # check for necessary packages, install if they are not there
    #require(matR) || install.packages("matR", repo="http://mcs.anl.gov/~braithwaite/R", type="source")
    #chooseCRANmirror()
    #setRepositories(ind=1:2)
    source("http://bioconductor.org/biocLite.R")
    require(preprocessCore) || install.packages("preprocessCore")
    #source("http://bioconductor.org/biocLite.R")
    #require(DESeq) || biocLite("DESeq")
    
    require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance 

                                        # (DESeq): www.ncbi.nlm.nih.gov/pubmed/20979621

    #library(preprocessCore)
    #library(DESeq)
    ###### MAIN
    
    # get the name of the data object if an object is used -- use the filename if input is filename string
    if ( identical( data_type, "file") ){
      input_name <- data_in
    }else if( identical( data_type, "r_matrix") ){
      input_name <- deparse(substitute(data_in))
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }    

    # Generate names for the output file and object
    if ( identical( output_object, "default") ){
      output_object <- paste( input_name, ".", norm_method, ".PREPROCESSED" , sep="", collapse="")
    }
    if ( identical( output_file, "default") ){
      output_file <- paste( input_name, ".", norm_method, ".PREPROCESSED.txt" , sep="", collapse="")
    }

    # Input the data
    if ( identical( data_type, "file") ){
      input_data <- data.matrix(read.table(data_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote=""))
    }else if( identical( data_type, "r_matrix") ){
      input_data <- data.matrix(data_in)
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }
    
    # sort the data (COLUMNWISE) by id
    sample_names <- order(colnames(input_data))
    input_data <- input_data[,sample_names]
    
    # make a copy of the input data that is not processed
    input_data.og <- input_data
 
    # non optional, convert "na's" to 0
    input_data[is.na(input_data)] <- 0
    
    # remove singletons
    if(removeSg==TRUE){
      input_data <- remove.singletons(x=input_data, lim.entry=removeSg_valueMin, lim.row=removeSg_rowMin, debug=debug)
    }
    
    # log transform log(x+1)2
    if ( log_transform==TRUE ){
      input_data <- log_data(input_data)
    }

    regression_message <- "DESeq regression:      NA"
    # Normalize -- stadardize or quantile norm (depends on user selection)
    switch(
           norm_method,
           
           standardize={
             input_data <- standardize_data(input_data)
           },

           quantile={
             input_data <- quantile_norm_data(input_data)
           },

           DESeq_blind={
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="blind", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_per_condition={
             stop( cat("The DESeq_per_condition option does not work as it should. DESeq authors advise using the pooled method (DESeq_pooled here) instead.\n
You can accomplish a normalization equivalent to per-condition if you break your data into one matrix per-condition and use the pooled option.
Given that the method athors advise using the pooled methods anyways, I don't plan to fix this unless it is requested. For future reference, it
works up through estimateDispersions(), but fails on varianceStabilizingTransformation().  I can't find examples - and would not be able to debug
quickly"
                       ))
             #if( is.na(DESeq_metadata_table) ){ stop("To DESeq_norm_by_group you must specify a DESeq_metadata_table") }
             #regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             #regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             #input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
             #                              DESeq_metadata_table, DESeq_metadata_column, sample_names,
             #                              DESeq_method="per-condition", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)    
           },
           
           DESeq_pooled={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled you must specify a DESeq_metadata_table") }
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_pooled_CR={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled_CR you must specify a DESeq_metadata_table") }             
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled-CR", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)  
           },
             
           none={
             input_data <- input_data
           },
           {
             stop( paste( norm_method, " is not a valid option for method", sep="", collapse=""))
           }
           )
    
    # scale normalized data [max..min] to [0..1] over the entire dataset 
    if ( scale_0_to_1==TRUE ){
      input_data <- scale_data(input_data)
    }
    
    # create object, with specified name, that contains the preprocessed data
    do.call("<<-",list(output_object, input_data))
 
    # write flat file, with specified name, that contains the preprocessed data
    write.table(input_data, file=output_file, sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")
    
    # produce boxplots
    boxplot_message <- "output boxplot:        NA"
    if ( produce_boxplots==TRUE ) {
      boxplots_file <- paste(input_name, ".boxplots.png", "\n", sep="", collapse="")
      
      if( identical(boxplot_height_in, "default") ){ boxplot_height_in <- 11 }
      if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- round(ncol(input_data)/14) }

      png(
          filename = boxplots_file,
          height = boxplot_height_in,
          width = boxplot_width_in,
          res = boxplot_res_dpi,
          units = 'in'
          )
      plot.new()
      split.screen(c(2,1))
      screen(1)
      graphics::boxplot(input_data.og, main=(paste(input_name," RAW", sep="", collapse="")), las=2, cex.axis=0.5)
      screen(2)
      graphics::boxplot(input_data, main=(paste(input_name," PREPROCESSED (", norm_method, " norm)", sep="", collapse="")),las=2, cex.axis=0.5)
      dev.off()
      boxplot_message <- paste("output boxplot:       ", boxplots_file, "\n", sep="", collapse="")
    }


    # message to send to the user after completion, given names for object and flat file outputs
    #writeLines( paste("Data have been preprocessed. Proprocessed, see ", log_file, " for details", sep="", collapse=""))

    
    if ( create_log==TRUE ){
      # name log file
      log_file <- paste( output_file, ".log", sep="", collapse="")
      # write log
      writeLines(
                 paste(
                       "##############################################################\n",
                       "###################### INPUT PARAMETERS ######################\n",
                       "data_in:               ", data_in, "\n",
                       "data_type:             ", data_type, "\n",
                       "output_object:         ", output_object, "\n",
                       "output_file:           ", output_file, "\n",
                       "removeSg:              ", as.character(removeSg),
                       "removeSg_valueMin:     ", removeSg_valueMin, "\n",
                       "removeSg_rowMin:       ", removeSg_rowMin, "\n",
                       "log_transform          ", as.character(log_transform), "\n",
                       "norm_method:           ", norm_method, "\n",
                       "DESeq_metadata_table:  ", as.character(DESeq_metadata_table), "\n",
                       "DESeq_metadata_column: ", DESeq_metadata_column, "\n",
                       "DESeq_metadata_type:   ", DESeq_metadata_type, "\n",
                       #"DESeq_method:          ", DESeq_method, "\n",
                       "DESeq_sharingMode:     ", DESeq_sharingMode, "\n",
                       "DESeq_fitType:         ", DESeq_fitType, "\n",
                       "scale_0_to_1:          ", as.character(scale_0_to_1), "\n",
                       "produce_boxplots:      ", as.character(produce_boxplots), "\n",
                       "boxplot_height_in:     ", boxplot_height_in, "\n",
                       "boxplot_width_in:      ", boxplot_width_in, "\n",
                       "debug as.character:    ", as.character(debug), "\n",
                       "####################### OUTPUT SUMMARY #######################\n",
                       "output object:         ", output_object, "\n",
                       "otuput file:           ", output_file, "\n",
                       boxplot_message, "\n",
                       regression_message, "\n",
                       "##############################################################",
                       sep="", collapse=""
                       ),
                 con=log_file
                 )
    }


    
  }




######################################################################
######################################################################
### SUBS
######################################################################
######################################################################
    
######################################################################
### Load metadata (for groupings)    
######################################################################
load_metadata <- function(group_table, group_column, sample_names){
  metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                               read.table(
                                          file=group_table,row.names=1,header=TRUE,sep="\t",
                                          colClasses = "character", check.names=FALSE,
                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                          )
                               )
      
  #metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]
  group_names <- metadata_matrix[ order(sample_names), group_column,drop=FALSE ]
  return(group_names)
}
######################################################################

######################################################################
### Sub to remove singletons
######################################################################
remove.singletons <- function (x, lim.entry, lim.row, debug) {
  x <- as.matrix (x)
  x [is.na (x)] <- 0
  x [x < lim.entry] <- 0 # less than limit changed to 0
  #x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # THIS DOES NOT WORK - KEEPS ORIGINAL MATRIX
  x <- x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # row sum equal to or greater than limit is retained
  if (debug==TRUE){write.table(x, file="sg_removed.txt", sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")}
  x  
}
######################################################################

# theMatrixWithoutRow5 = theMatrix[-5,]
# t1 <- t1[-(4:6),-(7:9)]
# mm2 <- mm[mm[,1]!=2,] # delete row if first column is 2
# data[rowSums(is.na(data)) != ncol(data),] # remove rows with any NAs

######################################################################
### Sub to log transform (base two of x+1)
######################################################################
log_data <- function(x, pseudo_count){
  x <- log2(x + pseudo_count)
  x
}
######################################################################

######################################################################
### sub to perform quantile normalization
######################################################################
quantile_norm_data <- function (x, ...){
  data_names <- dimnames(x)
  x <- normalize.quantiles(x)
  dimnames(x) <- data_names
  x
}
######################################################################

######################################################################
### sub to perform standardization
######################################################################
standardize_data <- function (x, ...){
  mu <- matrix(apply(x, 2, mean), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  sigm <- apply(x, 2, sd)
  sigm <- matrix(ifelse(sigm == 0, 1, sigm), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  x <- (x - mu)/sigm
  x
}
######################################################################

######################################################################
### sub to perform DESeq normalization
######################################################################
DESeq_norm_data <- function (x, regression_filename, pseudo_count,
                             DESeq_metadata_table, DESeq_metadata_column, sample_names,
                             DESeq_method, DESeq_sharingMode, DESeq_fitType, DESeq_image, debug, ...){
  # much of the code in this function is adapted/borrowed from two sources
  # Orignal DESeq publication www.ncbi.nlm.nih.gov/pubmed/20979621
  #     also see vignette("DESeq")
  # and Paul J. McMurdie's example analysis in a later paper http://www.ncbi.nlm.nih.gov/pubmed/24699258
  #     with supporing material # http://joey711.github.io/waste-not-supplemental/simulation-cluster-accuracy/simulation-cluster-accuracy-server.html
  if(debug==TRUE)(print("made it here DESeq (1)"))

  # check that pseudo counts are integer - must for DESeq
  if ( all.equal(pseudo_count, as.integer(pseudo_count)) != TRUE ){
    stop(paste("DESeq requires an integer pseudo_count, (", pseudo_count, ") is not an integer" ))
  }

  
  # import metadata matrix (from object or file)
  #if(!is.na(DESeq_metadata_table)){
  #  my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
  #}

  # create metdata for the "blind" case -- all samples treated as if they are in the same group
  if( identical(DESeq_method,"blind") ){
    my_conditions <- as.factor(rep(1,ncol(x)))
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }else{
    my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
    metadata_factors <- as.factor(my_metadata)
    if(debug==TRUE){my_metadata.test<<-my_metadata}
    my_conditions <- metadata_factors
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }

  if(debug==TRUE)(print("made it here DESeq (2)"))
  
  # add pseudocount to prevent workflow from crashing on NaNs - DESeq will crash on non integer counts
  x = x + pseudo_count 
 
  # create dataset object
  if(debug==TRUE){my_conditions.test<<-my_conditions}
  my_dataset <- newCountDataSet( x, my_conditions )
  if(debug==TRUE){my_dataset.test1 <<- my_dataset}
  if(debug==TRUE)(print("made it here DESeq (3)"))
  
  # estimate the size factors
  my_dataset <- estimateSizeFactors(my_dataset)

  if(debug==TRUE)(print("made it here DESeq (4)"))
  if(debug==TRUE){my_dataset.test2 <<- my_dataset}
  
  # estimate dispersions
  # reproduce this: deseq_varstab(physeq, method = "blind", sharingMode = "maximum", fitType = "local")
  #      see https://stat.ethz.ch/pipermail/bioconductor/2012-April/044901.html
  # with DESeq code directly
  # my_dataset <- estimateDispersions(my_dataset, method = "blind", sharingMode = "maximum", fitType="local")
  # but this is what they did in the supplemental material for the DESeq paper (I think) -- and in figure 1 of McMurdie et al.
  #my_dataset <- estimateDispersions(my_dataset, method = "pooled", sharingMode = "fit-only", fitType="local") ### THIS WORKS
  # This is what they suggest in the DESeq vignette for multiple replicats

  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)

  # in the case of per-condition, creates an envrionment called fitInfo
  # ls(my_dataset.test4@fitInfo)

                                        #  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
  
  if(debug==TRUE){my_dataset.test3 <<- my_dataset}

  if(debug==TRUE)(print("made it here DESeq (5)"))
  
  # Determine which column(s) have the dispersion estimates
  dispcol = grep("disp\\_", colnames(fData(my_dataset)))

  # Enforce that there are no infinite values in the dispersion estimates
  #if (any(!is.finite(fData(my_dataset)[, dispcol]))) {
  #  fData(cds)[which(!is.finite(fData(my_dataset)[, dispcol])), dispcol] <- 0
  #}

  if(debug==TRUE)(print("made it here DESeq (6)"))
  
  # apply variance stabilization normalization
  #if ( identical(DESeq_method, "per-condition") ){

  # produce a plot of the regression
  if(DESeq_image==TRUE){
    png(
        filename = regression_filename,
        height = 8.5,
        width = 11,
        res = 300,
        units = 'in'
        )
        #plot.new()    
    plotDispEsts( my_dataset )
    dev.off()
  }

if(debug==TRUE)(print("made it here DESeq (7)"))
  

  
  my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  # ls(my_dataset.test4@fitInfo)
  # my_dataset.test4@fitInfo$Kirsten$fittedDispEsts

  if(debug==TRUE){my_dataset.test4 <<- my_dataset.normed}

  #}else{
   # my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  #}
    








  
  
  # return matrix of normed values
  x <- exprs(my_dataset.normed)
  x

}
######################################################################

######################################################################
### sub to scale dataset values from [min..max] to [0..1]
######################################################################
scale_data <- function(x){
  shift <- min(x, na.rm = TRUE)
  scale <- max(x, na.rm = TRUE) - shift
  if (scale != 0) x <- (x - shift)/scale
  x
}
######################################################################


MGRAST_preprocessing <<- function(
                                  data_in,     # name of the input file (tab delimited text with the raw counts) or R matrix
                                  data_type             ="file",  # c(file, r_matrix)
                                  output_object         ="default", # output R object (matrix)
                                  output_file           ="default", # output flat file                       
                                  removeSg              = TRUE, # boolean to remove singleton counts
                                  removeSg_valueMin     = 2, # lowest retained value (lower converted to 0)
                                  removeSg_rowMin       = 4, # lowest retained row sum (lower, row is removed)
                                  log_transform         = FALSE,
                                  norm_method           = "DESeq_blind", #c("standardize", "quantile", "DESeq_blind", "DESeq_per_condition", "DESeq_pooled", "DESeq_pooled_CR", "none"), # USE blind if not replicates -- use pooled to get DESeq default
                                  pseudo_count          = 1, # has to be integer for DESeq
                                  DESeq_metadata_table  = NA, # only used if method is other than "blind"
                                  DESeq_metadata_column = 1, # only used if method is other than "blind"
                                  DESeq_metadata_type   = "file",           # c( "file", "r_matrix" )
                                  #DESeq_method          = "blind",  # c( "pooled", "pooled-CR", "per-condition", "blind" ) # blind, treat everything as one group
                                  DESeq_sharingMode     = "maximum",  # c( "maximum", "fit-only", "gene-est-only" ) # maximum is the most conservative choice
                                  DESeq_fitType         = "local",          # c( "parametric", "local" )
                                  DESeq_image           = TRUE, # create dispersion vs mean plot indicate DESeq regression
                                  scale_0_to_1          = FALSE,
                                  produce_boxplots      = FALSE,
                                  boxplot_height_in     = "default", # 11,
                                  boxplot_width_in      = "default", #"8.5,
                                  boxplot_res_dpi       = 300,
                                  create_log            = TRUE,
                                  debug                 = FALSE                                  
                                  )

  {
    
    # check for necessary packages, install if they are not there
    #require(matR) || install.packages("matR", repo="http://mcs.anl.gov/~braithwaite/R", type="source")
    #chooseCRANmirror()
    setRepositories(ind=1:2)
    require(preprocessCore) || install.packages("preprocessCore")
    #source("http://bioconductor.org/biocLite.R")
    #require(DESeq) || biocLite("DESeq")
    require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance 

                                        # (DESeq): www.ncbi.nlm.nih.gov/pubmed/20979621

    #library(preprocessCore)
    #library(DESeq)
    ###### MAIN
    
    # get the name of the data object if an object is used -- use the filename if input is filename string
    if ( identical( data_type, "file") ){
      input_name <- data_in
    }else if( identical( data_type, "r_matrix") ){
      input_name <- deparse(substitute(data_in))
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }    

    # Generate names for the output file and object
    if ( identical( output_object, "default") ){
      output_object <- paste( input_name, ".", norm_method, ".PREPROCESSED" , sep="", collapse="")
    }
    if ( identical( output_file, "default") ){
      output_file <- paste( input_name, ".", norm_method, ".PREPROCESSED.txt" , sep="", collapse="")
    }

    # Input the data
    if ( identical( data_type, "file") ){
      input_data <- data.matrix(read.table(data_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote=""))
    }else if( identical( data_type, "r_matrix") ){
      input_data <- data.matrix(data_in)
    }else{
      stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
    }
    
    # sort the data (COLUMNWISE) by id
    sample_names <- order(colnames(input_data))
    input_data <- input_data[,sample_names]
    
    # make a copy of the input data that is not processed
    input_data.og <- input_data
 
    # non optional, convert "na's" to 0
    input_data[is.na(input_data)] <- 0
    
    # remove singletons
    if(removeSg==TRUE){
      input_data <- remove.singletons(x=input_data, lim.entry=removeSg_valueMin, lim.row=removeSg_rowMin, debug=debug)
    }
    
    # log transform log(x+1)2
    if ( log_transform==TRUE ){
      input_data <- log_data(input_data)
    }

    regression_message <- "DESeq regression:      NA"
    # Normalize -- stadardize or quantile norm (depends on user selection)
    switch(
           norm_method,
           
           standardize={
             input_data <- standardize_data(input_data)
           },

           quantile={
             input_data <- quantile_norm_data(input_data)
           },

           DESeq_blind={
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="blind", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_per_condition={
             stop( cat("The DESeq_per_condition option does not work as it should. DESeq authors advise using the pooled method (DESeq_pooled here) instead.\n
You can accomplish a normalization equivalent to per-condition if you break your data into one matrix per-condition and use the pooled option.
Given that the method athors advise using the pooled methods anyways, I don't plan to fix this unless it is requested. For future reference, it
works up through estimateDispersions(), but fails on varianceStabilizingTransformation().  I can't find examples - and would not be able to debug
quickly"
                       ))
             #if( is.na(DESeq_metadata_table) ){ stop("To DESeq_norm_by_group you must specify a DESeq_metadata_table") }
             #regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             #regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             #input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
             #                              DESeq_metadata_table, DESeq_metadata_column, sample_names,
             #                              DESeq_method="per-condition", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)    
           },
           
           DESeq_pooled={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled you must specify a DESeq_metadata_table") }
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
           },

           DESeq_pooled_CR={
             if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled_CR you must specify a DESeq_metadata_table") }             
             regression_filename = paste(  input_name, ".DESeq_regression.png", sep="", collapse="" )
             regression_message <- paste("DESeq regression:      ", regression_filename, sep="", collapse="" )
             input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
                                           DESeq_metadata_table, DESeq_metadata_column, sample_names,
                                           DESeq_method="pooled-CR", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)  
           },
             
           none={
             input_data <- input_data
           },
           {
             stop( paste( norm_method, " is not a valid option for method", sep="", collapse=""))
           }
           )
    
    # scale normalized data [max..min] to [0..1] over the entire dataset 
    if ( scale_0_to_1==TRUE ){
      input_data <- scale_data(input_data)
    }
    
    # create object, with specified name, that contains the preprocessed data
    do.call("<<-",list(output_object, input_data))
 
    # write flat file, with specified name, that contains the preprocessed data
    write.table(input_data, file=output_file, sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")
    
    # produce boxplots
    boxplot_message <- "output boxplot:        NA"
    if ( produce_boxplots==TRUE ) {
      boxplots_file <- paste(input_name, ".boxplots.png", "\n", sep="", collapse="")
      
      if( identical(boxplot_height_in, "default") ){ boxplot_height_in <- 11 }
      if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- round(ncol(input_data)/14) }

      png(
          filename = boxplots_file,
          height = boxplot_height_in,
          width = boxplot_width_in,
          res = boxplot_res_dpi,
          units = 'in'
          )
      plot.new()
      split.screen(c(2,1))
      screen(1)
      graphics::boxplot(input_data.og, main=(paste(input_name," RAW", sep="", collapse="")), las=2, cex.axis=0.5)
      screen(2)
      graphics::boxplot(input_data, main=(paste(input_name," PREPROCESSED (", norm_method, " norm)", sep="", collapse="")),las=2, cex.axis=0.5)
      dev.off()
      boxplot_message <- paste("output boxplot:       ", boxplots_file, "\n", sep="", collapse="")
    }


    # message to send to the user after completion, given names for object and flat file outputs
    #writeLines( paste("Data have been preprocessed. Proprocessed, see ", log_file, " for details", sep="", collapse=""))

    
    if ( create_log==TRUE ){
      # name log file
      log_file <- paste( output_file, ".log", sep="", collapse="")
      # write log
      writeLines(
                 paste(
                       "##############################################################\n",
                       "###################### INPUT PARAMETERS ######################\n",
                       "data_in:               ", data_in, "\n",
                       "data_type:             ", data_type, "\n",
                       "output_object:         ", output_object, "\n",
                       "output_file:           ", output_file, "\n",
                       "removeSg:              ", as.character(removeSg),
                       "removeSg_valueMin:     ", removeSg_valueMin, "\n",
                       "removeSg_rowMin:       ", removeSg_rowMin, "\n",
                       "log_transform          ", as.character(log_transform), "\n",
                       "norm_method:           ", norm_method, "\n",
                       "DESeq_metadata_table:  ", as.character(DESeq_metadata_table), "\n",
                       "DESeq_metadata_column: ", DESeq_metadata_column, "\n",
                       "DESeq_metadata_type:   ", DESeq_metadata_type, "\n",
                       #"DESeq_method:          ", DESeq_method, "\n",
                       "DESeq_sharingMode:     ", DESeq_sharingMode, "\n",
                       "DESeq_fitType:         ", DESeq_fitType, "\n",
                       "scale_0_to_1:          ", as.character(scale_0_to_1), "\n",
                       "produce_boxplots:      ", as.character(produce_boxplots), "\n",
                       "boxplot_height_in:     ", boxplot_height_in, "\n",
                       "boxplot_width_in:      ", boxplot_width_in, "\n",
                       "debug as.character:    ", as.character(debug), "\n",
                       "####################### OUTPUT SUMMARY #######################\n",
                       "output object:         ", output_object, "\n",
                       "otuput file:           ", output_file, "\n",
                       boxplot_message, "\n",
                       regression_message, "\n",
                       "##############################################################",
                       sep="", collapse=""
                       ),
                 con=log_file
                 )
    }


    
  }




######################################################################
######################################################################
### SUBS
######################################################################
######################################################################
    
######################################################################
### Load metadata (for groupings)    
######################################################################
load_metadata <- function(group_table, group_column, sample_names){
  metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                               read.table(
                                          file=group_table,row.names=1,header=TRUE,sep="\t",
                                          colClasses = "character", check.names=FALSE,
                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                          )
                               )
      
  #metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]
  group_names <- metadata_matrix[ order(sample_names), group_column,drop=FALSE ]
  return(group_names)
}
######################################################################

######################################################################
### Sub to remove singletons
######################################################################
remove.singletons <- function (x, lim.entry, lim.row, debug) {
  x <- as.matrix (x)
  x [is.na (x)] <- 0
  x [x < lim.entry] <- 0 # less than limit changed to 0
  #x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # THIS DOES NOT WORK - KEEPS ORIGINAL MATRIX
  x <- x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # row sum equal to or greater than limit is retained
  if (debug==TRUE){write.table(x, file="sg_removed.txt", sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")}
  x  
}
######################################################################

# theMatrixWithoutRow5 = theMatrix[-5,]
# t1 <- t1[-(4:6),-(7:9)]
# mm2 <- mm[mm[,1]!=2,] # delete row if first column is 2
# data[rowSums(is.na(data)) != ncol(data),] # remove rows with any NAs

######################################################################
### Sub to log transform (base two of x+1)
######################################################################
log_data <- function(x, pseudo_count){
  x <- log2(x + pseudo_count)
  x
}
######################################################################

######################################################################
### sub to perform quantile normalization
######################################################################
quantile_norm_data <- function (x, ...){
  data_names <- dimnames(x)
  x <- normalize.quantiles(x)
  dimnames(x) <- data_names
  x
}
######################################################################

######################################################################
### sub to perform standardization
######################################################################
standardize_data <- function (x, ...){
  mu <- matrix(apply(x, 2, mean), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  sigm <- apply(x, 2, sd)
  sigm <- matrix(ifelse(sigm == 0, 1, sigm), nr = nrow(x), nc = ncol(x), byrow = TRUE)
  x <- (x - mu)/sigm
  x
}
######################################################################

######################################################################
### sub to perform DESeq normalization
######################################################################
DESeq_norm_data <- function (x, regression_filename, pseudo_count,
                             DESeq_metadata_table, DESeq_metadata_column, sample_names,
                             DESeq_method, DESeq_sharingMode, DESeq_fitType, DESeq_image, debug, ...){
  # much of the code in this function is adapted/borrowed from two sources
  # Orignal DESeq publication www.ncbi.nlm.nih.gov/pubmed/20979621
  #     also see vignette("DESeq")
  # and Paul J. McMurdie's example analysis in a later paper http://www.ncbi.nlm.nih.gov/pubmed/24699258
  #     with supporing material # http://joey711.github.io/waste-not-supplemental/simulation-cluster-accuracy/simulation-cluster-accuracy-server.html
  if(debug==TRUE)(print("made it here DESeq (1)"))

  # check that pseudo counts are integer - must for DESeq
  if ( all.equal(pseudo_count, as.integer(pseudo_count)) != TRUE ){
    stop(paste("DESeq requires an integer pseudo_count, (", pseudo_count, ") is not an integer" ))
  }

  
  # import metadata matrix (from object or file)
  #if(!is.na(DESeq_metadata_table)){
  #  my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
  #}

  # create metdata for the "blind" case -- all samples treated as if they are in the same group
  if( identical(DESeq_method,"blind") ){
    my_conditions <- as.factor(rep(1,ncol(x)))
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }else{
    my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
    metadata_factors <- as.factor(my_metadata)
    if(debug==TRUE){my_metadata.test<<-my_metadata}
    my_conditions <- metadata_factors
    if(debug==TRUE){my_conditions.test<<-my_conditions}
  }

  if(debug==TRUE)(print("made it here DESeq (2)"))
  
  # add pseudocount to prevent workflow from crashing on NaNs - DESeq will crash on non integer counts
  x = x + pseudo_count 
 
  # create dataset object
  if(debug==TRUE){my_conditions.test<<-my_conditions}
  my_dataset <- newCountDataSet( x, my_conditions )
  if(debug==TRUE){my_dataset.test1 <<- my_dataset}
  if(debug==TRUE)(print("made it here DESeq (3)"))
  
  # estimate the size factors
  my_dataset <- estimateSizeFactors(my_dataset)

  if(debug==TRUE)(print("made it here DESeq (4)"))
  if(debug==TRUE){my_dataset.test2 <<- my_dataset}
  
  # estimate dispersions
  # reproduce this: deseq_varstab(physeq, method = "blind", sharingMode = "maximum", fitType = "local")
  #      see https://stat.ethz.ch/pipermail/bioconductor/2012-April/044901.html
  # with DESeq code directly
  # my_dataset <- estimateDispersions(my_dataset, method = "blind", sharingMode = "maximum", fitType="local")
  # but this is what they did in the supplemental material for the DESeq paper (I think) -- and in figure 1 of McMurdie et al.
  #my_dataset <- estimateDispersions(my_dataset, method = "pooled", sharingMode = "fit-only", fitType="local") ### THIS WORKS
  # This is what they suggest in the DESeq vignette for multiple replicats

  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)

  # in the case of per-condition, creates an envrionment called fitInfo
  # ls(my_dataset.test4@fitInfo)

                                        #  my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
  
  if(debug==TRUE){my_dataset.test3 <<- my_dataset}

  if(debug==TRUE)(print("made it here DESeq (5)"))
  
  # Determine which column(s) have the dispersion estimates
  dispcol = grep("disp\\_", colnames(fData(my_dataset)))

  # Enforce that there are no infinite values in the dispersion estimates
  #if (any(!is.finite(fData(my_dataset)[, dispcol]))) {
  #  fData(cds)[which(!is.finite(fData(my_dataset)[, dispcol])), dispcol] <- 0
  #}

  if(debug==TRUE)(print("made it here DESeq (6)"))
  
  # apply variance stabilization normalization
  #if ( identical(DESeq_method, "per-condition") ){

  # produce a plot of the regression
  if(DESeq_image==TRUE){
    png(
        filename = regression_filename,
        height = 8.5,
        width = 11,
        res = 300,
        units = 'in'
        )
        #plot.new()    
    plotDispEsts( my_dataset )
    dev.off()
  }

if(debug==TRUE)(print("made it here DESeq (7)"))
  

  
  my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  # ls(my_dataset.test4@fitInfo)
  # my_dataset.test4@fitInfo$Kirsten$fittedDispEsts

  if(debug==TRUE){my_dataset.test4 <<- my_dataset.normed}

  #}else{
   # my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
  #}
    








  
  
  # return matrix of normed values
  x <- exprs(my_dataset.normed)
  x

}
######################################################################

######################################################################
### sub to scale dataset values from [min..max] to [0..1]
######################################################################
scale_data <- function(x){
  shift <- min(x, na.rm = TRUE)
  scale <- max(x, na.rm = TRUE) - shift
  if (scale != 0) x <- (x - shift)/scale
  x
}
######################################################################


#' Load a bunch of dependencies by filename
#'
#' @name load_dependency
#' @param dep Name of dependency, e.g., relative filename (without .r)
#' @examples
#' \dontrun{
#'   helper <- load_dependency('path/to/helper')
#' }
load_dependency <- function(dep) {
  path <- suppressWarnings(base::normalizePath(file.path(current_directory(), dep)))
  if (!file.exists(path)) {
    new_path <- paste(path, '.r', sep = '')
    if (!file.exists(new_path)) new_path <- paste(path, '.R', sep = '')
    path <- new_path
  }
  if (!file.exists(path))
    stop(paste("Unable to load dependency '", dep, "'", sep = ''))
  fileinfo <- file.info(path)
  mtime <- fileinfo$mtime

  value <- NULL
  
  if (path %in% get_src_cache_names() &&
      mtime == (cache_hit = get_src_cache(path))$mtime)
    value <- cache_hit$value
  else {
    # We fetch "source" from the global environment to allow other packages
    # to inject around sourcing files and be compatible with Ramd.
    value <- get('source', globalenv())(path)$value
    set_src_cache(list(value = value, mtime = mtime), path)
  }
  invisible(value)
}
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="thresher")
rs <- dbSendQuery(con, 'select T.id as tua_id, T.offsets as tua_offsets, A.text as article_text, A.city_published as city, A.date_published as date, A.article_id, A.periodical_code, A.annotators as annotators, TT.name as tua_type from thresher_tua T, thresher_article A, thresher_analysistype TT where T.article_id = A.article_id and T.analysis_type_id = TT.id;')
data <- fetch(rs, n=-1)
write.csv(data, file = "tua_data.csv", fileEncoding = "UTF-8")#Topic Model script
#Much of this initial workflow is from Jockers Text Analysis for R 
#and Shawn Graham's Ferguson Grand Jury corpus topic model at https://github.com/shawngraham/ferguson
library(mallet)
library(wordcloud)
library(dplyr)
library(tm)
library(Hmisc)

# import the OCR'd ICC decisions from the text folder
# each decision is here its own text file
#decisions <- mallet.read.dir("text") 

#Better is to use load.r file to provide cleaner texts via get_real_words function, etc

mallet.instances <- mallet.import(decisions$id, decisions$text, "icc.txt", token.regexp = "\\p{L}[\\p{L}\\p{P}]+\\p{L}")

#' create topic trainer object
n.topics <- 100
topic.model <- MalletLDA(n.topics)

#' load documents
topic.model$loadDocuments(mallet.instances)

## Get the vocabulary, and some statistics about word frequencies.
## These may be useful in further curating the stopword list.
vocabulary <- topic.model$getVocabulary()
word.freqs <- mallet.word.freqs(topic.model)
#Get additional words for stoplist
#stopwords<- arrange(word.freqs, words, term.freq)
#rank(stopwords)



## Optimize hyperparameters every 20 iterations,
## after 50 burn-in iterations.
topic.model$setAlphaOptimization(20, 50)

## Now train a model. Note that hyperparameter optimization is on, by default.
## We can specify the number of iterations. Here we'll use a large-ish round number.
topic.model$train(400)

## NEW: run through a few iterations where we pick the best topic for each token,
## rather than sampling from the posterior distribution.
topic.model$maximize(40)

#' Get the probability of topics in documents and the probability of words in topics.
#' By default, these functions return raw word counts. Here we want probabilities,
#' so we normalize, and add "smoothing" so that nothing has exactly 0 probability.
doc.topics <- mallet.doc.topics(topic.model, smoothed=T, normalized=T)
topic.words <- mallet.topic.words(topic.model, smoothed=T, normalized=T)  ##adap jockers wordcloud script to use this variable

#' from http://www.cs.princeton.edu/~mimno/R/clustertrees.R
#' transpose and normalize the doc topics
topic.docs <- t(doc.topics)
topic.docs <- topic.docs / rowSums(topic.docs)

#Get shorter versions of the topics
topics.labels <- rep("", n.topics)
for (topic in 1:n.topics) topics.labels[topic] <- paste(mallet.top.words(topic.model, topic.words[topic,], num.top.words=7)$words, collapse=" ")


#output some of the topic model raw data
write.csv(topic.docs, "out/icc-topic-docs.csv") 
write.csv(topics.labels, "out/icc-topic-labels.csv") 

# create data.frame with columns as ids and rows as topics
topic_docs <- data.frame(topic.docs)
plotdocs <- names(topic_docs) 
names(topic_docs) <- decisions$id

## cluster based on shared words
plot(hclust(dist(topic.words)), labels=topics.labels)

#' Calculate similarity matrix
#' Shows which documents are similar to each other
#' by their proportions of topics. Based on Matt Jockers' method

library(cluster)
topic_df_dist <- as.matrix(daisy(t(topic_docs), metric = "euclidean", stand = TRUE))
# Change row values to zero if less than row minimum plus row standard deviation
# keep only closely related documents and avoid a dense spagetti diagram
# that's difficult to interpret (hat-tip: http://stackoverflow.com/a/16047196/1036500)
topic_df_dist[ sweep(topic_df_dist, 1, (apply(topic_df_dist,1,min) + apply(topic_df_dist,1,sd) )) > 0 ] <- 0

#' Use kmeans to identify groups of similar authors

km <- kmeans(topic_df_dist, n.topics)
# get names for each cluster
allnames <- vector("list", length = n.topics)
for(i in 1:n.topics){
  allnames[[i]] <- names(km$cluster[km$cluster == i])
}

#Shawn Graham's topics as wordclouds with some of Jockers print to pdf code
pdf(file="icc-topics.pdf")
for(i in 1:40){
  topic.top.words <- mallet.top.words(topic.model,
                                      topic.words[i,], 15)
  print(wordcloud(topic.top.words$words,
                  topic.top.words$weights,
                  c(4,.8), rot.per=0,
                  random.order=F))
  
}
dev.off()

#create some plots of topics across the range of decisions
library(ggplot2)
library(tidyr)
pdf(file="icc-topics-across-docs.pdf")
cols <- 1:2502
doc_topics <- data.frame(doc.topics, row.names = decisions$id, stringsAsFactors = FALSE)
doc_topics$docs <- cols

topic.cols <- names(doc_topics)

for(i in 1:100){
print(ggplot(doc_topics) + geom_smooth(aes_string(x="docs", y=(topic.cols[i]))))

}  
dev.off()

ggplot(doc_topics, aes(x=docs, y=X30)) + geom_smooth() + geom_line()
#load and parse html tables

#load libraries
library(stringr)
library(stringi)
library(XML)
library(dplyr)
library(magrittr)

#Loads all the html tables into one list
table_dir <- "table"
files <- dir(table_dir, "*.html")
tbls <- file.path(table_dir, files) 
tbls <- lapply(tbls, htmlParse) %>%
  lapply(., readHTMLTable, head = FALSE, stringsAsFactors = FALSE, which = 1) %>%
  lapply(., )

#Currently This code isn't necessary #/
#According to Hadley Wickham, creating an empty dataset and populating it is drastically faster in R
"tbl.df <- data.frame((character(length = length(tbls))), stringsAsFactors = FALSE)

#iterate through the list of tables and parse the html structure
i <- 1
for(i in 1:length(tbls)){
  
  i.df <- readHTMLTable(tbls[i], head = FALSE, stringsAsFactors = FALSE)
  tbl.df <- cbind(tbl.df, i.df)

}

readHTMLTable(tbls[1])


stopwords <- unique(tbls)
"
#Parse a sample table, this is the path
doc <-"table/v02toc.html"

#Pull in html files
p <- htmlParse(doc)

 

#iccv02toc.df <- xmlToDataFrame(p, collectNames = FALSE, stringsAsFactors = FALSE, nodes= iccv02toc[4] )

iccv02toc <- readHTMLTable(p, header = FALSE, stringsAsFactors = FALSE)

#Turn the HtmlInternalDocument into a data.frame
iccv02toc.df <- as.data.frame(iccv02toc[4], stringsAsFactors = FALSE)

#Use dplyr to munge the data from 3 columns of information into several columns of information
#First is to move plaintiff tribe into a separate column.
#iccv02toc.df$table1.V2 <- str_replace_all(iccv02toc.df$table1.V2, "[\t]", "")

v02tocfinal.df <- mutate(iccv02toc.df, tribe = str_extract(iccv02toc.df$table1.V2, ".*\r\n"))
v02tocfinal.df <- mutate(v02tocfinal.df, page1 = str_extract(v02tocfinal.df$table1.V3, ".*\r\n"))



str(iccv02toc)
write.csv(iccv02toc[4], file = "out/iccv02toc.csv")
#' @name tundra_container
#' @title tundra_container
#' @export
NULL

#' Tundra container class
#'
#' TODO: Formally define parameter spaces for models
#' 
#' @docType class
#' @name tundraContainer
#' @aliases NULL
#' @export
tundra_container <- setRefClass('tundraContainer',  #define reference classes to access by reference instead of by value
  fields = list(keyword = 'character',
                train_fn = 'function',
                predict_fn = 'function',
                munge_procedure = 'list',  # tundra contains munge_procedure so that it remembers the data-prep steps
                default_args = 'list',
                trained = 'logical',
                input = 'list',
                output = 'ANY',    # output stores the actual output of the train function (e.g. the model object)
                internal = 'list', # for storing info about the model
                hooks = 'list'),
  methods = list(
    initialize = function(keyword = character(0),
                          train_fn = identity, predict_fn = identity,
                          munge_procedure = list(),
                          default_args = list(),
                          internal = list()) {
      keyword <<- keyword
      train_fn <<- train_fn
      predict_fn <<- predict_fn
      munge_procedure <<- munge_procedure
      default_args <<- default_args
      internal <<- internal
      trained <<- FALSE
    },

    train = function(dataframe, train_args = list(), verbose = FALSE, munge = TRUE) {
      if (trained)
        stop("Tundra model '", keyword, "' has already been trained.")

      force(train_args); force(verbose); force(munge) 

      .run_hooks('train_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        triggers <- unlist(lapply(munge_procedure,
                              function(x) inherits(x, 'trigger')))
        
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe

        # Store trained munge_procedure
        munge_procedure <<- attr(dataframe, 'mungepieces')[!triggers]

        # reset mungepieces to NULL after training
        attr(dataframe, 'mungepieces') <- NULL
      }

      run_env <- new.env(parent = old_env <- environment(train_fn))
      on.exit(environment(train_fn) <<- old_env)
      input <<- append(train_args, default_args)
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(train_fn)
      environment(train_fn) <<- run_env
      if (debug_flag) debug(train_fn)

      .run_hooks('train_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <- train_fn(dataframe))           # Apply train function to dataframe

      input <<- run_env$input; output <<- run_env$output
      trained <<- TRUE
      res 
    },

    predict = function(dataframe, predict_args = list(), verbose = FALSE, munge = TRUE) {
      if (!trained)
        stop("Tundra model '", keyword, "' has not been trained yet.")

      force(verbose); force(munge); force(predict_args)

      .run_hooks('predict_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        initial_nrow <- nrow(dataframe)
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe
        if (nrow(dataframe) != initial_nrow)
          warning(paste("Some rows were removed during data preparation.",
                        "Predictions will not match input dataframe."))

      }

      run_env <- new.env(parent = globalenv())
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(predict_fn)
      environment(predict_fn) <<- run_env
      if (debug_flag) debug(predict_fn)

      .run_hooks('predict_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <-
          if (length(formals(predict_fn)) < 2 || missing(predict_args)) {
            predict_fn(dataframe)
          } else { predict_fn(dataframe, predict_args) }
      )
      input <<- run_env$input; output <<- run_env$output
      res
    },
    
    munge = function(dataframe, steps = TRUE) {
      mungebits::munge(dataframe, munge_procedure[steps]) 
    },

    show = function() {
      cat(paste("A tundraContainer of type", sQuote(keyword)), "\n")
    },

    add_hook = function(type, hook_function) {
      stopifnot(is.character(type) && length(type) == 1)
      stopifnot(is.function(hook_function))
      allowed_types <- paste0(as.character(outer(
        c('train', 'predict'), c('pre', 'post'), paste, sep = '_')), '_munge')
      if (!is.element(type, allowed_types)) {
        stop("Tundra container hooks must be one of: ",
             paste(allowed_types, collapse = ", "))
      }

      hooks[[type]] <<- c(hooks[[type]], hook_function)
    },

    .run_hooks = function(type) {
      for (i in seq_along(hooks[[type]])) {
        eval.parent(bquote({
          `*fn*` <- hooks[[.(type)]][[.(i)]]
          environment(`*fn*`) <- environment()
          `*fn*`()
        }))
      }
    }
  )
)

#' @export
summary.tundraContainer <- function(x, ...) summary(x$output$model, ...)
#' @export
print.tundraContainer <-
  function(x, ...) print(paste("A tundraContainer of type", sQuote(x$keyword)), ...)

library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # consider coords (r,c)
  start_r <- coords[1]
  start_c <- coords[2]
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 
  
  # if caption, start the table one row lower
  if (add.caption) { start_r <- start_r + 1 }
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = start_c, startRow = start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "surrounding")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is one above start_r 
    comment_r <- start_r - 1
    writeData(
      wb = wb, sheet = sheet, startCol = start_c, startRow = comment_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    comment_merge_width <- ifelse(7 - start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = start_c:comment_merge_width, 
               rows = comment_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen rownames zijn?
    row_margin_c <- 1 + ncol(tabular) + 1
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  if (add.col.margin) {
    col.margin.contents <- t(rep(100, ncol(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen colnames zijn?
    col_margin_c <- start_c + 1
    col_margin_r <- 1 + nrow(tabular) + 1
    
    writeData(
      wb = wb, sheet = sheet, startCol = col_margin_c, startRow = col_margin_r,
      x = col.margin.contents, rowNames=FALSE, colNames=FALSE)  
     
  } 
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
library(openxlsx)


# GENERAL AND HELPER FUNCTIONS #
# ============================ #


# basis-elementen die rondom de data geplaatst worden
#
# * caption       # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.comment=FALSE, 
                               add.row.margin=FALSE, add.col.margin=FALSE,
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # consider coords (r,c)
  start_r <- coords[1]
  start_c <- coords[2]
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 
  
  # if caption, start the table one row lower
  if (add.caption) { start_r <- start_r + 1 }
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = start_c, startRow = start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "surrounding")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is one above start_r 
    comment_r <- start_r - 1
    writeData(
      wb = wb, sheet = sheet, startCol = start_c, startRow = comment_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    comment_merge_width <- ifelse(7 - start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = start_c:comment_merge_width, 
               rows = comment_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  if (add.row.margin) {
    row.margin.contents <- t(rep(100, nrow(tabular))) # TODO, parametriseer
    
    # TODO: ook mogelijk maken dat er geen rownames zijn?
    row_margin_c <- 1 + ncol(tabular) + 1
    
    for (i in 1:length(row.margin.contents)) {
      writeData(
        wb = wb, sheet = sheet, startCol = row_margin_c, startRow = start_r+i,
        x = row.margin.contents[i], rowNames=FALSE, colNames=FALSE)  
    }
    
    
  }
  
  #   row.margin.name
  #   col.margin.name
  #   
  #   margin.table(tab)
  
  
  # if comment, add additional row with comment
  # -------------------------------------------
  
  
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}


print.tabulars.xlsx <- function(wb, sheet, tabulars, start_c=1) {
  # todo: specify by sheet index or name

  for (tabular in tabulars) {
    
    # check the last 
    previous_r <- last_filled_row(wb, sheet)
    
    if (previous_r == 0) { 
      start_r <- 1
    }else {
      start_r <- previous_r + 2
    }    
    
    coords <- c(start_r, start_c)
    print.tabular.xlsx(wb, sheet, coords, tabular) # modify in place!
    #openXL(wb)
  }
  
  wb
  
}


#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 
source('table_export_openxlsx.r')


# BASIC EXAMPLES #
# ============== #

d <- as.data.frame(Titanic)
tab1 <- table(d$Class, d$Sex)
tab2 <- table(d$Class, d$Survived)
tab3 <- table(d$Sex, d$Survived)


# write single table
# ------------------

wb <- createWorkbook()
addWorksheet(wb = wb, sheetName = 'OR_tables')

wb <- print.tabular.xlsx(wb, 1, c(1,1), tab1)
openXL(wb)


# write multiple tables
# ---------------------

wb <- createWorkbook()
addWorksheet(wb = wb, sheetName = 'OR_tables')

wb <- print.tabulars.xlsx(wb, 1, list(tab1) )
#wb <- print.tabulars.xlsx(wb, 1, list(tab1, tab2, tab3) )
# Error in .self$updateCellStyles(sheet = r$sheet, rows = r$rows, cols = r$cols,  : 
#                                   CHAR() can only be applied to a 'CHARSXP', not a 'NULL'
openXL(wb)




# EXAMPLES: OR TABELLEN # 
# ===================== #

wd <- getwd()
setwd('C:/Users/MaartenH/Documents/work/HIVA/acv_or')
load('rapportering/descr_tables.RData')
setwd(wd)
rm(wd)


# General styling
# ---------------

# make custom table header style
hs1 <- createStyle(fgFill = "#DCE6F1", halign = "CENTER", 
                   textDecoration = "Italic", border = "Bottom")

# stel algemene stijlelementen in
options("openxlsx.borderColour" = "#4F80BD")
options("openxlsx.borderStyle" = "thin")


# Setup workbook, sheet
# ---------------------

wb <- createWorkbook()
addWorksheet(wb = wb, sheetName = 'OR_tables')
setColWidths(wb, sheet = 1, cols=1:30, widths = "auto") # set cols to automatically resize

# write multiple tables in single sheet
# -------------------------------------

# Table 1: cbind()'ed table

tab1 <- as.data.frame(t.wg.centrale) # omzetten naar dataframe
#class(tab1[,3] ) <- "percentage"

# Table 2: svytable()
tab2 <- as.data.frame.matrix(t.hhr.centrale)

wb <- print.tabulars.xlsx(wb, 1, list(tab1, tab2))
openXL(wb) # toon excel bestand zonder weg te schrijven

saveWorkbook(wb, "OR1_descr_tables.xlsx", overwrite = TRUE)



# writeData(wb = wb, sheet = sheet_name, x = tab, xy=coords,
#           borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")
# writeData(wb = wb, 
#           sheet = sheet_name, x = tab, 
#           xy=coords,
#           borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")

library(openxlsx)

wd <- getwd()
setwd('C:/Users/MaartenH/Documents/work/HIVA/acv_or')
load('rapportering/descr_tables.RData')
setwd(wd)
rm(wd)

#write.xlsx(t.wg.centrale, file = "writeXLSXTable1.xlsx", asTable = TRUE) # error, geen data.frame

# options: simple data, or automatically formatedd as a table
# write.xlsx(tab, file = "OR1_descr_tables.xlsx", asTable = TRUE, # issue, "row.name"s als colname
#            col.names=TRUE, row.names=TRUE) 


# General styling
# ---------------

# make custom table header style
hs1 <- createStyle(fgFill = "#DCE6F1", halign = "CENTER", 
                   textDecoration = "Italic", border = "Bottom")

# stel algemene stijlelementen in
options("openxlsx.borderColour" = "#4F80BD")
options("openxlsx.borderStyle" = "thin")


# Setup workbook, sheet
# ---------------------

wb <- createWorkbook()
sheet_name <- 'OR_tables'
addWorksheet(wb = wb, sheetName = sheet_name)
setColWidths(wb, sheet = 1, cols=1:100, widths = "auto") # set cols to automatically resize

# write multiple tables in single sheet
# -------------------------------------

# Table 1: cbind()'ed table

tab <- as.data.frame(t.wg.centrale) # omzetten naar dataframe
class(tab[,3] ) <- "percentage"
  
coords <- c(1,1)
writeData(wb = wb, sheet = sheet_name, x = tab, xy=coords,
          borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")

# Table 2: svytable()

tab <- as.data.frame.matrix(t.hhr.centrale)

coords <- c(1,nrow(tab) + 3) # hoogte tab 1 + 3 rows => 1 spatie
writeData(wb = wb, 
          sheet = sheet_name, x = tab, 
          xy=coords,
          borders = "surrounding", rowNames=TRUE, headerStyle = hs1, borderStyle = "dashed")


openXL(wb) # toon excel bestand zonder weg te schrijven

saveWorkbook(wb, "OR1_descr_tables.xlsx", overwrite = TRUE)

# TODO wat is een header/footer?



# basis-elementen die rondom de data geplaatst worden
#
# * caption   	  # col onder of boven toevoegen, spanning?
# * row.margin 		# col rechts toevoegen
# * col.margin 		# row onder toevoegen
# * comment			  # row onder toevoegen [italic?)

print.tabular.xlsx <- function(wb, sheet, coords, tabular, 
                               add.caption=FALSE, add.row.margin=FALSE, add.col.margin=FALSE, add.comment=FALSE, 
                               style=None) {
  
  # make sure the object is a data.frame, convert if needed
  # -------------------------------------------------------
  
  if ('matrix' %in% class(tabular) ) { tabular <- as.data.frame(tabular) }
  if ('svytable' %in% class(tabular)) { tabular <- as.data.frame.matrix(tabular) }
  
  # consider coords (r,c)
  start_r <- coords[2]
  start_c <- coords[1]
  
  n_data_rows <- nrow(tabular)
  n_data_cols <- ncol(tabular)
  #n_total_cols <- 
  #n_total_rows <- 

  # if caption, start the table one row lower
  if (add.caption) { start_r <- start_r + 1 }
  
  # write out data rows/cols, including row & col names
  # ---------------------------------------------------
  
  writeData(
    wb = wb, sheet = sheet, startCol = start_c, startRow = start_r,
    x = tabular, rowNames=TRUE, colNames=TRUE,
    borders = "surrounding")
  
  
  # add caption-row and caption (on top by default)
  # -----------------------------------------------
  
  if (add.caption) {
    caption_text <- 'Table 1: This is a very long static table caption that needs to be fixed with a variable input (in %)'
    
    # add row contents
    # ----------------
    
    # row for comment is one above start_r 
    comment_r <- start_r - 1
    writeData(
      wb = wb, sheet = sheet, startCol = start_c, startRow = comment_r,
      x = caption_text, rowNames=FALSE, colNames=FALSE)
    
    # for caption, merge the cells to span multiple cols, either width table, or 
    # some minimum nr. of cols
    
    comment_merge_width <- ifelse(7 - start_c >= 6, 6)
    mergeCells(wb, sheet=sheet, 
               cols = start_c:comment_merge_width, 
               rows = comment_r)
    
    # TODO: auto col width should not be affected
    # cf. https://github.com/awalker89/openxlsx/issues/43
    
  }
  

  
  
  # if margins, add row/and or col margin
  # -------------------------------------
  
  row.margin.name
  col.margin.name
  
  margin.table(tab)
    
  # if comment, add additional row with comment
  # -------------------------------------------
  
    
  
  # return wb (save if filename?)
  # -----------------------------
  wb
  
}




wb <- createWorkbook()
sheet_name <- 'OR_tables'
addWorksheet(wb = wb, sheetName = sheet_name)
#setColWidths(wb, sheet = 1, cols=1:100, widths = "auto") # set cols to automatically resize
setColWidths(wb, sheet = 1, cols=1:100, widths = "auto") # set cols to automatically resize
wb <- print.tabular.xlsx(wb, sheet='OR_tables', coords=c(1,1), tabular=t.wg.centrale, add.caption=TRUE)
wb <- print.tabular.xlsx(wb, 'OR_tables', c(1, nrow(t.wg.centrale)+4), t.hhr.centrale)
openXL(wb)


last_filled_row <- function(wb, sheet_number) {
  # returns the indexnumber of the last row with data on it
  # returns 0 if no rows contain data
  
  sheet_data <- wb$sheetData[[sheet_number]]
  if (length(sheet_data) == 0 ) {
    max_row <- 0
  }else{
    max_row <- max(as.integer(names(sheet_data)))  
  }
  
  max_row
}
#' @name tundra_container
#' @title tundra_container
#' @export
NULL

#' Tundra container class
#'
#' TODO: Formally define parameter spaces for models
#' 
#' @docType class
#' @name tundraContainer
#' @aliases NULL
#' @export
tundra_container <- setRefClass('tundraContainer',  #define reference classes to access by reference instead of by value
  fields = list(keyword = 'character',
                train_fn = 'function',
                predict_fn = 'function',
                munge_procedure = 'list',  # tundra contains munge_procedure so that it remembers the data-prep steps
                default_args = 'list',
                trained = 'logical',
                input = 'list',
                output = 'ANY',    # output stores the actual output of the train function (e.g. the model object)
                internal = 'list', # for storing info about the model
                hooks = 'list'),
  methods = list(
    initialize = function(keyword = character(0),
                          train_fn = identity, predict_fn = identity,
                          munge_procedure = list(),
                          default_args = list(),
                          internal = list()) {
      keyword <<- keyword
      train_fn <<- train_fn
      predict_fn <<- predict_fn
      munge_procedure <<- munge_procedure
      default_args <<- default_args
      internal <<- internal
      trained <<- FALSE
    },

    train = function(dataframe, train_args = list(), verbose = FALSE, munge = TRUE) {
      if (trained)
        stop("Tundra model '", keyword, "' has already been trained.")

      .run_hooks('train_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        triggers <- unlist(lapply(munge_procedure,
                              function(x) inherits(x, 'trigger')))
        
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe

        # Store trained munge_procedure
        munge_procedure <<- attr(dataframe, 'mungepieces')[!triggers]

        # reset mungepieces to NULL after training
        attr(dataframe, 'mungepieces') <- NULL
      }

      run_env <- new.env(parent = old_env <- environment(train_fn))
      on.exit(environment(train_fn) <<- old_env)
      input <<- append(train_args, default_args)
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(train_fn)
      environment(train_fn) <<- run_env
      if (debug_flag) debug(train_fn)

      .run_hooks('train_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <- train_fn(dataframe))           # Apply train function to dataframe

      input <<- run_env$input; output <<- run_env$output
      trained <<- TRUE
      res 
    },

    predict = function(dataframe, predict_args = list(), verbose = FALSE, munge = TRUE) {
      if (!trained)
        stop("Tundra model '", keyword, "' has not been trained yet.")

      .run_hooks('predict_pre_munge')

      if (length(munge_procedure) > 0 && identical(munge, TRUE)) {
        require(mungebits)
        initial_nrow <- nrow(dataframe)
        (if (!verbose) capture.output else function(...) eval.parent(...))(
          dataframe <- mungebits::munge(dataframe, munge_procedure)) # Apply munge_procedure to dataframe
        if (nrow(dataframe) != initial_nrow)
          warning(paste("Some rows were removed during data preparation.",
                        "Predictions will not match input dataframe."))

      }

      run_env <- new.env(parent = globalenv())
      run_env$input <- input; run_env$output <- output
      debug_flag <- isdebugged(predict_fn)
      environment(predict_fn) <<- run_env
      if (debug_flag) debug(predict_fn)

      .run_hooks('predict_post_munge')

      (if (!verbose) capture.output else function(...) eval.parent(...))(
        res <-
          if (length(formals(predict_fn)) < 2 || missing(predict_args)) {
            predict_fn(dataframe)
          } else { predict_fn(dataframe, predict_args) }
      )
      input <<- run_env$input; output <<- run_env$output
      res
    },
    
    munge = function(dataframe, steps = TRUE) {
      mungebits::munge(dataframe, munge_procedure[steps]) 
    },

    show = function() {
      cat(paste("A tundraContainer of type", sQuote(keyword)), "\n")
    },

    add_hook = function(type, hook_function) {
      stopifnot(is.character(type) && length(type) == 1)
      stopifnot(is.function(hook_function))
      allowed_types <- paste0(as.character(outer(
        c('train', 'predict'), c('pre', 'post'), paste, sep = '_')), '_munge')
      if (!is.element(type, allowed_types)) {
        stop("Tundra container hooks must be one of: ",
             paste(allowed_types, collapse = ", "))
      }

      hooks[[type]] <<- c(hooks[[type]], hook_function)
    },

    .run_hooks = function(type) {
      for (i in seq_along(hooks[[type]])) {
        eval.parent(bquote({
          `*fn*` <- hooks[[.(type)]][[.(i)]]
          environment(`*fn*`) <- environment()
          `*fn*`()
        }))
      }
    }
  )
)

#' @export
summary.tundraContainer <- function(x, ...) summary(x$output$model, ...)
#' @export
print.tundraContainer <-
  function(x, ...) print(paste("A tundraContainer of type", sQuote(x$keyword)), ...)

# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
kategorije <- c("Večkrat prvak", "Dva naslova prvaka", "En naslov prvaka")
stevilo.naslovov.dirkaca <- character(length(svetovniprvaki$Driver))
stevilo.naslovov.dirkaca[summary(svetovniprvaki$Driver) > 2] <- "Večkrat prvak"
stevilo.naslovov.dirkaca[summary(svetovniprvaki$Driver) == 2] <- "Dvakrat prvak"
stevilo.naslovov.dirkaca[summary(svetovniprvaki$Driver) < 2] <- "Enkrat prvak"
Stevilo.Naslovov.Dirkaca <- factor(stevilo.naslovov.dirkaca, levels = kategorije, ordered = TRUE)
Stevilo.naslovov.dirkaca <- data.frame(Sezona = svetovniprvaki$Season, Dirkač = svetovniprvaki$Driver, Država = svetovniprvaki$Country,
                                       Ekipa = svetovniprvaki$Team, Stevilo.Naslovov.Dirkaca)


source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="thresher")
rs <- dbSendQuery(con, 'select T.id as tua_id, T.offsets as tua_offsets, A.text as article_text, A.city_published as city, A.date_published as date, A.article_id, A.periodical_code, A.annotators as annotators, TT.name as tua_type from thresher_tua T, thresher_article A, thresher_analysistype TT where T.article_id = A.article_id and T.analysis_type_id = TT.id;')
data <- fetch(rs, n=-1)
write.csv(data, file = "tua_data.csv", fileEncoding = "UTF-8")library(XML)

# Vrne vektor nizov z odstranjenimi začetnimi in končnimi "prazninami" (whitespace)
# iz vozlišč, ki ustrezajo podani poti.
stripByPath <- function(x, path) {
  unlist(xpathApply(x, path,
                    function(y) gsub("^\\s*(.*?)\\s*$", "\\1", xmlValue(y))))
}

uvoz.konstruktorske.zmage <- function() {
  url.konstruktorske.zmage <- "http://en.wikipedia.org/wiki/List_of_Formula_One_World_Drivers%27_Champions#By_constructor"
  doc.konstruktorske.zmage <- htmlTreeParse(url.konstruktorske.zmage,encoding = "UTF-8", useInternalNodes=TRUE)
  
  # Poiščemo vse tabele v dokumentu
  tabele <- getNodeSet(doc.konstruktorske.zmage, "//table")
  
  # Iz šeste tabele dobimo seznam vrstic (<tr>) neposredno pod
  # trenutnim vozliščem
  vrstice <- getNodeSet(tabele[[6]], "./tr")
  
  # Seznam vrstic pretvorimo v seznam (znakovnih) vektorjev
  # s porezanimi vsebinami celic (<td>) neposredno pod trenutnim vozliščem
  seznam <- lapply(vrstice[2:length(vrstice)], stripByPath, "./td")
  
  # Iz seznama vrstic naredimo matriko
  matrika <- matrix(unlist(seznam), nrow=length(seznam), byrow=TRUE)
  
  # Imena stolpcev matrike dobimo iz celic (<th>) glave (prve vrstice) prve tabele
  colnames(matrika) <- gsub("\n", " ", stripByPath(vrstice[[1]], ".//th"))
  
  # Podatke iz matrike spravimo v razpredelnico
  return(data.frame(Country = gsub("^.(.*)$", "\\1", matrika[,2]),
                    Total = as.numeric(matrika[,3]), row.names = matrika[,1]))
  
}
# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()

# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
stevilo.zmag <- c("veliko zmag", "nekaj zmag", "ena zmaga")
zmage.ekip <- character(length(svetovniprvaki$Team))
zmage.ekip[summary(svetovniprvaki$Team) > 3] <- "veliko zmag"
zmage.ekip[summary(svetovniprvaki$Team) > 1 & summary(svetovniprvaki$Team) < 4] <- "nekaj zmag"
zmage.ekip[summary(svetovniprvaki$Team) < 2] <- "ena zmaga"
Zmage.ekip <- factor(svetovniprvaki$Team, levels = stevilo.zmag, ordered = TRUE)
Zmage.Ekip <- data.frame(svetovniprvaki$Season, svetovniprvaki$Driver, svetovniprvaki$Country,
                         svetovniprvaki$Team,svetovniprvaki$Base, svetovniprvaki$Engine, zmage.ekip)



source("lib/xml.r", encoding="UTF-8")
cat("Uvažam podatke o konstruktorskih zmagah.\n")
konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()


# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))

}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()

# Urejenostna spremenljivka
cat("Uvažam urejenostno spremenljivko... \n")
stevilo.zmag <- c("veliko zmag", "nekaj zmag", "ena zmaga")
zmage.ekip <- character(length(svetovniprvaki$Team))
zmage.ekip[summary(svetovniprvaki$Team) > 3] <- "veliko zmag"
zmage.ekip[summary(svetovniprvaki$Team) > 1 & summary(svetovniprvaki$Team) < 4] <- "nekaj zmag"
zmage.ekip[summary(svetovniprvaki$Team) < 2] <- "ena zmaga"
Zmage.ekip <- factor(svetovniprvaki$Team, levels = stevilo.zmag, ordered = TRUE)
Zmage.Ekip <- data.frame(svetovniprvaki$Season, svetovniprvaki$Driver, svetovniprvaki$Country,
                         svetovniprvaki$Team,svetovniprvaki$Base, svetovniprvaki$Engine, zmage.ekip)



# source("lib/xml.r", encoding="UTF-8")
# cat("Uvažam podatke o konstruktorskih zmagah.\n")
# konstruktorske.zmage <- uvoz.konstruktorske.zmage()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke sezona2014.csv
uvoziSezona2014 <- function() {
  return(read.table("podatki/sezona2014.csv", sep = ";", as.is = TRUE,
                      row.names = 1, header = TRUE,
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico sezona 2014.
cat("Uvažam podatke o sezoni 2014...\n")
sezona2014 <- uvoziSezona2014()




# Funkcija, ki uvozi podatke iz datoteke svetovniprvaki.csv
uvoziSvetovniprvaki <- function() {
  return(read.table("podatki/svetovniprvaki.csv", sep = ";", as.is = TRUE,
                    header = TRUE,
                    fileEncoding = "Windows-1250"))
}


# Zapišimo podatke v razpredelnico svetovni prvaki.
cat("Uvažam podatke o svetovnih prvakih...\n")
svetovniprvaki <- uvoziSvetovniprvaki()


# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if(debug==TRUE){print(paste("argument_test:", argument_test))}
  
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files

    if(debug==TRUE){print("Rendering without metadata")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with amethst_groups")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with color_list")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      if(debug==TRUE){print("Rendering with metadata_matrix, all columns")}
      
      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE

      if(debug==TRUE){print("Rendering with metadata_matrix, single column")}

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files

    if(debug==TRUE){print("Rendering without metadata")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with amethst_groups")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files

    if(debug==TRUE){print("Rendering with color_list")}
    
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      if(debug==TRUE){print("Rendering with metadata_matrix, all columns")}
      
      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE

      if(debug==TRUE){print("Rendering with metadata_matrix, single column")}

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==3 ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v12 <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors
  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)
  sample_names <- gsub("\"", "", sample_names)
  
  # make sure everything is sorted by id
  if(debug==TRUE){sample_names.test1<<-sample_names}
  
  if(debug==TRUE){sample_names.test2<<-sample_names}
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]
  sample_names <- sample_names[ order(sample_names) ]
  
  if(debug==TRUE){
    eigen_vectors.test<<-eigen_vectors
    eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  num_samples <- ncol(my_data$eigen_vectors)

  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug) 

  if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  if(debug==TRUE){
    print(paste("first_data_sample:", sample_names[1]))
    print(paste("last_data_sample :", sample_names[length(sample_names)]))
    print(paste("first_pch_sample :", names(plot_pch)[1]))
    print(paste("first_pch_sample :", names(plot_pch)[length(plot_pch)]))
    print(paste("first_pch_value  :", (plot_pch)[1]))
    print(paste("last_pch_value  :", (plot_pch)[length(plot_pch)]))
  }
  

  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==0 ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ sample_names,,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          test.color_column <<- color_column
          test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      if(debug==TRUE){ test1<<-metadata_column }

      if ( identical(image_out, "default") ){
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      }else{
        image_out = paste(image_out, ".png", sep="", collapse="")
        figure_main = paste( image_out,".PCoA", sep="", collapse="")
      }
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ sample_names,,drop=FALSE ] # order the metadata by value
      if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")
  #my_names <- gsub("\"", "", my_names)
  
  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    #pch_matrix <- pch_matrix[order(rownames(pch_matrix)),]
    #pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

    #my_names <- gsub("\"", "", my_names)


    #pch_matrix <- pch_matrix[ order(rownames(pch_matrix)), ]
    if(debug==TRUE){pch_matrix.test1<<-pch_matrix}
    pch_matrix <- pch_matrix[ sample_names, ]
    if(debug==TRUE){pch_matrix.test2<<-pch_matrix}
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    if(debug==TRUE){pch_levels.test<<-pch_levels}
    #pch_labels <- pch_labels
    if(debug==TRUE){pch_labels.test<<-pch_labels}
    if(debug==TRUE){plot_pch_vector.test<<-plot_pch_vector}
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch)))


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ sample_names, metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# 2. faza: Uvoz podatkov

# Funkcija, ki uvozi podatke iz datoteke druzine.csv
uvoziDruzine <- function() {
  return(read.table("podatki/druzine.csv", sep = ";", as.is = TRUE,
                      row.names = 1,
                      col.names = c("obcina", "en", "dva", "tri", "stiri"),
                      fileEncoding = "Windows-1250"))
}

# Zapišimo podatke v razpredelnico druzine.
cat("Uvažam podatke o družinah...\n")
druzine <- uvoziDruzine()

# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   File   : rbamtools.r
#   Date   : 12.Mar.2012
#   Sam    : Samtools downloaded September 7, 2011. Format: v1.4-r985
#   Content: R-Source for package rbamtools
#   Version: 2.9.8
#   Author : W. Kaisers
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  CRAN submission:
#  check R CMD check --as-cran
#  wput rbamtools_2.0.tar.gz ftp://cran.r-project.org/incoming/ 
#  Changelog
#  30.Okt.12  [initialize.gapList] Made printout message optional (verbose)
#  31.Okt.12  [bamRange] Included test for initialized index
#  31.Okt.12  Check for open reader in getHeader, getHeaderText, getRefCount
#  01.Nov.12  [get_const_next_align] added to correct memory leak.
#  08.Nov.12  Reading and writing big bamRanges (pure C, no R) valgrind
#                                                                checked.
#  09.Nov.12  [bamCopy.bamReader] Added which allows refwise copying.
#  31.Dec.12  gapSiteList class added
#  11.Jan.13  bamGapList class added
#  06.Feb.13  First successful test of bamGapList on 36 BAM-files 
#                                                       (871.926/sec)
#  20.Feb.13  Fixed Error in merge.bamGapList
#  27.Feb.13  Renamed createIndex -> create.index and loadIndex -> load.index
#             and bamSiteList -> bamGapList
#  18.Apr.13  Corrected some memory leaks in C-Code as reported by Brian Ripley
#  22.Apr.13  Added (read-) name and revstrand to as.data.frame.bamRange
#                                               (as proposed by Ander Muniategui)
#  11.Jun.13  Added reader2fastq and range2fastq functions
#                                               (2.5.3, valgrind tested)
#  11.Jun.13  Changed signature for bamSave: added refid argument
#               (needed to prevent samtools crashes when creating BAM files
#               with single align regions and appropriate refSeqDict entries)
#             (2.5.4, valgrind tested)
#  12.Jun.13  Added extractRanges function (2.5.5)
#  21.Jun.13  Added bamAlign function (2.5.6)
#  01.Jul.13  Added bamCount function (2.5.8)
#  02.Jul.13  Added bamCountAll function, valgrind tested (2.5.9)
#  18.Jul.13  Changed 'nGapAligns' to 'nAlignGaps (2.5.10)
#                                               nGapAligns deprecated!
#  24.JUl.13  Added alignQual function, valgrind tested (2.5.11)
#  28.Jul.13  Added alignDepth function, valgrind tested (2.5.12)
#  13.Aug.13  Added countTextLines function, valgrind tested (2.6.1)
#  26.Aug.13  Removed "coerce" from Namespace declaration
#  02.Sep.13  Changed "cat" to "message"
#  10.Jun.14  On CRAN after correction of "Mis-alignment errors"
#  19.Jun.14  Re-introduction of changes after resetting to 2.7.0
#                                                       due to internal errors.
#  21.Jul.14  Updated plotAlignDepth 
#  14.Jul.14  Added test directory
#  28.Jul.14  Added NEWS and ChangeLog file
#  29.Sep.14  Added support for DS segment in headerProgram (@PG)
#               Added support for Supplementary alignmnet FLAG
#               Corrected error in resetting FLAG values
#               Replaced rand() by runif() in ksort.h
#               Enclosed reader2fastq example in \dontrun{}
#  03.Nov.14  Changed nAligns data type to unsigned long long int
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

.onUnload <- function(libpath) { library.dynam.unload("rbamtools", libpath) }


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Declaration of classes
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  File interacting classes:
#  bamReader, bamWriter
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamReader", representation(
    filename="character", reader="externalptr", index="externalptr",
    startpos="numeric"),
    validity=function(object)
    {return(ifelse(is.null(object@reader), FALSE, TRUE))})


setClass("bamWriter",
            representation(filename="character", writer="externalptr"),
            validity=function(object)
            {
                return(ifelse(is.null(object@writer), FALSE, TRUE))
            })

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Header section related classes:
#  bamHeader, bamHeaderText,
#  headerLine,
#  
#  refSectDict, headerReadGroup,
#  headerProgram
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamHeader",
        representation(header="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@header), FALSE, TRUE))
})

setClass("headerLine",
    representation(VN="character", SO="character"),
    validity=function(object)
    {
        if( (length(VN) == 1) & (length(SO) == 1) )
            return(TRUE)
        else
            return(FALSE)
    })


setClass("refSeqDict",
    representation(SN="character", LN="numeric",   AS="character",
                   M5="numeric",   SP="character", UR="character"))

setClass("headerReadGroup", representation(
            nrg="integer",          #  Number of read groups
            ID="character",         #  Read group identifier
            CN="character",         #  Name of sequencing center
            DS="character",         #  Description
            DT="character",         #  Date
            FO="character",         #  Flow order
            KS="character",         #  Array of nucleotide bases
            LB="character",         #  Library
            PG="character",         #  Programes used for processing
            PI="character",         #  Predicted median insert size
            PL="character",         #  Platform (ILLUMINA,...)
            PU="character",         #  Platform unit (e.g. lane code)
            SM="character",         #  Sample (Pool name)
            ntl="integer"           #  number of taglabs (= 12 (static))
            ),
                                validity=function(object) {return(TRUE)})

tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG",
             "PI", "PL", "PU", "SM")

setClass("headerProgram",
    representation(l="list"),
    validity=function(object) {return(TRUE)})

setClass("bamHeaderText",
        representation(head="headerLine", dict="refSeqDict",
                    group="headerReadGroup", prog="headerProgram", 
                    com="character"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Align related classes:
#  bamAlign, bamRange, alignDepth
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamAlign", 
    representation(align="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@align, FALSE, TRUE)))
})


setClass("bamRange", 
    representation(range="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@range), FALSE, TRUE))
})


setClass("alignDepth",
            representation(depth="integer", depth_r="integer", pos="integer",
            params="numeric", refname="character"))


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Segment Count
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("bamSegments",
        representation(
            seqid = "numeric",
            seqname = "character",
            seqlen = "numeric",
            #
            seg_seqid = "numeric",
            seg_start = "numeric",
            seg_end = "numeric"
        ),
        validity = function(object) {
            n <- length(object@seqid)
            if(length(object@seqs)!=n || 
                length(object@seqnames)!=n ||
                length(object@seqlen) !=n)
            { return(false) }
            
            n <- length(object@seg_seqid)
            if(length(object@seg_start)!=n ||
                length(object@seg_end) != n)
            { return(false) }
        }
)

bamSegments <- function(bam=NULL)
{
    if(is.null(bam))
        return( new("bamSegments"))
    
    if(!is.character(bam))
        stop("bam must be character!")
    
    if(!file.exists(bam))
        stop("bam does not exist!")
    
    reader <- bamReader(bam)
    rd <- getRefData(reader)
    
    res <- new("bamSegments")
    res@seqid <- rd$ID
    res@seqname <- rd$SN
    res@seqlen <- rd$LN
    return(res)
}

setMethod("show", "bamSegments", function(object)
{
    n <- min(6, length(object@seqid))
    
    if(n==0)
    {
        cat("An empty object of class '", class(object), "'.\n", sep="")
        return(invisible())
    }
    
    cat("An object of class '", class(object), "'.\n", sep="")
    cat("Reference sequences: (", length(object@seqid), ")\n", sep="")
    print(data.frame(seqid=object@seqid[1:n],
                        seqname=object@seqname[1:n],
                        seqlen=object@seqlen[1:n]))
    

    cat("Segments: (",length(object@seg_seqid) ,")\n", sep="")
    n <- min(6, length(object@seg_seqid))
    if(n > 0)
    {
        print(data.frame(seqid=object@seg_seqid[1:n],
                    start=object@seg_start[1:n],
                    end=object@seg_end[1:n]))
    }
    return(invisible())
})



setClass("rangeSegCount",
        representation(
            position = "integer",
            count = "integer",
            refname = "character",
            LN = "integer",
            coords = "numeric",
            complex = "logical"
        ),
        validity = function(object) { return(length(position)==length(count)) }
)


setMethod("show", "rangeSegCount", function(object)
{
    o <- object
    op <- o@coords
    n <- 6
    cat("An object of class '", class(o), "'.\n",sep="")
    bm<-Sys.localeconv()[7]
    w<-15
    r<-"right"
    cat("Refname : ", format(o@refname              , w=w, j=r), "\n", sep="")
    cat("Seqid   : ", format(format(op[1], big.m=bm), w=w, j=r), "\n", sep="")
    cat("LN      : ", format(format(o@LN,  big.m=bm), w=w, j=r), "\n", sep="")
    cat("qrBegin : ", format(format(op[2], big.m=bm), w=w, j=r), "\n", sep="")
    cat("qrEnd   : ", format(format(op[3], big.m=bm), w=w, j=r), "\n", sep="")
    cat("Complex : ", format(o@complex              , w=w, j=r), "\n", sep="")
    cat("\n")
    print(data.frame(position=o@position[1:n], count=o@count[1:n]))
    return(invisible())
})

as.data.frame.rangeSegCount <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(data.frame(position=x@position, 
                        count=x@count,
                        row.names=row.names))
}

setGeneric("rangeSegCount", function(object, 
                coords=NULL, segments=NULL, 
                complex=FALSE) standardGeneric("rangeSegCount"))

setMethod("rangeSegCount", "bamReader", 
    function(object, coords=NULL, segments=NULL, complex=FALSE)
    {
        if(!indexInitialized(object))
            stop("Reader must have initialized index! Use 'load.index'!")
        
        if(is.null(coords))
            stop("coords argument is not optional!")
        
        if(!is.numeric(coords))
            stop("coords must be numeric!")
        
        if(length(coords) != 3)
            stop("coords must have length 3")
        
        if(any(coords < 0))
            stop("coords must not be negative")
        
        coords <- as.numeric(coords)
        
        if(is.null(segments))
            stop("segments argument is not optional")
        
        if(!is.numeric(segments))
            stop("segments must be numeric")
        
        if(any(segments < 0))
            stop("segment values must not be negative")
        
        segments <- sort(as.integer(segments))
        
        if(!is.logical(complex))
            stop("complex must be logical")
        
        res <- .Call("bam_count_segment_aligns",
                     object@reader, object@index,
                     coords, segments, 
                     complex[1], PACKAGE="rbamtools")
        
        return(res)
        
    }
)


setGeneric("meltDownSegments", 
           function(object, factor=1) standardGeneric("meltDownSegments"))

setMethod("meltDownSegments", "rangeSegCount", function(object, factor=1)
{
    if(!is.numeric(factor))
        stop("factor must be numeric")
    
    if(length(factor) != 1)
        stop("factor must contain exactly one value")
    
    if(factor[1] < 1)
        stop("factor must be >= 1")
    
    factor <- as.integer(factor)
    
    res <- .Call("bam_count_segment_melt_down", 
                 object, factor[1], PACKAGE="rbamtools")
    return(res)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Gap sites related classes:
#  gapList, gapSiteList
#  bamGapList
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setClass("gapList", 
    representation(list="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@list), FALSE, TRUE))
})

setClass("gapSiteList",
    representation(list="externalptr"), validity=function(object)
{
    return(ifelse(is.null(object@list), FALSE, TRUE))
})

setClass("bamGapList",
        representation(list="externalptr", refdata="data.frame"),
        validity=function(object)
{ 
    return(ifelse(is.null(object@list), FALSE, TRUE))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Declaration of generics
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# Reader associated Generics

setGeneric("filename", function(object) standardGeneric("filename"))

setGeneric("isOpen", function(con, rw="") standardGeneric("isOpen"))

setGeneric("bamClose", function(object) standardGeneric("bamClose"))

setGeneric("rewind", function(object) standardGeneric("rewind"))

setGeneric("getHeader",function(object) standardGeneric("getHeader"))

setGeneric("getRefCount",function(object) standardGeneric("getRefCount"))

setGeneric("getRefData",function(object) standardGeneric("getRefData"))

setGeneric("getRefCoords",function(object, sn) standardGeneric("getRefCoords"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Replacement for (deprecated) functions -> .Defunct
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setGeneric("createIndex",function(object,idx_filename)
                                standardGeneric("createIndex"))

setGeneric("loadIndex", function(object, filename)
                                standardGeneric("loadIndex"))

setGeneric("indexInitialized", function(object) 
                                standardGeneric("indexInitialized"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Soon deprecated functions (for consistency reasons)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setGeneric("create.index",function(object, idx_filename)
                                standardGeneric("create.index"))

setGeneric("load.index",function(object, filename)
                                standardGeneric("load.index"))

setGeneric("index.initialized",function(object) 
                                standardGeneric("index.initialized"))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setGeneric("bamSort",function(object, prefix="sorted",
            byName=FALSE, maxmem=1e+9,
            path=dirname(filename(object))) standardGeneric("bamSort"))

setGeneric("reader2fastq",function(object, filename, which, append=FALSE)
            standardGeneric("reader2fastq"))

setGeneric("readerToFastq", function(object, filename, which, append=FALSE)
            standardGeneric("readerToFastq"))

setGeneric("bamCopy", function(object, writer, refids, verbose=FALSE)
            standardGeneric("bamCopy"))

setGeneric("extractRanges",function(object, ranges, filename, complex=FALSE,
            header, idxname) standardGeneric("extractRanges"))

setGeneric("bamCount", function(object, coords) standardGeneric("bamCount"))

setGeneric("bamCountAll", function(object, verbose=FALSE)
            standardGeneric("bamCountAll"))

setGeneric("nucStats", function(object, ...) standardGeneric("nucStats"))


# generic for bamReader and bamRange
setGeneric("getNextAlign", function(object) standardGeneric("getNextAlign"))

# generic for bamWriter and bamRange
setGeneric("bamSave", function(object, ...) standardGeneric("bamSave"))

# Generic for conversion into list
setGeneric("as.list", function(x, ...) standardGeneric("as.list"))

# Generic for retrieving RefData string from Objects
setGeneric("getHeaderText", function(object, delim="\n")
                                    standardGeneric("getHeaderText"))

# Generic for Reading member from object list
setGeneric("getVal", function(object, member) standardGeneric("getVal"))

# Generic for Writing member to object list
setGeneric("setVal", function(object, members, values)
                                            standardGeneric("setVal"))

# Generic fora adding read group to header
setGeneric("addReadGroup",function(object, l) standardGeneric("addReadGroup"))

# Generic for retrieving of list size
setGeneric("size", function(object) standardGeneric("size"))

# Generic for retrieving Nr of aligns in BAM region from gapList
setGeneric("nAligns", function(object) standardGeneric("nAligns"))

# Generic for retrieving Nr of gapped-aligns in BAM region from gapList
setGeneric("nAlignGaps", function(object) standardGeneric("nAlignGaps"))

# Generic for reading gapLists (align gaps) from bamReader
setGeneric("gapList", function(object, coords) standardGeneric("gapList"))

# Generic for reading gapSiteList (merged align gap sites) from bamReader
setGeneric("siteList", function(object, coords) standardGeneric("siteList"))

# Generic for reading bamGapList (merged align gap sites for whole bam-files)
# from bamReader
setGeneric("bamGapList", function(object) standardGeneric("bamGapList"))

# Generic for retrieving quality values
setGeneric("getQualDf", function(object, prob=FALSE, ...)
                                    standardGeneric("getQualDf"))

# Generic for retrieving quantile values from (phred) 
# quality tables (used for plotQualQuant)
setGeneric("getQualQuantiles", function(object, quantiles, ...)
                                    standardGeneric("getQualQuantiles"))

# Generic for plotting of (phred) quality quantiles.
setGeneric("plotQualQuant", function(object)
                                    standardGeneric("plotQualQuant"))

# bamHeader related generics
setGeneric("bamWriter", function(x, filename) standardGeneric("bamWriter"))

# refSeqDict related generics
setGeneric("removeSeqs", function(x, rows) standardGeneric("removeSeqs"))

setGeneric("addSeq",
            function(object, SN, LN, AS="", M5=0, SP="", UR="")
            standardGeneric("addSeq"))

setGeneric("head", function(x, ...) standardGeneric("head"))
setGeneric("tail", function(x, ...) standardGeneric("tail"))

# bamHeaderText related generics
setGeneric("headerLine", function(object) standardGeneric("headerLine"))

setGeneric("refSeqDict", function(object) standardGeneric("refSeqDict"))

setGeneric("headerReadGroup", function(object)
        standardGeneric("headerReadGroup"))

setGeneric("headerProgram", function(object)
        standardGeneric("headerProgram"))

setGeneric("headerLine<-", function(object,value)
        standardGeneric("headerLine<-"))

setGeneric("refSeqDict<-", function(object, value)
        standardGeneric("refSeqDict<-"))

setGeneric("headerReadGroup<-", function(object, value)
        standardGeneric("headerReadGroup<-"))

setGeneric("headerProgram<-", function(object, value)
        standardGeneric("headerProgram<-"))

setGeneric("bamHeader", function(object)
        standardGeneric("bamHeader"))

# gapSiteList related generics
setGeneric("refID", function(object) standardGeneric("refID"))

# bamRange related generics
setGeneric("getCoords", function(object) standardGeneric("getCoords"))

setGeneric("getParams", function(object) standardGeneric("getParams"))

setGeneric("getSeqLen", function(object) standardGeneric("getSeqLen"))

setGeneric("getRefName", function(object) standardGeneric("getRefName"))

setGeneric("getAlignRange", function(object) standardGeneric("getAlignRange"))

setGeneric("getPrevAlign", function(object) standardGeneric("getPrevAlign"))

setGeneric("stepNextAlign", function(object) standardGeneric("stepNextAlign"))

setGeneric("stepPrevAlign", function(object) standardGeneric("stepPrevAlign"))

setGeneric("push_back", function(object, value) standardGeneric("push_back"))

setGeneric("pop_back", function(object) standardGeneric("pop_back"))

setGeneric("push_front", function(object, value) standardGeneric("push_front"))

setGeneric("pop_front", function(object) standardGeneric("pop_front"))

setGeneric("writeCurrentAlign", 
                function(object, value) standardGeneric("writeCurrentAlign"))

setGeneric("insertPastCurrent", 
                function(object, value) standardGeneric("insertPastCurrent"))

setGeneric("insertPreCurrent", 
                function(object, value) standardGeneric("insertPreCurrent"))

setGeneric("moveCurrentAlign",
                function(object, target) standardGeneric("moveCurrentAlign"))

# Deprecated:
setGeneric("range2fastq", 
        function(object, filename, which, append=FALSE)
            standardGeneric("range2fastq"))

setGeneric("rangeToFastq", 
           function(object, filename, which, append=FALSE)
               standardGeneric("rangeToFastq"))

setGeneric("countNucs", function(object) standardGeneric("countNucs"))


# alignDepth related generics
setGeneric("alignDepth", 
                function(object, gap=FALSE, flagFilter=0) standardGeneric("alignDepth"))

setGeneric("getDepth", 
                function(object, named=FALSE) standardGeneric("getDepth"))

setGeneric("getPos", function(object) standardGeneric("getPos"))

setGeneric("plotAlignDepth",
           function(object, start=NULL, end=NULL, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",  transcript="",
                    strand=NULL , log="y", cex.main=2,
                    col="grey50", fill="grey90", grid=TRUE, 
                    box.col="grey20", box.border="grey80", ... )
    standardGeneric("plotAlignDepth")
)

    
setGeneric("plotAlignDepths",
           function(object, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",
                    log="y", cex.main=2,
                    col="black", fill.fw="grey90", fill.rv="grey40", grid=TRUE, 
                    ... )
    standardGeneric("plotAlignDepths")
)


# bamAlign related generics
setGeneric("name", function(object)
        standardGeneric("name"))

setGeneric("position", function(object)
        standardGeneric("position"))

setGeneric("nCigar", function(object)
        standardGeneric("nCigar"))

setGeneric("cigarData", function(object)
        standardGeneric("cigarData"))

setGeneric("mateRefID", function(object)
        standardGeneric("mateRefID"))

setGeneric("matePosition", function(object)
        standardGeneric("matePosition"))

setGeneric("insertSize", function(object)
        standardGeneric("insertSize"))

setGeneric("mapQuality", function(object)
        standardGeneric("mapQuality"))

setGeneric("alignSeq", function(object)
        standardGeneric("alignSeq"))

setGeneric("alignQual", function(object)
        standardGeneric("alignQual"))

setGeneric("alignQualVal", function(object)
    standardGeneric("alignQualVal"))

setGeneric("pcrORopt_duplicate", function(object)
    standardGeneric("pcrORopt_duplicate"))

setGeneric("pcrORopt_duplicate<-", function(object, value)
    standardGeneric("pcrORopt_duplicate<-"))

setGeneric("failedQC", function(object)
        standardGeneric("failedQC"))

setGeneric("failedQC<-", function(object, value)
        standardGeneric("failedQC<-"))

setGeneric("firstInPair", function(object) 
        standardGeneric("firstInPair"))

setGeneric("firstInPair<-", function(object ,value)
        standardGeneric("firstInPair<-"))

setGeneric("secondInPair", function(object) 
        standardGeneric("secondInPair"))

setGeneric("secondInPair<-", function(object, value)
        standardGeneric("secondInPair<-"))

setGeneric("unmapped", function(object)
        standardGeneric("unmapped"))

setGeneric("unmapped<-", function(object, value)
        standardGeneric("unmapped<-"))

setGeneric("mateUnmapped", function(object)
        standardGeneric("mateUnmapped"))

setGeneric("mateUnmapped<-", function(object, value)
        standardGeneric("mateUnmapped<-"))

setGeneric("reverseStrand", function(object)
        standardGeneric("reverseStrand"))

setGeneric("reverseStrand<-", function(object, value)
        standardGeneric("reverseStrand<-"))

setGeneric("mateReverseStrand", function(object)
        standardGeneric("mateReverseStrand"))

setGeneric("mateReverseStrand<-", function(object, value)
        standardGeneric("mateReverseStrand<-"))

setGeneric("paired", function(object) 
        standardGeneric("paired"))

setGeneric("paired<-", function(object, value)
        standardGeneric("paired<-"))

setGeneric("properPair", function(object)
        standardGeneric("properPair"))

setGeneric("properPair<-", function(object, value)
        standardGeneric("properPair<-"))

setGeneric("secondaryAlign", function(object)
        standardGeneric("secondaryAlign"))

setGeneric("secondaryAlign<-", function(object, value)
        standardGeneric("secondaryAlign<-"))

setGeneric("suppAlign", function(object)
    standardGeneric("suppAlign"))

setGeneric("suppAlign<-", function(object, value)
    standardGeneric("suppAlign<-"))

setGeneric("flag", function(object) 
        standardGeneric("flag"))

setGeneric("flag<-", function(object, value)
        standardGeneric("flag<-"))



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  static functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

gc_content <- function(An, Cn, Gn, Tn)
{
    denom <- sum(An+Cn+Gn+Tn)
    if(denom==0)
        return(0)
    return(sum(Gn + Cn) / denom)
}
at_gc_ratio <- function(An, Cn, Gn, Tn)
{
    denom <- sum(Gn+Cn)
    if(denom==0)
        return(NA)
    return(sum(An + Tn) / denom)
}



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamReader
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Opening and closing a BAM-File for reading
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", signature="bamReader",
            definition=function(.Object, filename)
{
        .Object@filename <- filename
        .Object@reader <- .Call("bam_reader_open",
                                    path.expand(filename), PACKAGE="rbamtools")
        
        .Object@startpos <- .Call("bam_reader_tell", 
                                    .Object@reader, PACKAGE="rbamtools")
        return(.Object)
})


bamReader <- function(filename, indexname, idx=FALSE, verbose=0)
{
    if(!is.logical(idx))
        stop("[bamReader] idx must be logical!")
    if(length(idx)>1)
        stop("[bamReader] length(idx) must be 1!")
    if(!is.numeric(verbose))
        stop("[bamReader] verbose must be numeric!")
    
    reader <- new("bamReader", filename)
    
    if((!idx) && missing(indexname))
    {
        if(verbose[1]==1)
            cat("[bamReader] Opened file '", basename(filename), "'.\n", sep="")
        else if(verbose[1]==2)
            cat("[bamReader] Opened file '", filename, "'.\n", sep="")
        return(reader)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  use indexname or set default
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(missing(indexname))
        idxfile <- paste(filename, "bai", sep=".")
    else
        idxfile <- indexname
    
    loadIndex(reader, idxfile)
    
    if(verbose[1]==1)
    {
        cat("[bamReader] Opened file '", basename(filename),
                    "' and index '", basename(idxfile), "'.\n", sep="")
    }else if(verbose[1]==2)
    {
        cat("[bamReader] Opened file '", filename,
                    "' and index '", idxfile, "'.\n", sep="")
    }
    
    return(reader)
}

setMethod("filename", "bamReader", function(object) return(object@filename))

setMethod("isOpen", signature="bamReader", definition=function(con, rw="")
{
    return(!(.Call("is_nil_externalptr", con@reader, PACKAGE="rbamtools")))
})

setMethod(f="bamClose", signature="bamReader", definition=function(object)
{
    if(!.Call("is_nil_externalptr", object@index, PACKAGE="rbamtools"))
    {
        .Call("bam_reader_unload_index", object@index, PACKAGE="rbamtools")
    }
    invisible(.Call("bam_reader_close", object@reader, PACKAGE="rbamtools"))
})


setMethod("show","bamReader", function(object)
{
    bm <- Sys.localeconv()[7]
    w <- 20
    r <- "right"
    cat("Class       : ", format(class(object)  , w=w, j=r)                       , "\n", sep="")
    cat("Filename    : ", format(basename(object@filename), w=w, j=r)             , "\n", sep="")
    cat("File status : ", format(ifelse(isOpen(object), "Open", "Closed"), w=w, j=r), "\n", sep="")
    cat("Index status: ", format(ifelse(indexInitialized(object), "Initialized", "Not initialized"), w=w, j=r), "\n", sep="")
    
    if(isOpen(object))
    {
        cat("RefCount    : ", format(getRefCount(object), w=w, j=r)                  , "\n", sep="")
    }
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Opening and closing a BAM-File for reading
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#   Header related functions
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   This is one standard Method for creation of bamHeader
#   and is used as a simple way to pass a header to a new
#   instance of bamWriter
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="getHeader", signature="bamReader", definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check with 'isOpen(reader)'!")
    
    return(new("bamHeader", .Call("bam_reader_get_header", object@reader))) 
})


setMethod(f="getHeaderText", signature="bamReader", definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check 'isOpen(reader)'!")
    
    return(new("bamHeaderText", .Call("bam_reader_get_header_text",
                                    object@reader, PACKAGE="rbamtools")))
})

#  + + + + + + + + + + + + + + + + + # 
#  getRefCount
#  + + + + + + + + + + + + + + + + + # 
setMethod(f="getRefCount", signature="bamReader",
                                            definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check with 'isOpen(reader)'!")
    
    return(.Call("bam_reader_get_ref_count",
                                object@reader, PACKAGE="rbamtools"))
})


#  + + + + + + + + + + + + + + + + + # 
#  getRefData
#  + + + + + + + + + + + + + + + + + # 
setMethod(f="getRefData", signature="bamReader", definition=function(object)
{
    if(!isOpen(object))
        stop("reader must be opened! Check with 'isOpen(reader)'!")
    
    return(.Call("bam_reader_get_ref_data", 
                                object@reader, PACKAGE="rbamtools"))
})


#  + + + + + + + + + + + + + + + + + # 
#  getRefCoords: Returns coordinates 
#  of entire reference for usage with
#  bamRange, gapList or siteList
#  function.
#  + + + + + + + + + + + + + + + + + # 
setMethod(f="getRefCoords",
                        signature="bamReader", definition=function(object,sn)
{
    if(!is.character(sn))
        stop("sn must be character!")
    
    if(length(sn) > 1)
        stop("sn must have length 1!")
    
    ref <- getRefData(object)
    id <- which(sn==ref$SN)
    
    if(length(id) == 0)
        stop("No match for sn in ref-data-SN!")
    
    coords <- c(ref$ID[id], 0, ref$LN[id])
    names(coords) <- c("refid", "start", "stop")
    return(c(ref$ID[id], 0, ref$LN[id]))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End Header related functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Index related functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="createIndex", signature="bamReader",
    definition=function(object,idx_filename)
{
    if(missing(idx_filename))
        idx_filename <- paste(object@filename, ".bai", sep="")
    
    return(invisible(.Call("bam_reader_create_index",
                            path.expand(object@filename),
                            path.expand(idx_filename), PACKAGE="rbamtools")))
})

setMethod("loadIndex", signature="bamReader", 
                                        definition=function(object,filename)
{
    if(!is.character(filename))
        stop("Filename must be character!\n")
    
    if(!file.exists(filename))
        stop("Index file \"", filename, "\" does not exist!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Set index Variable in given bamReader object:
    #  Read object name, create expression string and evaluate in parent frame
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    reader <- deparse(substitute(object))
    
    extxt <- paste(reader,"@index<-.Call(\"bam_reader_load_index\",\"",
                path.expand(filename), "\",PACKAGE=\"rbamtools\")", sep="")
    
    eval.parent(parse(text=extxt))
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Return true if bamReader@index!=NULL (parent frame)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    extxt <- paste(".Call(\"is_nil_externalptr\",", reader,
                                    "@index,PACKAGE=\"rbamtools\")", sep="")
    
    return(invisible(!eval.parent(parse(text=extxt))))
})


setMethod("indexInitialized", signature="bamReader", definition=function(object)
{ return(!(.Call("is_nil_externalptr", object@index, PACKAGE="rbamtools"))) })



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Deprecated functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("create.index", "bamReader", function(object, idx_filename)
{
    message("[create.index] Will soon be deprecated. Use createIndex.")
    return(createIndex(object, idx_filename))
    #.Deprecated(new="createIndex",package="rbamtools")
})


setMethod("load.index", "bamReader", function(object, filename)
{
    message("[load.index] Will soon be deprecated. Use loadIndex.")
    #.Deprecated(new="loadIndex", package="rbamtools")
    
    if(!is.character(filename))
        stop("Filename must be character!\n")
    
    if(!file.exists(filename))
        stop("Index file \"", filename, "\" does not exist!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Set index Variable in given bamReader object:
    #  Read object name, create expression string and evaluate in parent frame
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    reader <- deparse(substitute(object))
    
    extxt <- paste(reader,"@index<-.Call(\"bam_reader_load_index\",\"",
                   path.expand(filename), "\",PACKAGE=\"rbamtools\")", sep="")
    
    eval.parent(parse(text=extxt))
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Return true if bamReader@index!=NULL (parent frame)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    extxt <- paste(".Call(\"is_nil_externalptr\",", reader,
                   "@index,PACKAGE=\"rbamtools\")", sep="")
    
    return(invisible(!eval.parent(parse(text=extxt))))
})


setMethod("index.initialized", "bamReader", function(object)
{
    message("[index.initialized] Will soon be deprecated. Use indexInitialized")
    #.Deprecated(new="indexInitialized", package="rbamtools")
    return(indexInitialized(object))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# 
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="bamSort", signature="bamReader",
        definition=function(object, prefix="sorted", byName=FALSE,
                    maxmem=1e+9, path=dirname(filename(object)))
{
    if(!isOpen(object))
        stop("bamReader must be opened!")
    
    if(!is.logical(byName))
        stop("[bamSort] byName must be logical!")
    
    if(length(byName) > 1)
        stop("[bamSort] byName must have length 1!")
    
    if(!is.numeric(maxmem))
        stop("[bamSort] maxmem must be numeric!")
    
    if(length(maxmem)>1)
        stop("[bamSort] maxmem must have length 1!")
            
    maxmem <- floor(maxmem)
    message("[bamSort] Filename: ", object@filename)
    message("[bamSort] Prefix  : ", prefix)
    message("[bamSort] Maxmem  : ", maxmem)
    message("[bamSort] By Name : ", byName)
    
    .Call("bam_reader_sort_file",
            object@filename,
            path.expand(file.path(path,prefix)),
            maxmem, byName, PACKAGE="rbamtools")
    
    cat("[bamSort] Sorting finished.\n")
    
    return(invisible(paste(prefix, ".bam", sep="")))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End Index related functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# getNextAlign
setMethod(f="getNextAlign", signature="bamReader", definition=function(object)
{
    ans <- .Call("bam_reader_get_next_align", 
                                        object@reader, PACKAGE="rbamtools")
    
    if(is.null(ans))
        return(invisible(NULL))
    else
        return(new("bamAlign", ans))
})



setMethod("reader2fastq", "bamReader", 
        function(object, filename, which, append=FALSE)
{
    message("[reader2fastq] Will soon be deprecated. Use readerToFastq")
    readerToFastq(object, filename, which, append)
})

setMethod("readerToFastq", "bamReader", 
          function(object, filename, which, append=FALSE)
{
    if(!isOpen(object))
        stop("Reader must be opened!")
    
    if(!is.logical(append))
        stop("'append' must be logical!")
    
    if(!is.character(filename))
        stop("'filename' must be character!")
              
    if(missing(which))
    {
        return(invisible(.Call("bam_reader_write_fastq", object@reader,
            filename, append, PACKAGE="rbamtools")))
    }else{
        if(!is.numeric(which))
            stop("'which' argument must be numeric!")
        
        ans <- .Call("bam_reader_write_fastq_index", object@reader, filename,
            as.integer(sort(unique(which))), append, PACKAGE="rbamtools")
        
        if(ans < length(which))
            message("[readerToFastq] EOF reached.\n")
        
        message("[readerToFastq]", ans, "records written.\n")
            return(invisible(ans))
    }
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Reading gap-lists
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("gapList", "bamReader", function(object, coords)
{
    if(!indexInitialized(object))
        stop("Reader must have initialized index!")
    
    return(new("gapList", object, coords))
})

setMethod("siteList", "bamReader", function(object, coords)
{
    if(!indexInitialized(object))
        stop("Reader must have initialized index!")
    
    return(new("gapSiteList", object, coords))
})

setMethod("bamGapList", "bamReader", function(object)
{
    if(!indexInitialized(object))
        stop("Reader must have initialized index!")
    
    return(new("bamGapList", object))
})


setMethod("rewind", "bamReader", function(object)
{
    return(invisible(.Call("bam_reader_seek", 
                    object@reader, object@startpos, PACKAGE="rbamtools")))
})


setMethod("bamSave", "bamReader", function(object, writer)
{
    if(!is(writer, "bamWriter"))
        stop("'writer' must be 'bamWriter'!")
    
    if(!isOpen(object))
        stop("'reader' is not open! Check 'isOpen'!")
    
    if(!isOpen(writer))
        stop("'writer' is not open! Check 'isOpen'!")
    
    # Saving old reading position
    oldpos <- .Call("bam_reader_tell", object@reader, PACKAGE="rbamtools")
    
    # Reset reader to start position
    .Call("bam_reader_seek",
                    object@reader, object@startpos, PACKAGE="rbamtools")
    
    nAligns <- .Call("bam_reader_save_aligns",
                    object@reader, writer@writer, PACKAGE="rbamtools")
    
    bm <- Sys.localeconv()[7]
    
    message("[bamSave.bamReader] Saving ", format(nAligns, big.mark=bm),
            " to file '", basename(writer@filename), "' finished.\n", sep="")
    
    .Call("bam_reader_seek", object@reader, oldpos, PACKAGE="rbamtools")
    
    return(invisible(nAligns))
})


setMethod("bamCopy", "bamReader", function(object, writer, refids, verbose=FALSE)
{
    if(!is(writer, "bamWriter"))
        stop("writer must be 'bamWriter'!")
    
    if(!isOpen(object))
        stop("reader is not open! Check 'isOpen'!")
    
    if(!isOpen(writer))
        stop("writer is not open! Check 'isOpen'!")
    
    if(!indexInitialized(object))
        stop("reader must have initialized index! Check 'indexInitialized'!")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check refids argument: When missing copy all ref's
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ref <- getRefData(object)
    if(missing(refids))
    {
        refids <- ref$ID
        n <- length(refids)
        mtc <- 1:n
    }
    else
    {
        mtc <- match(refids, ref$ID)
        if(any(is.na(mtc)))
            stop("refids must be subset of Reference-ID's! Check 'getRefData'!")
        n <- length(refids)    
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Copy aligns with bamRanges as intermediate buffer
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    bm <- Sys.localeconv()[7]
    nAligns <- 0
    for(i in 1:n)
    {
        range <- bamRange(object, 
                        c(ref$ID[mtc[i]], 0, ref$LN[mtc[i]]), complex=FALSE)
        
        nAligns <- nAligns+size(range)
        if(verbose)
        {
            message("[bamCopy.bamReader] i: ", i, "\tCopying ", 
            format(size(range), big.mark=bm, width=10), 
                    " aligns for Reference '", ref$SN[mtc[i]], "'.\n", sep="")
        }
        
        bamSave(writer, range, ref$ID[mtc[i]])
        rm(range)
        gc()
    }
    message("[bamCopy.bamReader] Copying ", 
        format(nAligns, big.mark=bm, width=10), " aligns finished.\n", sep="")
})


setMethod("extractRanges", "bamReader",
    definition=function(object, ranges, filename, complex=FALSE, header, idxname)
{
    if(!isOpen(object))  
        stop("Provided reader must be opened!")
    
    if(!indexInitialized(object))
        stop("Provided reader must have initialized index!")
    
    if(missing(header))
    {
        header <- getHeader(object)
    }else{
        if(!is(header, "bamHeader"))
            stop("[extractRanges] header must be of class 'bamHeader'")
        
        message("[extractRanges] bamHeader provided. Slot 'headerLine' will be changed (SO: unknown). Slot 'refSeqDict' will be overwritten.\n")
    }
    if(!is.data.frame(ranges))
        stop("[extractRanges] ranges must be 'data.frame'!")
    
    if(!is.logical(complex))
        stop("[extractRanges] complex must be logical!")
    
    if(length(complex) > 1)
        stop("[extractRanges] complex must have length 1!")
    
    # Preparing ranges table
    if(!all(is.element(c("seqid", "start", "end"), names(ranges))))
        stop("ranges argument must contain columns 'seqid', 'start', 'end'!")
    
    
    # Preparing filenames
    file_prefix <- sub("^([^.]*).*", "\\1", basename(filename))
    unsort_filename <- file.path(dirname(filename),
                paste("unsort", paste(file_prefix, "bam", sep="."), sep="_"))
    
    filename <- file.path(dirname(filename), paste(file_prefix, "bam", sep="."))
    
    message("[extractRanges] Provided filename is changed to '", filename,
                                        "' (see help for 'bamSort').", sep="")
    
    if(missing(idxname))
    {
        idxname <- paste(filename, "bai", sep=".")
    }else{
        if(!is.character(idxname))
            stop("[extractRanges] idxname must be character!\n")
    }
    bm <- Sys.localeconv()[7]
    

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  prepare range data
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    # It is essential for indexing, that all ref-ID's which
    # occur in aligns are also (implicitly) present in the
    # reference sequence dictionary (RSD) section.
    #
    # E.g. when there is an align which has refid 4, there
    # must be at least 5 entries in RSD because they are
    # indexed implicitly (that is: there is no entry in RSD
    # which says refid=4).
    #
    # Their ID is identified with the numbers
    # 0 to [(number of Entries in RSD)-1].
    #
    # Otherwise samtools indexing crashes without warning.
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    gp <- ranges[, c("seqid", "start", "end")] 
    rd <- getRefData(object)
    mtc <- match(gp$seqid, rd$SN)
    isna <- is.na(mtc)
    if(all(isna))
    {
        message("[extractRanges] No matching seqids for genes:")
        print(gp)
        message("[extractRanges] No output generated.\n")
        return(invisible())
    }
    
    if(any(isna))
    {
        message("[extractRanges] Missing seqid matches. Skipping following genes:")
        print(gp[isna, ])
        gp <- gp[!isna, ]
    }
    
    n <- dim(gp)[1]
    gp$old_ID <- rd$ID[mtc]
    gp$LN <- rd$LN[mtc]
    
    # Provide (unique) new ID's
    renew <- data.frame(old=sort(unique(gp$old_ID)))
    nid <- dim(renew)[1]
    renew$new <- 0:(nid-1)
    mtc <- match(gp$old_ID, renew$old)
    
    gp$new_ID <- renew$new[mtc]
    
    new_rd <- merge(renew, rd, by.x="old", by.y="ID")
    nref <- dim(new_rd)[1]
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  create new header
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    htxt <- getHeaderText(header)
    hl <- headerLine(htxt)
    setVal(hl, "SO", "unsorted")
    
    rsd <- new("refSeqDict")
    for(i in 1:nref)
        addSeq(rsd, SN=new_rd$SN[i], LN=new_rd$LN[i])
    headerLine(htxt) <- hl
    refSeqDict(htxt) <- rsd
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Writing aligns
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    cat("[extractRanges] Writing aligns to temporary file '", 
                                    unsort_filename, "'.\n", sep="")
    
    writer <- bamWriter(bamHeader(htxt), unsort_filename)
    
    nAligns <- 0
    for(i in 1:n)
    {
        range <- bamRange(object, c(gp$old_ID[i], gp$start[i], gp$end[i]))
        if(size(range)==0)
        {
            message("No aligns found for gene '", gp$gene_name[i], "'.")
        }else{
            bamSave(writer, range, refid=gp$new_ID[i])
            nAligns <- nAligns+size(range)
        }
    }
    message("[extractRanges] Writing of", format(nAligns, big.mark=bm),
                                                        "aligns finished.")
    
    bamClose(writer)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Sorting BAM output file
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    cat("[extractRanges] Sorting:\n")
    nread <- bamReader(unsort_filename)
    if(!isOpen(nread))
        stop("unsorted bam file not found!")
    bamSort(nread, prefix=file_prefix)
    bamClose(nread)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Creating index for ouput file
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    message("[extractRanges] Creating index '", basename(idxname), "'.", sep="")
    
    nread <- bamReader(filename)
    createIndex(nread, idx_filename=idxname)
    message("[extractRanges] Finished.\n")
    message("[extractRanges] You may want to delete file '", 
                                    basename(unsort_filename), "'.\n", sep="")
    return(invisible(nAligns))
})



setMethod("bamCount", signature="bamReader", definition=function(object, coords)
{
    if(!indexInitialized(object))
        stop("[bamCount] reader must have initialized index! Use 'loadIndex'!")
    
    if(missing(coords))
        stop("[bamCount] coords is not optional!")
    
    if(!is.numeric(coords))
        stop("[bamCount] coords must be numeric")
    
    res <- .Call("bam_count", object@reader, 
                                    object@index, coords, PACKAGE="rbamtools")
    
    names(res) <- c("M", "I", "D", "N", "S", "H", "P", "=", "X", "nAligns")
    return(res)
})


setMethod("bamCountAll", "bamReader", function(object, verbose=FALSE)
{
    if(!isOpen(object))
        stop("reader is not open! Check 'isOpen'!")
    
    if(!indexInitialized(object))
        stop("reader must have initialized index! Check 'indexInitialized'!")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check refids argument: When missing copy all ref's
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ref <- getRefData(object)
    nr <- nrow(ref)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Count first refid
    #  and read size and names of result
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(verbose)
        cat("[bamCountAll] Counting ", ref$SN[1],  "\t[ 1/", nr, "]", sep="")
    count <- bamCount(object, c(ref$ID[1], 0, ref$LN[1]))
    nc <- length(count)
    
    mtx <- matrix(numeric(nc*nr), ncol=nc)
    colnames(mtx) <- names(count)
    rownames(mtx) <- ref$SN
    mtx[1, ] <- count
    
    if(nr > 1)
    {
        for(i in 2:nr)
        {
            if(verbose)
            {
                cat("\r[bamCountAll] Counting ", ref$SN[i], 
                            "\t[", format(i, width=2), "/", nr, "]", sep="")
            }
            mtx[i, ] <- bamCount(object, c(ref$ID[i], 0, ref$LN[i]))
        }
    }
    
    if(verbose)
        cat("\n[bamCountAll] Finished.\n")
    res <- as.data.frame(mtx)
    res$ID <- ref$ID
    res$LN <- ref$LN
    return(res)
})


setMethod("nucStats", "bamRange", function(object)
{
    m <- countNucs(object)
    gcc <- gc_content(m[1], m[2], m[3], m[4])
    at_gc <- at_gc_ratio(m[1], m[2], m[3], m[4])
    dfr<-data.frame(
                        nAligns=size(object),
                        A=m[1],
                        C=m[2],
                        G=m[3],
                        T=m[4],
                        N=m[5],
                        gcc=gcc,
                        at_gc_ratio=at_gc
                    )
    
    refname <- .Call("bam_range_get_refname",
                        object@range, PACKAGE="rbamtools")
    
    if(!is.null(refname))
        row.names(dfr) <- refname
    
    return(dfr)
})



setMethod("nucStats", "bamReader", function(object)
{
    if(!isOpen(object))
        stop("Reader must be open (check 'isOpen')!")
    if(!indexInitialized(object))
        stop("Reader must have initialized index (use 'loadIndex')!")
    
    
    ref <- getRefData(object)
    n <- nrow(ref)
    m <- matrix(0, nrow=n, ncol=5)
    nAligns <- numeric(n)
    for(i in 1:n)
    {
        range <- bamRange(object, c(ref$ID[i], 0, ref$LN[i]))
        nAligns[i] <- size(range)
        m[i, ] <- countNucs(range)
    }
    dfr <- data.frame(nAligns=nAligns, 
                            A=m[, 1], C=m[, 2], G=m[, 3], T=m[, 4], N=m[, 5])
    
    dfr$gcc <- gc_content(dfr$A, dfr$C, dfr$G, dfr$T)
    
    dfr$at_gc_ratio <- at_gc_ratio(dfr$A, dfr$C, dfr$G, dfr$T)
    
    rownames(dfr) <- ref$SN
    return(dfr)
})

setMethod("nucStats", "character", 
        definition=function(object, idxInfiles=paste(object, ".bai", sep=""))
{
    if(any(!file.exists(object)))
        stop("[nucStats] Files (object) not found!")
    
    if(!is.character(idxInfiles))
        stop("[nucStats] idxInfiles must be character!")
    
    if(any(!file.exists(idxInfiles)))
        stop("[nucStats] Files (idxInfiles) not found!")
    
    n <- length(object)
    if(length(idxInfiles)!=n)
        stop("[nucStats] infiles and idxInfiles must have same length!")
    
    res <- data.frame(nAligns=numeric(n), A=numeric(n),
                C=numeric(n), G=numeric(n), T=numeric(n), N=numeric(n))
    
    for(i in 1:n)
    {
        reader <- bamReader(object[i])
        loadIndex(reader, idxInfiles[i])
        nc <- nucStats(reader)
        res[i, ] <- lapply(nc[, 1:6], sum)
    }
    res$gcc <- gc_content(res$A, res$C, res$G, res$T)
    res$at_gc_ratio <- at_gc_ratio(res$A, res$C, res$G, res$T)
    rownames(res) <- 1:n
    return(res)
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamHeader
#  Description: See SAM File Format Specification (v1.4-r985)
#  September 7, 2011, Section 1.3
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod("initialize", "bamHeader", function(.Object, extptr)
{
    if(!is(extptr, "externalptr"))
        stop("extptr must be externalptr!")
    .Object@header <- extptr
    return(.Object)
})

setMethod(f="getHeaderText", signature="bamHeader", definition=function(object)
{
    return(new("bamHeaderText", .Call("bam_header_get_header_text", 
                                object@header, PACKAGE="rbamtools"))) })

setMethod("as.character", "bamHeader", function(x, ...)
{
    .Call("bam_header_get_header_text", x@header, PACKAGE="rbamtools")
})

setMethod("show", "bamHeader", function(object)
{
    cat("An object of class \"", class(object), "\"\n", sep="")
    ht <- getHeaderText(object)
    hl <- headerLine(ht)
    dc <- refSeqDict(ht)
    
    cat("headerLine:\n")
    cat("VN:", hl@VN, "\n")
    cat("SO:", hl@SO, "\n")
    
    nsq <- length(dc@SN)
    cat("refSeqDict: (size ", nsq, ")\n", sep="")
    if(nsq>0)
    {
        cat("Seqs: ")
        for(i in 1:(pmin(nsq, 3)))
            cat(dc@SN[i], ",  ")
        cat("...\n")    
    }
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  This is the main function for creating an instance of bamWriter
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("bamWriter", "bamHeader", function(x, filename)
{
    if(!is.character(filename))
        stop("[bamWriter.bamHeader] filename must be character!")
    return(new("bamWriter", x, filename))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# headerLine: Represents two entries: 
# Format version (VN) and sorting order(SO)
# Valid format for VN : /^[0-9]+\.[0-9]+$/.
# Valid entries for SO: unknown (default),  unsorted,  queryname,  coordinate.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", signature="headerLine", 
                            definition=function(.Object, hl="", delim="\t")
{
    # Parses header line from header section
    if(!is.character(hl))
        stop("[headerLine.initialize] Argument must be string.\n")
    
    # Default object content (hl="" or character(0))
    if((length(hl)==1 && nchar(hl)==0) || length(hl)==0)
    {
        .Object@VN="1.4"
        .Object@SO="unknown"
        return(.Object)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Split input string into tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    tags <- unlist(strsplit(hl, delim))
    
    #  Three tags!
    if(length(tags)!=3)
        stop("hl must contain three tags separated by '", delim, "'!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   First  tag: '@HD'
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(tags[1]!="@HD")
        stop("First tag of string must be @HD!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Second tag: 'VN'
    #   TODO: Check Accepted format: /^[0-9]+\.[0-9]+$/.  
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(substr(tags[2], 1, 2)!="VN")
        stop("Second tag of string must be VN!\n")
    
    .Object@VN=substring(tags[2], 4)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Third   tag: 'SO'
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(substr(tags[3], 1, 2)!="SO")
        stop("Third tag of string must be SO!\n")
    
    str <- substring(tags[3], 4)
    if(str=="coordinate")
        .Object@SO <- "coordinate"
    else if(str=="unknown")
        .Object@SO <- "unknown"
    else if(str=="unsorted")
        .Object@SO <- "unsorted"
    else if(str=="queryname")
        .Object@SO <- "queryname"
    
    return(.Object)
})

setMethod("getHeaderText", "headerLine", function(object, delim="\t")
    {return(paste("@HD\tVN:", object@VN, "\tSO:", object@SO, sep=""))})

setMethod("getVal", signature="headerLine", definition=function(object, member)
{
    if(!is.character(member))
        stop("[getVal.headerLine] Member must be character!\n")
    if(member=="VN")
        return(object@VN)
    if(member=="SO")
        return(object@SO)
    stop("Member '", member, "' must be 'VN' or 'SO'!\n")
})

setMethod("setVal", signature="headerLine",
                                definition=function(object, members, values)
{
    if(!is.character(members) || !is.character(values))
        stop("Members and values must be character!\n")
    if(length(members)!=length(values))
        stop("Members and values must have same length!\n")
    
    tagLabs <- c("VN", "SO")
    mtc <- match(members, tagLabs)
    if(any(is.na(mtc)))
        stop("Member names must be valid Header line entries!\n")
    
    n <- length(members)
    if(n>2)
        stop("Only two members can be set!\n")
    
    obj <- deparse(substitute(object))
    for(i in 1:n)
    {
        txt <- paste(obj, "@", members[i], " <- '", values[i], "'", sep="")
        eval.parent(parse(text=txt))
    }
    return(invisible())
})

setMethod("as.list", signature="headerLine", definition=function(x, ...)
    {return(list(VN=x@VN, SO=x@SO))})

setMethod("show", "headerLine", function(object)
{
    cat("An object of class \"", class(object), "\"\n", sep="")
    cat("VN: ", object@VN, "\nSO: ", object@SO, "\n", sep="")
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  End headerLine
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   refSeqDict: Reference Sequence Dictionary
#   Represents a variable number of Ref Seqs
#   Valid Members (Entries for each sequence, stored in a data.frame):
#   SN Reference sequence name
#   LN Reference sequence length
#   AS Genome assembly identifier
#   M5 MD5 checksum of the sequence
#   SP Species
#   UR URI of the sequence
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", signature="refSeqDict", 
                            definition=function(.Object, hsq="", delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Reference sequence dictionary of header-text
    #  hsq= Vector of characters,  each representing one Ref-Sequence
    #  length(hsq) = number of Ref-Sequences
    #  Each Ref-string contains 'internally' [tab] delimited seqments:
    #                "SN:ab\tLN:12\tAS:ab\tM5:12\tSP:ab\tUR:ab"
    #  It's allowed to skip segments
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.character(hsq))
        stop("[refSeqDict.initialize] hsq must be character!")
    
    n <- length(hsq)
    # Return empty object when no input string is given
    if((n==1 && nchar(hsq)==0) || n==0)
        return(.Object)
    
    .Object@SN <- character(n)
    .Object@LN <- numeric(n)
    .Object@AS <- character(n)
    .Object@M5 <- numeric(n)
    .Object@SP <- character(n)
    .Object@UR <- character(n)
    
    labels <- c("SN", "LN", "AS", "M5", "SP", "UR")
    for(i in 1:n)
    {
        # Containes separated tags for one sequence
        seq <- unlist(strsplit(hsq[i], delim))
        if(seq[1]!="@SQ")
        stop("First segment in Ref-sequence tag must be '@SQ'!")
        seq <- seq[-1]
        
        # Contains column number in dict@df for each tag
        cols <- match(substr(seq, 1, 2), labels)
        m <- length(cols)
        
        for(j in 1:m)
        {
            txt <- substr(seq[j], 4, nchar(seq[j]))
            # Empty entries are skipped (to avoid errors)
            if(nchar(txt)>0)
            {
                if(cols[j]==1)
                    .Object@SN[i] <- txt
                else if(cols[j]==2)
                {
                    # Try to convert into numeric value
                    numb <- suppressWarnings(as.numeric(txt))  
                    if(is.na(numb))
                    {
                        warning("[refSeqDict.initialize] No numeric value for LN: '",
                                                txt, "'!\n", sep="")
                    }else{
                        .Object@LN[i] <- numb
                    }
                }
                else if(cols[j]==3)
                    .Object@AS[i] <- txt
                else if(cols[j]==4)
                {
                    # Try to convert into numeric value
                    numb <- suppressWarnings(as.numeric(txt))  
                    if(is.na(numb))
                    {
                        warning("[refSeqDict.initialize] No numeric value for LN: '",
                                                txt, "'!\n", sep="")
                    }else{
                        .Object@M5 <- numb
                    }
                }
                else if(cols[j]==5)
                    .Object@SP[i] <- txt
                else if(cols[j]==6)
                    .Object@UR[i] <- txt
            }
        }
    }
    return(.Object)
})

setMethod(f= "[", signature="refSeqDict", definition=function(x, i)
{
    rsd <- new("refSeqDict")
    rsd@SN <- x@SN[i]
    rsd@LN <- x@LN[i]
    rsd@AS <- x@AS[i]
    rsd@M5 <- x@M5[i]
    rsd@SP <- x@SP[i]
    rsd@UR <- x@UR[i]
    return(rsd)
})

setMethod(f="dim", signature="refSeqDict", definition=function(x)
                            {return(c(length(x@SN), 6))})


setMethod("removeSeqs", signature="refSeqDict", definition=function(x, rows)
{
    #  Removes given rows (=Sequences) from Dictionary
    #  so they are excluded from header
    n <- length(x@SN)
    if(!is.numeric(rows))  
        stop("[removeSeqs.refSeqDict] Sequence indices must be numeric!")
    rows <- as.integer(rows)
    
    if(any(rows)<1)
        stop("[removeSeqs.refSeqDict] Sequence indices must be positive!")
    if(any(rows)>n)
        stop("[removeSeqs.refSeqDict] Sequence indices must be <", n, "!")
    
    # Execute per eval in parent.frame
    if(length(rows)>1)
        rmv <- paste("c(", paste(rows, collapse=", "), ")", sep="")
    else
    rmv <- rows
    
    obj <- deparse(substitute(x))
    dictcol <- paste(obj, "@SN", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@LN", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@AS", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@M5", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@SP", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    
    dictcol<-paste(obj, "@UR", sep="")
    eval.parent(parse(text=paste(dictcol, "<-", dictcol, "[-", rmv, "]", sep="")))
    return(invisible())
})


setMethod("addSeq", signature="refSeqDict", 
                definition=function(object, SN, LN, AS="", M5=0, SP="", UR="")
{
    index <- length(object@SN)+1
    obj <- deparse(substitute(object))
    colidx <- paste("[", index, "]", sep="")
    
    # Appends new Sequence (row) at the end
    dictcol <- paste(obj, "@SN", colidx, sep="")
    eval.parent(parse(text=paste(dictcol, "<-'", SN, "'", sep="")))
    
    dictcol <- paste(obj, "@LN", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-", LN, sep="")))
    
    dictcol <- paste(obj, "@AS", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-'", AS, "'", sep="")))
    
    dictcol <- paste(obj, "@M5", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-", M5, sep="")))
    
    dictcol <- paste(obj, "@SP", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-'", SP, "'", sep="")))
    
    dictcol <- paste(obj, "@UR", colidx, sep="") 
    eval.parent(parse(text=paste(dictcol, "<-'", UR, "'", sep="")))
    
    return(invisible())
})

setMethod("getHeaderText", signature="refSeqDict", 
                                    definition=function(object, delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Returns Ref Data String (can be used for creating new BAM 
    #  file via bamWriter)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
                                        
    labels <- c("SN", "LN", "AS", "M5", "SP", "UR")
    n <- length(object@SN)
    
    if(n==0)
        return(character(0))
    
    seqs <- character(n)
    
    for(i in 1:n)
    {
        ans <- "@SQ"    
        if(nchar(object@SN[i])>0)
            ans <- paste(ans, delim, "SN:", object@SN[i], sep="")
        if(object@LN[i]>0)
            ans <- paste(ans, delim, "LN:", object@LN[i], sep="")
        if(nchar(object@AS[i])>0)
            ans <- paste(ans, delim, "AS:", object@AS[i], sep="")
        if(object@M5[i]>0)
            ans <- paste(ans, delim, "M5:", object@M5[i], sep="")
        if(nchar(object@SP[i])>0)
            ans <- paste(ans, delim, "SP:", object@SP[i], sep="")
        if(nchar(object@UR[i])>0)
            ans <- paste(ans, delim, "UR:", object@UR[i], sep="")
        seqs[i] <- ans
    }
    return(paste(seqs, collapse="\n"))
})


#  Return first or last part of refSeqDict data.frame
#  S3 Generic is supplied via importFrom in NAMESPACE

setMethod("head", "refSeqDict", function(x, n=6L, ...)
{
    stopifnot(length(n) == 1L)
    if (n < 0L)
        stop("[head.refSeqDict] n<0!")
    
    m <- length(x@SN)
    if(m==0)
        cat("[head.refSeqDict] Empty object.\n")
    
    n <- min(n, m)
    if(n == 0L)
        return(as.data.frame(new("refSeqDict")))
    else
        return(as.data.frame(x)[1:n, ])
})

# S3 Generic is supplied via importFrom in NAMESPACE
setMethod("tail", "refSeqDict", definition=function(x, n=6L, ...)
{
    stopifnot(length(n) == 1L)
    if (n < 0L)
        stop("[tail.refSeqDict] n<0!")
    m <- length(x@SN)
    if(m==0)
        cat("[tail.refSeqDict] Empty object.\n") 
    n <- min(n, m)
    if(n == 0L)
        return(as.data.frame(new("refSeqDict")))
    else
    {
        n <- m-n+1
        return(x@df[n:m, ])
    }
})

setMethod("show", "refSeqDict", function(object)
{
    if(length(object@SN)>0)
    {
        cat("An object of class \"", class(object), "\"\n", sep="")
        print(head(object))
    }else{
        cat("An empty object of class \"", class(object), "\".\n", sep="")
    }
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End refSeqDict
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  headerReadGroup
#  ReadGroup
#  ID Read Group identifier
#  CN Name of sequencing center
#  DS Description
#  FO Flow order
#  KS Nucleotides corresponding to key sequence of each read
#  LB Library
#  PG Programs used for processing the Read Group
#  PI Predicted median insert size
#  PL Sequencing Platform:
#     CAPILLARY, LS454, ILLUMINA, SOLID, HELICOS, IONTORRENT or PACBIO
#  SM Sample name.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



setMethod(f="initialize", signature="headerReadGroup",  
                                definition=function(.Object, hrg="", delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Read-Group part of Header data. See Sam Format 
    #  Specificatioin 1.3 (Header Section)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.character(hrg))
        stop("[headerReadGroup.initialize] Argument must be string.\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Samtools file format says: Unordered multiple @RG lines are allowed
    #  Each @RG segment comes as one string in hrg
    #  Number of @RG segments = length(hrg)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Split hgr into multiple @RG fragments
    #  In effect, hrg can be either given as vector with length > 1
    #  or as single vector with @RG entries separated by '\n'
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    hrg <- unlist(strsplit(hrg, "\n"))
    
    .Object@nrg <- length(hrg)
    
    .Object@ntl <- 12L                      # number of tags
    .Object@ID <- character(.Object@nrg)
    .Object@CN <- character(.Object@nrg)
    .Object@DS <- character(.Object@nrg)
    .Object@DT <- character(.Object@nrg)
    .Object@FO <- character(.Object@nrg)
    .Object@KS <- character(.Object@nrg)
    .Object@LB <- character(.Object@nrg)
    .Object@PG <- character(.Object@nrg)
    .Object@PI <- character(.Object@nrg)
    .Object@PL <- character(.Object@nrg)
    .Object@PU <- character(.Object@nrg)
    .Object@SM <- character(.Object@nrg)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Allows for empty object
    #  hrg="" or character(0)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if((length(hrg)==1 && nchar(hrg)==0) || length(hrg)==0)
    {
        .Object@nrg <- 0L
        return(.Object)
    }
    
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG",
                                                    "PI", "PL", "PU", "SM")
    
    for(i in 1:(.Object@nrg))
    {
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Split string into fields
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        tags <- unlist(strsplit(hrg[i], delim))
        
        if(tags[1] != "@RG")
            stop("First item of string must be @RG!\n")
        
        #  TODO: Routine does not check for:
        #  'Each @RG line must have a unique ID.' (SAM file format)
        
        tags <- tags[-1]
        ntags <- length(tags)
        for(j in 1:ntags)
        {
            if(substr(tags[j], 1, 2) == "ID")
                .Object@ID[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "CN")
                .Object@CN[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "DS")
                .Object@DS[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "DT")
                .Object@DT[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "FO")
                .Object@FO[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "KS")
                .Object@KS[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "LB")
                .Object@LB[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PG")
                .Object@PG[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PI")
                .Object@PI[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PL")
                .Object@PL[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "PU")
                .Object@PU[i] <- substring(tags[j], 4)
            
            if(substr(tags[j], 1, 2) == "SM")
                .Object@SM[i] <- substring(tags[j], 4)
        }
    }
    return(.Object)
})


setMethod("show", "headerReadGroup",  function(object)
{
    n <- object@nrg
    if(n > 0)
    {
        cat("An object of class \"", class(object), "\"\n", sep="")
        for(i in 1:n)
        {
            if(nchar(object@ID[i]) > 0)
                cat("ID:", object@ID[i], "\n")
            
            if(nchar(object@CN[i]) > 0)
                cat("CN:", object@CN[i], "\n")
            
            if(nchar(object@DS[i]) > 0)
                cat("DS:", object@DS[i], "\n")
            
            if(nchar(object@DT[i]) > 0)
                cat("DT:", object@DT[i], "\n")
            
            if(nchar(object@FO[i]) > 0)
                cat("FO:", object@FO[i], "\n")
            
            if(nchar(object@KS[i]) > 0)
                cat("KS:", object@KS[i], "\n")
            
            if(nchar(object@LB[i]) > 0)
                cat("LB:", object@LB[i], "\n")
            
            if(nchar(object@PG[i]) > 0)
                cat("PG:", object@PG[i], "\n")
            
            if(nchar(object@PI[i]) > 0)
                cat("PI:", object@PI[i], "\n")
            
            if(nchar(object@PL[i]) > 0)
                cat("PL:", object@PL[i], "\n")
            
            if(nchar(object@PU[i]) > 0)
                cat("PU:", object@PU[i], "\n")
            
            if(nchar(object@SM[i]) > 0)
                cat("SM:", object@SM[i], "\n")
            
            if(n > i)
                cat("\n")
        }
    }else{
        cat("An empty object of class \"", class(object), "\"\n", sep="")
    }
    return(invisible())
})

setMethod("getHeaderText", signature="headerReadGroup", 
                                        definition=function(object, delim="\t")
{
    n <- object@nrg
    if(n == 0)
        return(character(0))
    
    rgtxt <- character(n)
    for(i in 1:n)
    {
        #  ID should always be present
        txt <- paste(delim,"ID:",object@ID[i], sep="")
        
        if(nchar(object@CN[i]) > 0)
            txt <- paste(txt, delim,  "CN:", object@CN[i], sep="")
        
        if(nchar(object@DS[i]) > 0)
            txt <- paste(txt, delim, "DS:", object@DS[i], sep="")
        
        if(nchar(object@DT[i]) > 0)
            txt <- paste(txt, delim, "DT:", object@DT[i], sep="")
        
        if(nchar(object@FO[i]) > 0)
            txt <- paste(txt, delim, "FO:", object@FO[i], sep="")
        
        if(nchar(object@KS[i]) > 0)
            txt <- paste(txt, delim, "KS:", object@KS[i], sep="")
        
        if(nchar(object@LB[i]) > 0)
            txt <- paste(txt, delim, "LB:", object@LB[i], sep="")
        
        if(nchar(object@PG[i]) > 0)
            txt <- paste(txt, delim, "PG:", object@PG[i], sep="")
        
        if(nchar(object@PI[i]) > 0)
            txt <- paste(txt, delim, "PI:", object@PI[i], sep="")
        
        if(nchar(object@PL[i]) > 0)
            txt <- paste(txt, delim, "PL:", object@PL[i], sep="")
        
        if(nchar(object@PU[i]) > 0)
            txt <- paste(txt, delim, "PU:", object@PU[i], sep="")
        
        if(nchar(object@SM[i]) > 0)
            txt <- paste(txt, delim, "SM:", object@SM[i], sep="")
        
        # Remove last "\t"
        rgtxt[i] <- paste("@RG",txt,"\n",sep="")
    }
    return(paste(rgtxt, collapse=""))
})

setMethod("getVal", signature="headerReadGroup", 
                                        definition=function(object, member)
{
    if(!is.character(member))
        stop("Member must be character!\n")
    
    
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", 
                                                "PG", "PI", "PL", "PU", "SM")
    
    mtc <- match(member, tagLabs)
    
    if(any(is.na(mtc)))
        stop("Invalid member name!\n")
    
    l <- list()
    if(object@nrg == 0)
        return(l)
    
    for(i in 1:length(member))
    {
        if(mtc[i] == 1)
            l$ID <- object@ID
        else if(mtc[i] == 2)
            l$CN <- object@CN
        else if(mtc[i] == 3)
            l$DS <- object@DS
        else if(mtc[i] == 4)
            l$DT <- object@DT
        else if(mtc[i] == 5)
            l$FO <- object@FO
        else if(mtc[i] == 6)
            l$KS <- object@KS
        else if(mtc[i] == 7)
            l$LB <- object@LB
        else if(mtc[i] == 8)
            l$PG <- object@PG
        else if(mtc[i] == 9)
            l$PI <- object@PI
        else if(mtc[i] == 10)
            l$PL <- object@PL
        else if(mtc[i] == 11)
            l$PU <- object@PU
        else if(mtc[i] == 12)
            l$SM <- object@SM
    }
    return(l)
})

setMethod("setVal", signature="headerReadGroup", 
                                    definition=function(object, members, values)
{
    if(!is.character(members))
        stop("Member name must be character!\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check for valid values list
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.list(values))
        stop("Values must be given as list object")
    
    if(length(members)!=length(values))
        stop("Members and values must have same length!\n")
    
    if(any(lapply(values,length)!=object@nrg))
        stop("Length of values must equal number of read groups!")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Check for valid members entries
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG", "PI", 
                                                            "PL", "PU", "SM")
    
    mtc <- match(members, tagLabs)
    
    if(any(is.na(mtc)))
    {
        stop("Members must be valid Read Group Entries ",
                                        "(See SAM Format Specification 1.3!\n")
    }
    
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Create insertion code as string and parse in parent environment
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    n <- length(members)
    obj <- deparse(substitute(object))
    for(i in 1:n)
    {
        for(j in 1:object@nrg)
        {
            txt <- paste(obj, "@", members[i], "[", j, "]", "<-'",
                                                values[[i]][j], "'", sep="")
            eval.parent(parse(text=txt))            
        }

    }
    return(invisible())
})

setMethod("as.list", signature="headerReadGroup", 
                                            definition=function(x, ...)
{
    l <- list()
    l$ID <- x@ID
    l$CN <- x@CN
    l$DS <- x@DS
    l$DT <- x@DT
    l$FO <- x@FO
    l$KS <- x@KS
    l$LB <- x@LB
    l$PG <- x@PG
    l$PI <- x@PI
    l$PL <- x@PL
    l$PU <- x@PU
    l$SM <- x@SM
    return(l)
})


setMethod("addReadGroup", signature="headerReadGroup", 
                                            definition=function(object, l)
{
    if(!is.list(l))
        stop("'l' must be list")
    
    tagLabs <- c("ID", "CN", "DS", "DT", "FO", "KS", "LB", "PG", "PI", 
                            "PL", "PU", "SM")
    
    mtc <- match(names(l), tagLabs)
    if(any(is.na(mtc)))
        stop("All list names must be valid read group tags.")
    
    mtc <- match(tagLabs, names(l))
    if(is.na(mtc[1]))
       stop("There must be an ID given for new read group")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Increase number of read groups by 1
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    n <- object@nrg
    object@nrg <- n + 1L
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Insert ID tag
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(n == 0)
    {
        object@ID <- l[[mtc[1]]]
    }else{
        object@ID <- c(object@ID, l[[mtc[1]]])        
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Eventually insert other tags
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ins <- function(o, i)
    {
        if(!is.na(mtc[i]))
        {
            if(n == 0)
                o <- l[[mtc[i]]]
            else if(length(o) > 0)
                o <- c(o, l[[mtc[i]]])
            else
                o <- c(rep("", n), l[[mtc[i]]])
        }else{
            if(n == 0)
                o <- ""
            else
                o <- c(o,"")
        }
        
        return(o)
    }
    
    i <- 2
    object@CN <- ins(object@CN, i)
    i <- i + 1
    object@DS <- ins(object@DS, i)
    i <- i + 1
    object@DT <- ins(object@DT, i)
    i <- i + 1
    object@FO <- ins(object@FO, i)
    i <- i + 1
    object@KS <- ins(object@KS, i)
    i <- i + 1
    object@LB <- ins(object@LB, i)
    i <- i + 1
    object@PG <- ins(object@PG, i)
    i <- i + 1
    object@PI <- ins(object@PI, i)
    i <- i + 1
    object@PL <- ins(object@PL, i)
    i <- i + 1
    object@PU <- ins(object@PU, i)
    i <- i + 1
    object@SM <- ins(object@SM, i)

    return(object)
})



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End headerReadGroup
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  headerProgram
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", signature="headerProgram", 
                        definition=function(.Object, hp="", delim="\t")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Program part of Header data.
    #  See Sam Format Specificatioin 1.3 (Header Section)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    .Object@l <- list()
    
    if(!is.character(hp))
        stop("[headerProgram.initialize] Argument must be string.\n")
    
    # hp="" or character(0)
    if((length(hp)==1 && nchar(hp)==0)||length(hp)==0)
        return(.Object)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Split string into fields
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    tags <- unlist(strsplit(hp, delim))
    if(tags[1]!="@PG")
        stop("[headerProgram.initialize] First item of string must be @PG!\n")
    
    tags <- tags[-1]
    tagLabs <- c("ID", "PN", "CL", "PP", "DS", "VN")
    n <- length(tags)
    for(i in 1:n)
    {
        f <- substr(tags[i], 1, 2)
        mtc <- match(f, tagLabs)
        if(is.na(mtc))
            stop("Field identifier '", f, "' not in List!\n")
        .Object@l[[f]] <- substr(tags[i], 4, nchar(tags[i]))
    }
    return(.Object)
})

setMethod("getHeaderText", signature="headerProgram", 
                                definition=function(object, delim="\t")
{
    n <- length(object@l)
    if(n==0)
        return(character(0))
    
    rfstr <- character(n)
    for(i in 1:n)
        rfstr[i] <- paste(names(object@l)[i], object@l[[i]], sep=":")
    return(paste("@PG", paste(rfstr, collapse=delim), sep=delim))
})

setMethod("getVal", signature="headerProgram", 
                                    definition=function(object, member)
{
    if(!is.character(member))
        stop("[getVal.headerProgram] Member must be character!\n")
    
    tagLabs <- c("ID", "PN", "CL", "PP", "DS", "VN")
    mtc <- match(member[1], tagLabs)
    
    if(is.na(mtc))
        stop("[getVal.headerProgram] Invalid member name!\n")
    
    return(object@l[[member]])
})

setMethod("setVal", signature="headerProgram", 
                                definition=function(object, members, values)
{
    if(!is.character(members) || !is.character(values))
        stop("Member name and value must be character!\n")
    
    if(length(members)!=length(values))
        stop("Members and values must have same length!\n")
    
    tagLabs <- c("ID", "PN", "CL", "PP", "DS", "VN")
    mtc <- match(members, tagLabs)
    if(any(is.na(mtc)))
        stop("Members must be valid Program Entries (See SAM Format Specification 1.3!\n")
    
    n <- length(members)
    obj <- deparse(substitute(object))
    for(i in 1:n)
    {
        txt <- paste(obj, "@l$", members[i], "<-'", values[i], "'", sep="")
        eval.parent(parse(text=txt))
    }
    return(invisible())
})

setMethod("as.list", signature="headerProgram", 
                                    definition=function(x, ...){return(x@l)})

setMethod("show", "headerProgram", function(object)
{
    n <- length(object@l)
    if(n>0)
    {
        cat("An object of class \"", class(object), "\"\n", sep="")
        for(i in 1:length(object@l))
        {
        cat(names(object@l)[i], ":", object@l[[i]], "\n")
        }
    }else{
        cat("An empty object of class \"", class(object), "\"\n", sep="")
    }
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End headerProgram
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   bamHeaderText: Represents and manages textual version of bamHeader
#   See SAM Format Specification (v1.4-r985)
#
#   Contains header Segments :
#    head  = headerLine        : @HD Header Line
#    dict  = refSeqDict        : @SQ Reference Sequence dictionary
#    group = headerReadGroup   : @RG Read Group
#    prog  = headerProgram     : @PG Program
#
#    TODO:
#    com   = headerComment     : @CO One-line text comment
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Class definition and creational routines for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", signature="bamHeaderText", 
                                definition=function(.Object, bh="", delim="\n")
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Parses Header data (as reported by getHeaderText)
    #  See Sam Format Specification 1.3 (Header Section)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.character(bh))
        stop("[bamHeaderText.initialize] Argument must be string.\n")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Create empty header Set (so it's legal to call getHeaderText()')
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(length(bh)==1 && nchar(bh)==0)
    {
        .Object@head <- new("headerLine")
        .Object@dict <- new("refSeqDict")
        .Object@group <- new("headerReadGroup")
        .Object@prog <- new("headerProgram")
        return(.Object)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Split input string: Each fragment contains data for one header segment
    # 
    #  Identification of tags must be restricted on prefix 
    #  because there may be @RG entries present inside program segment
    #  (used as command line argument e.g. for aligner)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    bht <- unlist(strsplit(bh, split=delim))
    bht_pre <- substr(bht,1,3)
    
    # Read Header Line
    bhl <- bht[grep("@HD", bht_pre)]
    .Object@head <- new("headerLine", bhl)
    
    # Read Sequence Directory
    bsd <- bht[grep("@SQ", bht_pre)]
    .Object@dict <- new("refSeqDict", bsd)
    
    # Read Group
    brg <- bht[grep("@RG", bht_pre)]
    .Object@group <- new("headerReadGroup", brg)
    
    # Read Program Data
    bpd <- bht[grep("@PG", bht_pre)]
    .Object@prog <- new("headerProgram", bpd)
    
    # Read Text comment
    btc <- bht[grep("@CO", bht_pre)]
    com <- substring(btc, 3)
    return(.Object)
})

bamHeaderText <- function(head=NULL, dict=NULL, group=NULL, prog=NULL, com=NULL)
{
    bh <- new("bamHeaderText")
    if(!is.null(head))
    {
        if(is(head, "headerLine"))
            bh@head <- head
        else
            stop("[bamHeaderText] head must be 'headerLine'!")
    }
    if(!is.null(dict))
    {
        if(is(dict, "refSeqDict"))
            bh@dict <- dict
        else
        stop("[bamHeaderText] dict must be 'refSeqDict'")
    }
    
    if(!is.null(group))
    {
        if(is(group, "headerReadGroup"))
            bh@group <- group
        else
            stop("[bamHeaderText] group must be 'headerReadGroup'!")
    }
    
    if(!is.null(prog))
    {
        if(is(prog, "headerProgram"))
            bh@prog <- prog
        else
            stop("[bamHeaderText] prog must be 'headerProgram'!")
    }
    
    if(!is.null(com))
    {
        if(is.character(com))
            bh@com <- com
        else
            stop("[bamHeaderText] com must be 'character'!")
    }
    return(invisible(bh))
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Class definition and creational routines for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Public accessors for member objects for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod(f="headerLine", signature="bamHeaderText", 
                            definition=function(object) {return(object@head)})

setMethod(f="refSeqDict", signature="bamHeaderText", 
            definition=function(object) {return(object@dict)})



setMethod(f="headerReadGroup", signature="bamHeaderText", 
                            definition=function(object){return(object@group)})


setMethod(f="headerProgram", signature="bamHeaderText", 
                            definition=function(object){return(object@prog)})


setReplaceMethod("headerLine", "bamHeaderText", function(object, value)
{
    if(!is(value, "headerLine"))
        stop("[headerLine<-.bamHeaderText] value must be 'headerLine'!")
    object@head <- value
    return(object)
})


setReplaceMethod("refSeqDict", "bamHeaderText", function(object, value)
{
    if(!is(value, "refSeqDict"))
        stop("[refSeqDict<-.bamHeaderText] value must be 'refSeqDict'!")
    object@dict <- value
    return(object)
})


setReplaceMethod("headerReadGroup", "bamHeaderText", function(object, value)
{
    if(!is(value, "headerReadGroup"))
        stop("value must be 'headerReadGroup'!")
    object@group <- value
    return(object)
})


setReplaceMethod("headerProgram", "bamHeaderText", function(object, value)
{
    if(!is(value, "headerProgram"))
        stop("value must be 'headerProgram'!")
    object@prog <- value
    return(object)
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Public accessors for member objects for bamHeaderText
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



setMethod("getHeaderText", signature="bamHeaderText",
                                    definition=function(object, delim="\n")
{
    hd <- getHeaderText(object@head)
    if(length(hd)==0)
        return(character(0))
    hd <- paste(hd, delim, sep="")
    
    dt <- getHeaderText(object@dict)
    if(length(dt)==0)
        return(character(0))
    dt <- paste(dt, delim, sep="")
    
    gp <- getHeaderText(object@group)
    if(length(gp)>0)
        gp <- paste(gp, delim, sep="")
    
    pg <- getHeaderText(object@prog)
    if(length(pg)>0)
        pg <- paste(pg, delim, sep="")
    
    if(length(object@com)>0)
        cm <- paste(paste("@CO", object@com, sep="\t"), collapse=delim)
    else
        cm <- character(0)
    return(paste(hd, dt, gp, pg, cm, sep=""))
})

setMethod("bamHeader", "bamHeaderText",  function(object)
{
    return(new("bamHeader", .Call("init_bam_header", getHeaderText(object))))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamWriter class
#  Encapsulates an write-opened Connection to a BAM-file.
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize",  signature="bamWriter", 
          definition=function(.Object, header, filename)
{
    if(!is(header, "bamHeader"))
        stop("[initialize.bamWriter] header must be bamHeader!\n")
    
    if(!is.character(filename))
        stop("[initialize.bamWriter] filename must be character!\n")
    
    .Object@filename <- filename
    .Object@writer <- .Call("bam_writer_open", header@header, 
                                path.expand(filename), PACKAGE="rbamtools")
    
    return(.Object)
})

setMethod("filename",  "bamWriter",  function(object) return(object@filename))

setMethod("isOpen", signature="bamWriter", definition=function(con, rw="")
{
    return(!(.Call("is_nil_externalptr", con@writer, PACKAGE="rbamtools")))
})

setMethod(f="bamClose", signature="bamWriter", definition=function(object)
{
    return(invisible(.Call("bam_writer_close", 
                                        object@writer, PACKAGE="rbamtools")))
})

setMethod(f="bamSave", signature="bamWriter", 
                                definition=function(object, value, refid) 
{
    if(missing(refid))
        stop("[bamSave] refid is not optional!")
    
    if(!is.numeric(refid))
        stop("[bamSave] refid must be numeric")
    
    if(refid < 0)
        stop("[bamSave] refid must be >=0!")
    
    refid <- as.integer(refid)
    
    if(is(value, "bamAlign"))
    {
        return(invisible(.Call("bam_writer_save_align", object@writer, 
                            value@align, refid, PACKAGE="rbamtools")))
    }
    
    if(is(value, "bamRange")){
        return(invisible(.Call("bam_range_write", object@writer, 
                               value@range, refid, PACKAGE="rbamtools")))
    }
    else
        stop("bamSave: Saved object must be of type bamAlign or bamRange!\n")
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  gapList
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="initialize", "gapList", 
                definition=function(.Object, reader, coords, verbose=FALSE)
{
    if(!is(reader, "bamReader"))
    {
        cat("[initialize.gapList] Class of reader: ", class(reader), ".\n")
        stop("reader must be an instance of bamReader!\n")
    }
    
    if(length(coords) != 3)
        stop("coords must be 3-dim numeric (ref, start, stop)!\n")
    
    if(is.null(reader@index))
        stop("bamReader must have initialized index!\n")
    
    .Object@list <- .Call("gap_list_fetch", 
                reader@reader, reader@index, trunc(coords), PACKAGE="rbamtools")
    
    glsize <- .Call("gap_list_get_size", .Object@list, PACKAGE="rbamtools")
    
    if(verbose)
    {
        message("[initialize.gapList] Fetched list of size ", 
        format(glsize, big.mark=Sys.localeconv()[7]),
                                        " for refid ", coords[1], ".")
    }
    return(.Object)
})

# gapList function for retrieving objects in bamReader section

setMethod("size", signature="gapList", definition=function(object)
    {.Call("gap_list_get_size", object@list, PACKAGE="rbamtools")})

setMethod("nAligns", signature="gapList", definition=function(object)
    {.Call("gap_list_get_nAligns", object@list, PACKAGE="rbamtools")})

setMethod("nAlignGaps", signature="gapList", definition=function(object)
    {.Call("gap_list_get_nAlignGaps", object@list, PACKAGE="rbamtools")})

setMethod("show", "gapList", function(object)
{
    cat("An object of class '", class(object), "'. size: ",
                                                    size(object), "\n", sep="")
    
    cat("nAligns:", nAligns(object), "\tnAlignGaps:", nAlignGaps(object), "\n")
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  gapSiteList
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", "gapSiteList", 
                                definition=function(.Object, reader, coords)
{
    if(missing(reader) || missing(coords))
        return(.Object)
    
    if(!is(reader, "bamReader"))
        stop("reader must be an instance of bamReader!\n")
    
    if(length(coords) != 3)
        stop("coords must be 3-dim numeric (ref, start, stop)!\n")
    
    if(is.null(reader@index))
        stop("bamReader must have initialized index!\n")
    
    .Object@list <- .Call("gap_site_list_fetch", 
        reader@reader, reader@index, trunc(coords), PACKAGE="rbamtools")
    
    return(.Object)
})

setMethod("size", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_size", object@list, PACKAGE="rbamtools")})

setMethod("nAligns", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_nAligns", object@list, PACKAGE="rbamtools")})

setMethod("nAlignGaps", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_nAlignGaps", object@list, PACKAGE="rbamtools")})

setMethod("refID", signature="gapSiteList", definition=function(object)
{.Call("gap_site_list_get_ref_id", object@list, PACKAGE="rbamtools")})


setMethod("show",  "gapSiteList", function(object)
{
    cat("An object of class '", class(object), 
                        "'. size: ", size(object), "\n", sep="")
    
    cat("nAligns:", nAligns(object), "\tnAlignGaps:", nAlignGaps(object), "\n")
    
    return(invisible())
})

merge.gapSiteList <- function(x, y, ...)
{
    if(!is(y,"gapSiteList"))
        stop("'y' must be of class 'gapSiteList'!")
    
    res <- new("gapSiteList")
    xref <- refID(x)
    
    if(refID(x) != refID(y))
        warning("[merge] 'x' and 'y' have different refID's. Using refID(x)!")
    
    res@list <- .Call("gap_site_list_merge", x@list, y@list, refID(x))
    
    return(res)
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamGapList
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", "bamGapList", definition=function(.Object, reader)
{
    if(missing(reader))
    {
        .Object@list <- .Call("gap_site_ll_init")
        return(.Object)
    }
    
    if(!is(reader, "bamReader"))
        stop("reader must be an instance of bamReader!\n")
    if(is.null(reader@index))
        stop("bamReader must have initialized index!\n")
    
    ref <- getRefData(reader)
    ref$start <- 0L
    .Object@list <- .Call("gap_site_ll_fetch", 
                        reader@reader, reader@index, ref$ID, ref$start,
                        ref$LN, PACKAGE="rbamtools")
    
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  filter refdata for existing lists
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    sm <- .Call("gap_site_ll_get_summary_df", .Object@list, PACKAGE="rbamtools")
    mtc <- match(ref$ID, sm$ID)
    .Object@refdata <- ref[!is.na(mtc), ]
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Re-enumerate ID's to 1:n
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    .Object@refdata$ID <- .Call("gap_site_ll_reset_refid", 
                                        .Object@list, PACKAGE="rbamtools")
    
    # ToDo: merge refdata with summary df?
  
    return(.Object)
})



setMethod("size", signature="bamGapList", definition=function(object)
    {.Call("gap_site_ll_get_size", object@list, PACKAGE="rbamtools")})

setMethod("nAligns", signature="bamGapList", definition=function(object)
    {.Call("gap_site_ll_get_nAligns", object@list, PACKAGE="rbamtools")})

setMethod("nAlignGaps", signature="bamGapList", definition=function(object)
    {.Call("gap_site_ll_get_nAlignGaps", object@list, PACKAGE="rbamtools")})

setMethod("show", "bamGapList", function(object)
{
    bm <- Sys.localeconv()[7]
    
    cat("An object of class '", class(object), "'. size: ", 
                    format(size(object), big.mark=bm), "\n", sep="")
    
    cat("nAligns:", format(nAligns(object), big.mark=bm), 
            "\tnAlignGaps:", format(nAlignGaps(object), big.mark=bm), "\n")
    
    return(invisible())
})

summary.bamGapList <- function(object, ...)
{
    return(merge(object@refdata, 
                        .Call("gap_site_ll_get_summary_df", object@list)))
}

merge.bamGapList <- function(x, y, ...)
{
    if(!is(y, "bamGapList"))
        stop("[merge.bamGapList] y must be bamGapList!")
    
    if(size(x)==0)
        stop("[merge.bamGapList] size(x)==0!")
    
    if(size(y)==0)
        stop("[merge.bamGapList] size(y)==0!")
    
    mref <- merge(x@refdata, y@refdata, by="SN", all=T)
    
    n <- dim(mref)[1]
    .Call("gap_site_ll_set_curr_first", x@list)
    .Call("gap_site_ll_set_curr_first", y@list)
    
    res <- new("bamGapList")
    for(i in 1:n)
    {
        if(is.na(mref$ID.x[i]))
        {
            .Call("gap_site_ll_add_curr_pp", 
                        y@list, res@list, as.integer(i-1))
            # copy values from .y to .x side (for later use in ref)
            mref[i, 2:4] <- mref[i, 5:7]
        }
        else if(is.na(mref$ID.y[i]))
        {
            .Call("gap_site_ll_add_curr_pp", 
                        x@list, res@list, as.integer(i-1))
        }else{
            .Call("gap_site_ll_add_merge_pp", 
                        x@list, y@list, res@list, as.integer(i-1))
        }
    }
    
    # get l-part of refdata
    ref <- mref[, 1:4]
    names(ref) <- c("SN", "ID", "LN", "start")
    
    # reset ID to new values  
    ref$ID <- 0:(n-1)
    res@refdata <- ref
    return(res)
}

readPooledBamGaps <- function(infiles, idxInfiles=paste(infiles, ".bai", sep=""))
{
    if(!is.character(infiles))
        stop("infiles must be character!")
    
    if(any(!file.exists(infiles)))
        stop("Files (infiles) not found!")
    
    if(!is.character(idxInfiles))
        stop("idxInFiles must be character!")
    
    if(any(!file.exists(idxInfiles)))
        stop("idxInfiles not found!")
    
    n <- length(infiles)  
    if(length(idxInfiles)!=n)
        stop("infiles and idxInfiles must have same length!")
    
    bm <- Sys.localeconv()[7]
    for(i in 1:n)
    {
        bam <- infiles[i]
        reader <- bamReader(bam)
        if(!file.exists(idxInfiles[i]))
        {
            message("[readPooledBamGaps] Creating BAM-index.", appendLF=FALSE)
            createIndex(reader, idxInfiles[i])
            message("Finished.")
        }
        
        loadIndex(reader, idxInfiles[i])
        message("[readPooledBamGaps] (",
                    format(i, width=2), "/", n, ")", appendLF=FALSE)
        
        if(i==1)
        ga <- bamGapList(reader)
        else
        {
            ga1 <- bamGapList(reader)
            ga <- merge.bamGapList(ga, ga1)
        }
            message("\tList-size: ", format(size(ga), width=7, big.mark=bm), 
                "\tnAligns: ", format(nAligns(ga), width=13, big.mark=bm), ".")
    }
    
    message("[readPooledBamGaps] Finished.")
    return(ga)
}

readPooledBamGapDf <- function(infiles, idxInfiles=paste(infiles, ".bai", sep=""))
{ 
    ga <- readPooledBamGaps(infiles, idxInfiles=paste(infiles, ".bai", sep=""))
    dfr <- as.data.frame(ga)
    attr(dfr, "nAligns") <- nAligns(ga)
    attr(dfr, "nAlignGaps") <- nAlignGaps(ga)
    return(dfr)
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamRange
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Encapsulates a bunch of Alignment datasets that typically have been
#  read from a defined reference region in a BAM-file.
#  Technically,  the alignments are stored in a (C-implemented) double linked
#  list.
#  bamRange objects can be created by a reading procedure on an indexed
#  BAM-file. The alignments can be iterated, readed, written, deleted and
#  added. bamRange objects can be written to a BAM-file via an Instance
#  of bamWriter.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  bamRange parameters:
#  1: seqid      : 0-based index of seqid
#  2: qrBegin    : 0-based left boundary of query region (query range begin)
#  3: qrEnd      : 0-based right boundary of query region (query range end)
#  4: complex    : 0= all aligns included, 1= only aligns with n_cigar > 1
#                                                    included
#  5: rSeqLen    : Length of reference sequence (from getRefData)
#  6: qSeqMinLen : Minimum of query sequence length (= read length)
#  7: qSeqMaxLen : Maximum of query sequence length (= read length)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


bamRange <- function(object=NULL, coords=NULL, complex=FALSE)
{
    if(is.null(object))
        return(new("bamRange", NULL, NULL, FALSE))
    
    if(!is(object, "bamReader"))
        stop("object must be of class 'bamReader'!")
    
    if(!indexInitialized(object))
        stop("reader must have initialized index! Use 'loadIndex'!")

    return(new("bamRange", object, coords, complex))
}


setMethod(f="initialize", signature="bamRange", 
          definition=function(.Object, reader=NULL, coords=NULL, complex=FALSE)
{ 

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Create empty range
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(is.null(reader))
    {
        .Object@range <- .Call("bam_range_init", PACKAGE="rbamtools")
        return(.Object)
    }
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #   Create range from bam-file
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    if(!is(reader, "bamReader"))
        stop("reader must be an instance of bamReader!")
    
    # coords may either be missing or 3 entries are needed
    if(!is.null(coords))
    {
        if(length(coords)!=3)
            stop("coords must be numeric with length=3 (ref, start, stop)!")
    }

    
    if(is.null(reader@index))
        stop("bamReader must have initialized index!")
    
    if(!is(complex, "logical"))
        stop("complex must be logical!")
    
    if(length(complex) > 1)
        stop("complex must have length 1!")
    
    if(!indexInitialized(reader))
        stop("reader must have initialized index! Use 'loadIndex'!")
    
    .Object <- .Call("bam_range_fetch", reader@reader, 
                    reader@index, trunc(coords), complex, PACKAGE="rbamtools")
    
    return(.Object)
})


setMethod("size", signature="bamRange", definition=function(object)
    {.Call("bam_range_get_size", object@range, PACKAGE="rbamtools")})


setMethod("getCoords", "bamRange", function(object)
    { return(.Call("bam_range_get_coords", object@range))})

setMethod("getParams", "bamRange", function(object)
    { return(.Call("bam_range_get_params", object@range))})

setMethod("getSeqLen", "bamRange", function(object){
  return(.Call("bam_range_get_seqlen", object@range, PACKAGE="rbamtools"))
})


setMethod("getRefName", "bamRange", function(object)
    return(.Call("bam_range_get_refname", object@range, PACKAGE="rbamtools")))


setMethod("show", "bamRange", function(object){
  bm <- Sys.localeconv()[7]
  w <- 11
  r <- "right"
  cat("Class       : ", format(class(object), w=w, j=r)                   , "\n", sep="")
  cat("Size        : ", format(format(size(object), big.m=bm), w=w, j=r)   , "\n", sep="")

  params <- .Call("bam_range_get_params", object@range, PACKAGE="rbamtools")
  cat("Seqid       : ", format(format(params[1], big.m=bm), w=w, j=r)     , "\n", sep="")
  cat("qrBegin     : ", format(format(params[2], big.m=bm), w=w, j=r)     , "\n", sep="")
  cat("qrEnd       : ", format(format(params[3], big.m=bm), w=w, j=r)     , "\n", sep="")
  cat("Complex     : ", format(params[4], w=w, big.m=bm)                , "\n", sep="")
  cat("rSeqLen(LN) : ", format(format(params[5], big.m=bm), w=w, j=r)   , "\n", sep="")
  cat("qSeqMinLen  : ", format(format(params[6], big.m=bm), w=w, j=r)   , "\n", sep="")
  cat("qSeqMaxLen  : ", format(format(params[7], big.m=bm), w=w, j=r)   , "\n", sep="")
  
  refname <- .Call("bam_range_get_refname", object@range, PACKAGE="rbamtools")
  if(!is.null(refname))
  cat("Refname     : ", format(refname, w=w, j="right")       , "\n", sep="")  
  return(invisible())
})


setMethod("getAlignRange", "bamRange", function(object)
    return(.Call("bam_range_get_align_range", 
                object@range, PACKAGE="rbamtools")))


setMethod("getNextAlign", signature="bamRange", definition=function(object)
{
    ans <- .Call("bam_range_get_next_align", object@range, PACKAGE="rbamtools")
    # Must be checked because align list returns NULL when end is reached
    if(is.null(ans))
        return(ans)
    else
        return(new("bamAlign", ans))
})


setMethod("getPrevAlign", signature="bamRange", definition=function(object)
{
    return(new("bamAlign", .Call("bam_range_get_prev_align", 
                        object@range, PACKAGE="rbamtools")))
})


setMethod("stepNextAlign", signature("bamRange"), definition=function(object)
{
    .Call("bam_range_step_next_align", object@range)
    return(invisible())
})


setMethod("stepPrevAlign", signature("bamRange"), definition=function(object)
{
    .Call("bam_range_step_prev_align", object@range)
    return(invisible())
})


# Resets current align to NULL position (i.e. before first element)
# The next call to getNextAlign then returns the first element of list
setMethod("rewind", signature="bamRange", definition=function(object)
{
    invisible(.Call("bam_range_wind_back", object@range, PACKAGE="rbamtools"))
})


setMethod("push_back", signature="bamRange", definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("pushed object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_push_back", object@range, value@align, PACKAGE="rbamtools")
})


setMethod("pop_back", signature="bamRange", definition=function(object)
{
    .Call("bam_range_pop_back", object@range, PACKAGE="rbamtools")
})


setMethod("push_front", signature="bamRange", definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("pushed object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_push_front", object@range, value@align, PACKAGE="rbamtools")
})


setMethod("pop_front", signature="bamRange", definition=function(object)
{
    .Call("bam_range_pop_front", object@range, PACKAGE="rbamtools")
})


setMethod("writeCurrentAlign", signature="bamRange", definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("written object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_write_current_align",
                        object@range, value@align, PACKAGE="rbamtools")
})


setMethod("insertPastCurrent", signature="bamRange", 
                                            definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("written object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_insert_past_curr_align", 
                                object@range, value@align, PACKAGE="rbamtools")
})


setMethod("insertPreCurrent", signature="bamRange",
                                            definition=function(object, value)
{
    if(!is(value, "bamAlign"))
        stop("written object must be of class \"bamAlign\"\n")
    
    .Call("bam_range_insert_pre_curr_align", 
                        object@range, value@align, PACKAGE="rbamtools")
})


setMethod("moveCurrentAlign", signature="bamRange", 
                                        definition=function(object, target)
{
    if(!is(target, "bamRange"))
        stop("target must be bamRange!\n")
    
    .Call("bam_range_mv_curr_align", object@range, target@range)
    return(invisible())
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Rudimentary subsetting operator:
#  Does not change the order of elements, just returns subset
#  Therefore sorts given index i
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("[", signature="bamRange", function(x, i)
{
    i <- sort(as.integer(i))
    if(i[1] < 1)
        stop("No negative indices allowed. Use 'pop_front' or 'pop_back'!")
    
    if(i[length(i)] > size(x))
        stop("Out of bounds index (> size(x))!")
    
    return(.Call("bam_range_idx_copy", x@range, i, PACKAGE="rbamtools"))
})


setMethod("range2fastq", signature="bamRange",
    definition=function(object, filename, which, append=FALSE)
{
    message("[range2fastq] Function is deprecated. Use rangeToFastq.")
    return(rangeToFastq(object, filename, which, append))
})

setMethod("rangeToFastq", signature="bamRange",
    definition=function(object, filename, which, append=FALSE)
{
    if(!is.character(filename))
        stop("'filename' must be character!")
    
    if(!is.logical(append))
        stop("'append' must be logical!")
    
    if(missing(which))
    {
        .Call("bam_range_write_fastq", object@range, filename,
                            append, PACKAGE="rbamtools")
    }else{
        if(!is.numeric(which))
            stop("'which' must be numeric!")
        
        mx <- max(which)
        
        if(mx>size(object))
        {
            cat("[rangeToFastq] Maximum index (", mx,
                    ") is greater than size of range (",
                    size(object), ")!\n", sep="")
        }
        
        written <- .Call("bam_range_write_fastq_index",
            object@range, filename, as.integer(sort(unique(which))),
            append, PACKAGE="rbamtools")
        
        cat("[rangeToFastq]", written, "records written.\n")
    }
    return(invisible())
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Functions to read and display phred qualities from bamRange
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("getQualDf", "bamRange", function(object, prob=FALSE, ...)
{
    if(!is.logical(prob))
        stop("[getQualDf.bamRange] ")
    if(prob)
    {
        qdf <- .Call("bam_range_get_qual_df", 
                                        object@range, PACKAGE="rbamtools")
        
        rel <- function(x)
        {
            xs <- sum(x)
            if(xs > 0)
                return(x / xs)
            return(x)
        }
        
        res <- data.frame(lapply(qdf, rel))
        names(res) <- names(qdf)
        attributes(res)$col.sums <- unlist(lapply(qdf, sum))
        return(res)
    }
    return(.Call("bam_range_get_qual_df", object@range, PACKAGE="rbamtools"))
})


setMethod("getQualQuantiles", "bamRange", function(object, quantiles, ...)
{
    if(!is.numeric(quantiles))
        stop("[getQualQuantiles.bamRange] quantiles must be numeric!")
    
    if(!(all(quantiles >= 0) & all(quantiles <= 1)))
        stop("[getQualQuantiles.bamRange] all quantiles mustbe in [0, 1]")
    
    quantiles <- sort(unique(round(quantiles, 2)))

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Count qual values for each sequence position
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    qdf <- .Call("bam_range_get_qual_df", object@range, PACKAGE="rbamtools")
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Convert integer counts into column-wise relative values
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    rel <- function(x)
    {
        xs <- sum(x)
        if(xs>0)
            return(x/xs)
        return(x)
    }
    
    qrel <- data.frame(lapply(qdf, rel))
    names(qrel) <- names(qdf)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Walk through each column and extract row number
    #  for given quantile values
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    res <- .Call("get_col_quantiles", quantiles, qrel, PACKAGE="rbamtools")
    return(res)
})


setMethod("plotQualQuant",  "bamRange",  function(object)
{
    quant <- c(0.1, 0.25, 0.5, 0.75, 0.9)
    cols <- c("#1F78B4", "#FF7F00", "#E31A1C", "#FF7F00", "#1F78B4")
    
    qq <- getQualQuantiles(object, quant)
    
    maxQ <- floor(1.2 * max(qq))
    xv <- 1:ncol(qq)
    
    plot(xv, xv, ylim=c(0, maxQ), type="n", bty="n", las=1,
            ylab="phred score", xlab="sequence position",
            main="Phred Quantiles for sequence")
    
    lines(xv, qq[1, ], col=cols[1], lty=2)
    lines(xv, qq[2, ], col=cols[2], lty=1)
    lines(xv, qq[3, ], col=cols[3], lwd=2)
    lines(xv, qq[4, ], col=cols[4], lty=1)
    lines(xv, qq[5, ], col=cols[5], lty=2)
    
    legend("top", ncol=6, lty=c(2, 1, 1, 1, 2),
        lwd=c(1, 1, 2, 1, 1), col=cols, xjust=0.5,
        legend=c("10%", "25%", "50%", "75%", "90%"), bty="n", cex=0.8)
    
    return(invisible()) 
})



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  alignDepth
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  alignDepth parameters:
#  - - bamRange derived - -
#  1: seqid      : 0-based index of seqid
#  2: qrBegin    : 0-based left boundary of query region (query range begin)
#  3: qrEnd      : 0-based right boundary of query region (query range end)
#  4: complex    : 0= all aligns included, 1= only aligns with n_cigar > 1
#                                                    included
#  5: rSeqLen    : Length of reference sequence (from getRefData)
#  6: qSeqMinLen : Minimum of query sequence length (= read length)
#  7: qSeqMaxLen : Maximum of query sequence length (= read length)
#  - - alignDepth proprietary - -
#  6: gap     : 0=all aligns counted, 1=only gap adjacent match regions
#  counted
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



setMethod("alignDepth", "bamRange", function(object, gap=FALSE, flagFilter=0)
{
    if(!is.logical(gap))
        stop("gap must be logical!")
    flagFilter <- as.integer(flagFilter)
    if(flagFilter < 0)
        stop("flagFilter must be non-negative")
    
    return(.Call("bam_range_get_align_depth", 
                        object@range, gap, flagFilter, PACKAGE="rbamtools"))
})

setMethod("show", "alignDepth", function(object){
    bm <- Sys.localeconv()[7]
    w <- 11
    cat("Class       : ", format(class(object), w=w, j="right")  , "\n", sep="")
    cat("Seqid       : ", format(object@params[1], w=w, big.m=bm)    , "\n", sep="")
    cat("qrBegin     : ", format(object@params[2], w=w, big.m=bm)    , "\n", sep="")
    cat("qrEnd       : ", format(object@params[3], w=w, big.m=bm)    , "\n", sep="")
    cat("Complex     : ", format(object@params[4], w=w, big.m=bm)    , "\n", sep="")
    cat("rSeqLen(LN) : ", format(object@params[5], w=w, big.m=bm)    , "\n", sep="")
    cat("qSeqMinLen  : ", format(object@params[6], w=w, big.m=bm)    , "\n", sep="")  
    cat("qSeqMaxLen  : ", format(object@params[7], w=w, big.m=bm)    , "\n", sep="")
    cat("refname     : ", format(object@refname, w=w, j="right")     , "\n", sep="") 
    n <- 6
    x <- object@depth[1:n]
    names(x) <- object@pos[1:n]
    print(x)
    return(invisible())
})


setMethod("getDepth", "alignDepth", function(object, named=FALSE)
{
    if(!is.logical(named))
        stop("[getDepth.alignDepth] named must be logical!")
    if(named)
    {
        dp <- object@depth
        names(dp)=object@pos
        return(dp)
    }
    return(object@depth)
})


setMethod("getPos",     "alignDepth", function(object) {return(object@pos)})
setMethod("getParams", "alignDepth", function(object) {return(object@params)})


setMethod("plotAlignDepth", "alignDepth",
        function(object, start=NULL, end=NULL, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",  transcript="",
                    strand=NULL , log="y", cex.main=2,
                    col="grey50", fill="grey90", grid=TRUE, 
                    box.col="grey20", box.border="grey80", ... )
{
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Start and end positions for exon - rectangles
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    
    if(!is.null(start))
    {
        if(is.null(end))
            stop("'end' must be given when start is present")
        
        if(length(start) != length(end))
            stop("'start' and 'end' must have same length!")
        
        if(any(start <0 ) || any(end < 0))
           stop("No negative values allowed in 'start' and 'end'")
    }
    
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    #  Prepare align depth values for polygon plotting and
    #  logarithmic scale
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    nx <- length(object@pos)
    x <- c(object@pos[1], object@pos, object@pos[nx])
    y <- c(1, ifelse(object@depth == 0, 1, object@depth), 1)
    
    
    #  
    if(is.null(xlim))
        xlim <- c(x[1], x[nx])
    
    
    if(!is.null(start))
    {
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Prepare plot area and layout
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        
        # Reset values
        op <- par(no.readonly=TRUE)
        par(oma=c(3, 2, 1, 3))
        
        m <- matrix(c(1, 0, 2), ncol=1)
        layout(m, heights=c(5, lcm(0.2), 2))
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Do upper plot: align depth polygon
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        par(mar=c(0, 4, 3, 1) + 0.1)
        
        plot(x, y, type="n", las=1, main=main, xlim=xlim, 
            xlab="", ylab="", log=log, xaxt="n", bty="n",
            cex.axis=1.5, cex.main=cex.main, ...)
        
        polygon(x, y, col=fill, border=col, lwd=2)
        
        if(grid)
            grid()
        
        #
        mtext(paste("Refname:", object@refname), adj=1, cex=0.8)
        # ylab has to be positioned more outside
        mtext(ylab, side=2, line=4 , adj=0.5)
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Do lower plot: Draw exon boxes, x-axis and transcript text
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        par(mar=c(4, 4, 0, 1) + 0.1)
        plot(x, y, type="n", yaxt="n", xlim=xlim, ylim=c(0, 10), 
            cex.axis=1.5, bty="n", ylab="", xlab=xlab , 
            cex.lab=1.5, ...)
        
        # Draw horizontal gene - line
        if(is.null(strand))
            lines(xlim,c(8,8))
        else
        {
            if(strand == "+")
            {
                arrows(x0=xlim[1], y0=8, x1=xlim[2], y1=8, code=2)
            } else {
                arrows(x0=xlim[1], y0=8, x1=xlim[2], y1=8, code=1)
            }
        }
        
        
        # Draw exon boxes
        for(i in 1:length(start))
            rect(start[i], 6, end[i], 10, col=box.col, border=box.border)
        
        # Write transcript text
        text(xlim[1], 2, transcript, adj=0, cex=1.2)
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Cleanup
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        par(op)
        
    }else{
        
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        #  Alternative plot when no exon positions are given
        #  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # 
        plot(x, y, type="l", las=1, col=col, bty="n" , log=log,
                    xlab=xlab, ylab=ylab, main=main, ...)
        # log="" turns log scaling off.
        
        if(grid)
            grid()
        mtext(paste("Refname:", object@refname))
    }
    
    return(invisible())
})

## A function for plotting both the forward and reverse strands
## This should probably be called from within another type of function
## plots only the Align depth. Does not deal with transcripts / positions
setMethod("plotAlignDepths", "alignDepth",
        function(object, xlim=NULL,
                    main="Align Depth", xlab="Position", 
                    ylab="Align Depth",
                    log="y", cex.main=1,
                    col="black", fill.fw="grey90", fill.rv="grey40", grid=TRUE, 
                    ... )
{
    ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    ##  Prepare align depth values for polygon plotting and
    ##  logarithmic scale
    ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
    nx <- length(object@pos)
    x <- c(object@pos[1], object@pos, object@pos[nx])
    y_fw <- c(0, object@depth, 0)
    y_rv <- c(0, object@depth_r, 0)
    ## if logs we don't like 0s. But more complicated is handling a reverse
    ## plot So let's do:
    if(log == "y"){
        y_fw = 1 + y_fw
        y_rv = 1 / (1 + y_rv)
    }else{
        y_rv = -y_rv
    }
    
    if(is.null(xlim))
        xlim <- range(x)
    ylim <- range(c(y_fw, y_rv))
    ## then set up the plot
    plot(x, y_fw, type='n', ylim=ylim, xlim=xlim,
         xlab=xlab, ylab=ylab, main=main,
         cex.main=cex.main, log=log, ...)
    polygon(x, y_fw, col=fill.fw, border=col, lwd=1)
    polygon(x, y_rv, col=fill.rv, border=col, lwd=1)

    if(grid)
        grid
    mtext(paste("Refname:", object@refname), adj=1, cex=0.8)
})
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Count nucleotides
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("countNucs", "bamRange", function(object)
                { return(.Call("bam_range_count_nucs",
                            object@range, PACKAGE="rbamtools"))})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#
#  bamAlign
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  bamAlign encapsulates all contained data in a single dataset in
#  a BAM-file.
#  bamAlign objects can be read from a bamReader instance and written to a
#  bamWriter instance. All contained data can be read and written via
#  accessors functions.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


setMethod(f="initialize", signature="bamAlign",
                                    definition=function(.Object,align=NULL)
{
    .Object@align <- align
    return(.Object)
})


setMethod("show", "bamAlign", function(object)
{
    bm <- Sys.localeconv()[7]
    w <- 11
    r <- "right"
    cat("Class       : ", format(class(object)  , w=w, j=r)                     , "\n", sep="")
    cat("refId       : ", format(refID(object)  , w=w, j=r)                     , "\n", sep="") 
    cat("Position    : ", format(format(position(object), big.m=bm), w=w, j=r)   , "\n", sep="")
    
    cat("\nCigar Data  :\n")
    print(cigarData(object))
})


bamAlign <- function(qname, qseq, qqual, cigar, refid, position, 
                flag=272L, alqual=10L, mrefid=(-1L), mpos=(-1L), insertsize=0L)
{
    if(missing(qname))
        stop("[bamAlign] Missing query name!")
    
    if(missing(qseq))
        stop("[bamAlign] Missing query sequence string!")
    
    if(missing(qqual))
        stop("[bamAlign] Missing query quality string!")
    
    if(missing(cigar))
        stop("[bamAlign] Missing CIGAR string!")
    
    if(missing(refid))
        stop("[bamAlign] Missing refid!")
    
    if(missing(position))
        stop("[bamAlign] Missing position!")
    
    
    if(!is.character(qname))
        stop("[bamAlign] Query name must be character!")
    
    if(!is.character(qseq))
        stop("[bamAlign] Query sequence must be character!")
    
    if(!is.character(qqual))
        stop("[bamAlign] Query quality must be character!")
    
    if(nchar(qseq)!=nchar(qqual))
        stop("Query sequence string and quality string must have equal size!")
    
    
    if(!is.character(cigar))
        stop("[bamAlign] CIGAR string must be character!")
    
    if(!is.numeric(refid))
        stop("[bamAlign] refid must be numeric!")
    
    if(!is.numeric(position))
        stop("[bamAlign] position must be numeric!")
    
    refid <- as.integer(refid)
    position <- as.integer(position)
    
    # String-values:
    # 1) query-name
    # 2) query sequence
    # 3) quality string
    # 4) CIGAR string
    
    strval <- character(4)
    strval[1] <- qname
    strval[2] <- qseq
    strval[3] <- qqual
    strval[4] <- cigar
    
    # Integer-values:
    # 1) refid
    # 2) position
    # 3) flag
    # 4) align quality
    # 5) mate refid
    # 6) mate position
    # 7) insert size
    intval <- integer(4)
    intval[1] <- refid
    intval[2] <- position
    intval[3] <- flag
    intval[4] <- alqual
    intval[5] <- mrefid
    intval[6] <- mpos
    intval[7] <- insertsize
    
    ans <- .Call("bam_align_create", strval, intval)
    
    # Must be checked because align list returns NULL when end is reached
    if(is.null(ans))
    {  
        cat("[bamAlign] Align creation unsuccessful! Data inconsistency?\n")
        return(NULL)
    }
    
    return(new("bamAlign", ans))
}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  bamAlign Member Reader functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod(f="name", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_name", object@align, PACKAGE="rbamtools")
})

setMethod(f="refID", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_refid", object@align, PACKAGE="rbamtools")
})

setMethod(f="position", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_position", object@align, PACKAGE="rbamtools")
})

setMethod("nCigar", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_nCigar", object@align, PACKAGE="rbamtools")
})

setMethod(f="cigarData", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_cigar_df", object@align, PACKAGE="rbamtools")
})

setMethod(f="mateRefID", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_mate_refid", object@align, PACKAGE="rbamtools")
})

setMethod(f="matePosition", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_mate_position", object@align, PACKAGE="rbamtools")
})

setMethod(f="insertSize", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_insert_size", object@align, PACKAGE="rbamtools")
})

setMethod(f="mapQuality", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_map_quality", object@align, PACKAGE="rbamtools")
})

setMethod(f="alignSeq", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_segment_sequence", object@align, PACKAGE="rbamtools")
})

setMethod(f="alignQual", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_qualities", object@align, PACKAGE="rbamtools")
})

setMethod(f="alignQualVal", signature="bamAlign", definition=function(object)
{
    .Call("bam_align_get_qual_values", object@align, PACKAGE="rbamtools")
})




# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  1.4  The alignment section: mandatory fields
#       2. FLAG: bitwise FLAG
#  Queries against alignment flag (Readers and Accessors)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x1 template having multiple segments in sequencing
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("paired", "bamAlign", function(object)
{
    .Call("bam_align_is_paired", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="paired",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_paired", 
                    object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x2 each segment properly aligned according to the aligner
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("properPair", "bamAlign", function(object)
{
    .Call("bam_align_mapped_in_proper_pair", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="properPair",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_mapped_in_proper_pair",
                    object@align, value, PACKAGE="rbamtools")
    
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x4 segment unmapped
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("unmapped", "bamAlign", function(object)
{
    .Call("bam_align_is_unmapped", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="unmapped",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_unmapped",
                    object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x8 next segment in the template unmapped
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("mateUnmapped", "bamAlign", function(object)
{
    .Call("bam_align_mate_is_unmapped", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="mateUnmapped",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_mate_is_unmapped",
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x10 SEQ being reverse complemented
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("reverseStrand", "bamAlign", function(object)
{
    .Call("bam_align_strand_reverse", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="reverseStrand",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_strand_reverse", 
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x20 SEQ of the next segment in the template being reversed
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("mateReverseStrand", "bamAlign", function(object)
{
    .Call("bam_align_mate_strand_reverse", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="mateReverseStrand",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_mate_strand_reverse",
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x40 the first segment in the template
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("firstInPair",  "bamAlign",  function(object)
{
    .Call("bam_align_is_first_in_pair", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="firstInPair", 
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("class bamReader, FirstInPair setter: value must be boolean")
     
    .Call("bam_align_set_is_first_in_pair", 
            object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x80 the last segment in the template
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

setMethod("secondInPair", "bamAlign", function(object)
{
    .Call("bam_align_is_second_in_pair", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="secondInPair",
    signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_second_in_pair", 
        object@align, value, PACKAGE="rbamtools")
                     
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x100 secondary alignment
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("secondaryAlign", "bamAlign", function(object)
{
  .Call("bam_align_is_secondary_align",object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="secondaryAlign", signature="bamAlign",
                                        definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_secondary_align", 
                    object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x200 not passing quality controls
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("failedQC", "bamAlign", function(object)
{
    return(.Call("bam_align_fail_qc", object@align, PACKAGE="rbamtools"))
})

setReplaceMethod(f="failedQC", 
        signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("class bamReader, failedQC setter: value must be boolean")
    
    .Call("bam_align_set_fail_qc", object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x400 PCR or optical duplicate
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("pcrORopt_duplicate", "bamAlign", function(object)
{
    return(.Call("bam_align_is_pcr_or_optical_dup",
                object@align, PACKAGE="rbamtools"))
})

setReplaceMethod(f="pcrORopt_duplicate",
        signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("class bamReader, Duplicate setter: value must be boolean")
    .Call("bam_align_set_is_pcr_or_optical_dup", 
                            object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  0x800 supplementary alignment
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("suppAlign", "bamAlign", function(object)
{
    .Call("bam_align_is_supplementary_align",object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="suppAlign",
        signature="bamAlign", definition=function(object, value)
{
    if(!is.logical(value))
        stop("value must be boolean")
    
    .Call("bam_align_set_is_supplementary_align", 
        object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  flag
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("flag", "bamAlign", function(object)
{
  .Call("bam_align_get_flag", object@align, PACKAGE="rbamtools")
})

setReplaceMethod(f="flag", signature="bamAlign",
                                    definition=function(object, value)
{
    if(!is.numeric(value))
        stop("value must be numeric")
    
    if(!is.integer(value))
    {
        value <- as.integer(value)
        message("[flag] Value is coerced to integer.")
    }
    
    .Call("bam_align_set_flag", object@align, value, PACKAGE="rbamtools")
    return(object)
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: Queries against alignment flag (Readers and Accessors)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
setMethod("countNucs","bamAlign",function(object)
{
    return(.Call("bam_align_count_nucs", object@align, PACKAGE="rbamtools"))
})


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   End: bamAlign
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   coercing
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

as.data.frame.bamRange <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("bam_range_get_align_df", x@range, PACKAGE="rbamtools"))
}

as.data.frame.gapList <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("gap_list_get_df", x@list, PACKAGE="rbamtools"))
}

as.data.frame.gapSiteList <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("gap_site_list_get_df", x@list, PACKAGE="rbamtools"))
}

as.data.frame.bamGapList <- function(x, row.names=NULL, optional=FALSE, ...)
{
    return(.Call("gap_site_ll_get_df", x@list,
                                        x@refdata$SN, PACKAGE="rbamtools"))
}

as.data.frame.refSeqDict <- function(x, row.names=NULL, optional=FALSE, ...)
{
    n <- length(x@SN)
    if(n == 0)
    {
        return(data.frame(SN=character(0), LN=numeric(0), AS=character(0),
                        M5=numeric(0), SP=character(0) , UR=character(0)))
    }
    
    if(is.null(row.names))
        row.names <- 1:(length(x@SN))
    else if(length(row.names) != length(x@SN))
        stop("length(row.names)!=length(x@SN)!")
    
    return(data.frame(SN=x@SN, LN=x@LN, 
                AS=x@AS ,M5=x@M5, SP=x@SP, UR=x@UR, row.names=row.names))
}


setAs("bamRange","data.frame", function(from)
{
    return(.Call("bam_range_get_align_df", from@range, PACKAGE="rbamtools"))
})

setAs("gapList", "data.frame", function(from)
{
    return(.Call("gap_list_get_df", from@list, PACKAGE="rbamtools"))
})

setAs("refSeqDict", "data.frame", function(from)
{
    return(data.frame(SN=from@SN, LN=from@LN, AS=from@AS, M5=from@M5,
                    SP=from@SP, UR=from@UR, row.names=1:length(from@SN)))
})

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  End: coercing
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  Miscellaneous functions
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #


createIdxBatch <- function(bam, idx=paste(bam, ".bai", sep=""), rebuild=FALSE)
{
    if(!is.character(bam))
        stop("'bam' must be character!")
    
    if(!is.character(idx))
        stop("'idx' must be character!")
    
    if(length(bam)!=length(idx))
        stop("'bam' and 'idx' must have same length!")
    
    if(!is.logical(rebuild))
        stop("'rebuild' must be logical!")
    
    if(length(rebuild) > 1)
        stop("'rebuild' must have length 1!")
    
    
    n <- length(bam)
    for(i in 1:n)
    {
        message("[", format(i, width=2), "/", n, "] ", appendLF=FALSE)
        if(!file.exists(bam[i]))
        stop("File ", i, " does not exist!")
        
        if(rebuild[1])
        {
        reader <- bamReader(bam[i])
        createIndex(reader, idx[i])
        bamClose(reader)       
        }else{
            if(!file.exists(idx[i]))
            {
                reader <- bamReader(bam[i])
                createIndex(reader, idx[i])
                bamClose(reader)     
            }
        }
        message("OK.")
    }
    return(invisible())
}

create.idx.batch <- function(bam, idx=paste(bam, ".bai", sep=""), rebuild=FALSE)
{ .Deprecated("createIdxBatch",package="rbamtools") }



countTextLines <- function(filenames)
{
    if(!is.character(filenames))
        stop("[countTextLines] filename must be character!")
    
    if(!all(file.exists(filenames)))
        stop("[countTextLines] Missing files!")
    
    n <- length(filenames)
    res <- numeric(n)
    bm <- Sys.localeconv()[7]
    
    for(i in 1:n)
    {
        cat("[countTextLines] Counting '", basename(filenames[i]), "'", sep="")
        res[i] <- .Call("count_text_lines", filenames[i])
        cat("\t found:", format(res[i], big.mark=bm), ".\n")
    }
    cat("[countTextLines] Finished. Found", 
                                format(sum(res), big.mark=bm), "lines.\n")
    return(res)
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#   Unexported and undocumented routines
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

readSepGapTables <- function(bam, profo, defo="sep_gap",
                                            idx=paste(bam, ".bai", sep=""))
{
    require(rbamtools)
    fo <- file.path(profo, defo)
    
    if(!file.exists(fo))
        dir.create(fo)
    bm <- Sys.localeconv()[7]
    
    n <- length(bam)
    for(i in 1:n)
    {
        cat("[readSepGapTables] i:(", format(i, width=2), "/", n, ")", sep="")
        
        if(!file.exists(bam[i]))
            stop("[readSepGapTables] i:", i, " File does not exist!")
        
        reader <- bamReader(bam[i])
        
        if(!file.exists(idx[i]))
            createIndex(reader, idx[i])
        
        loadIndex(reader, idx[i])
        
        if(i==1)
        {
            bsl <- bamGapList(reader)
            dfr <- as.data.frame(bsl)
            save(dfr, file=file.path(fo, paste("bsl_", i, ".RData", sep="")))
            write.table(dfr, file=file.path(fo, 
                paste("bsl_", i, ".csv", sep="")), sep=";", row.names=FALSE)
            
            cat("\r[readSepGapTables] i:(", format(i, width=2),
                "/", n, ")\tnr sites: ", format(size(bsl), big.mark=bm,
                                                width=9), "\n", sep="")
            
        }else{
            # save site-table for bam[i]
            bsli <- bamGapList(reader)
            dfri <- as.data.frame(bsli)
            save(dfri, file=file.path(fo, paste("bsl_", i, ".RData", sep="")))
            write.table(dfri, file=file.path(fo, paste("bsl_", i, ".csv", sep="")), 
                                                    sep=";", row.names=FALSE)
            
            # save cum-merged site-table for bam[i]
            bsl <- merge(bsl, bsli)
            dfr <- as.data.frame(bsl)
            
            save(dfr, file=file.path(fo, paste("bsl_c_", i, ".RData", sep="")))
            
            write.table(dfr, file=file.path(fo, paste("bsl_c_", i, 
                    ".csv", sep="")), sep=";", row.names=FALSE)
            
            cat("\r[readSepGapTables] i:(", format(i, width=2),
                "/", n, ")\tnr sites: ",  format(size(bsl), big.mark=bm,
                                                width=9), "\n", sep="")
        }
    }
    cat("[readSepGapTables] Finished.")
}

#  Unexported and undocumented
readAccGapTables <- function(bam, profo, defo="sep_gap",
                                            idx=paste(bam, ".bai", sep=""))
{
    # setup
    require(rbamtools)
    fo <- file.path(profo, defo)
    
    if(!file.exists(fo))
        dir.create(fo)
    
    bm <- Sys.localeconv()[7]
    
    n <- length(bam)
    res <- data.frame(i=1:n, sites=numeric(n), acc=numeric(n), nov=numeric(n))
    
    for(i in 1:n)
    {
        cat("[readAccGapTables] i:(", format(i, width=2), "/", n, ")", sep="")
        
        if(!file.exists(bam[i]))
            stop("[readAccGapTables] i:", i, " File does not exist!")
        
        reader <- bamReader(bam[i])
        if(!file.exists(idx[i]))
            createIndex(reader, idx[i])
        loadIndex(reader, idx[i])
        
        if(i==1) # first bam file
        {
            bsl <- bamGapList(reader)
            dfr <- as.data.frame(bsl)
            save(dfr, file=file.path(fo, paste("bsl_", i, ".RData", sep="")))
            
            # write report values
            res$sites[1] <- dim(dfr)[1]
            res$acc[1] <- res$sites[1]
            res$nov[1] <- res$sites[1]
            
            # printout status line
            cat("\r[readAccGapTables] i:(", format(i, width=2),
                "/", n, ")\tnr sites: ",  format(size(bsl), big.mark=bm,
                                                width=9), "\n", sep="")
            
        }else{    # subsequent bam file
            
            # read sites from bam[i]
            bsli <- bamGapList(reader)
            dfri <- as.data.frame(bsli)
            
            # extract novel sites as difference from accumulated sites
            mrg <- merge(dfri[, c("id", "seqid", "lend", "rstart")], 
                        dfr[, c("id", "seqid", "lend", "rstart")], 
                        by=c("seqid", "lend", "rstart"), all.x=TRUE)
            
            mrg$new <- is.na(mrg$id.y)
            mrg$id.x <- NULL
            mrg$id.y <- NULL
            nov <- merge(dfri, mrg, all=T)
            nov <- nov[nov$new, c(4, 1, 5, 2, 3, 6:13)]
            nov$new <- NULL
            nov <- nov[order(nov$seqid, nov$lend, nov$rstart), ]
            
            # Save image
            save(dfri, nov, dfr , file=file.path(fo, paste("acc_", i,
                                                        ".RData", sep="")))
            
            # create new accumulation via merging
            bsl <- merge(bsl, bsli)
            dfr <- as.data.frame(bsl)
            
            # write report values
            res$sites[i] <- dim(dfri)[1]
            res$acc[i] <- dim(dfr)[1]
            res$nov[i] <- dim(nov)[1]
            
            # print-out status line
            cat("\r[readAccGapTables] i:(", format(i, width=2), "/", n,
                ")\tnr sites: ", format(size(bsl), big.mark=bm, width=9),
                                "\n", sep="")
        }
    }
    
    # save final image
    save(dfr, file=file.path(fo, "bsl_acc_final.RData"))
    
    cat("[readAccGapTables] Final sites: ", 
                            format(size(bsl), big.mark=bm, width=9), "\n")
    
    return(res)
}

#  Unexported and undocumented
copy_fastq <- function(infile, outfile, which, append=FALSE)
{
    if(!is.character(infile))
        stop("[copy_fastq] infile must be character!")
    
    if(!is.character(outfile))
        stop("[copy_fastq] outfile must be character!")
    
    if(!is.numeric(which))
        stop("[copy_fastq] which must be numeric!")
    
    if(any(which<=0))
        stop("[copy_fastq] Only positive numbers in which allowed!")
    
    which <- as.integer(sort(unique(which)))
    if(!is.logical(append))
        stop("[copy_fastq] append must be logical!")
    
    if(!file.exists(infile))
        stop("[copy_fastq] infile does not exist!")
    
    ans <- .Call("copy_fastq_records", infile, outfile, which,
                                            append, PACKAGE="rbamtools")
    
    bm <- Sys.localeconv()[7]
    
    if(length(which)<ans){
        cat("[copy_fastq] Incomplete copy: ", format(ans, big.mark=bm), "/", 
                format(length(which), big.mark=bm), ". EOF reached?", sep="")
    }
    return(invisible(ans))
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Function declaration for extraction of regions into separate BAM files:
#
# Extracts alignments from given (genetic) ranges and BAM files
# into a set of output BAM files.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

extractBamRegions <- function(bamFiles, ranges,
                idxFiles=paste(bamFiles, "bai", sep="."),
                outFiles=paste("bam", 1:length(bamFiles),".bam", sep=""))
{
    if(!is.character(bamFiles))
        stop("'bamFiles' must be character!")
    
    if(!is.character(idxFiles))
        stop("'idxFiles' must be character!")
    
    if(!is.character(outFiles))
        stop("'outFiles' must be character!")
    
    if(!all(file.exists(bamFiles)))
        stop("bam file(s) not found!")
    
    if(!all(file.exists(idxFiles)))
        stop("idx file(s) not found!")
    
    if(length(bamFiles) != length(idxFiles))
        stop("bamFiles and idxFiles must have equal length!")
    
    if(length(bamFiles) != length(outFiles))
        stop("bamFiles and outFiles must have equal length!")
    
    if(!all(ranges$end > ranges$start))
        stop("All 'end' positions must be greater than 'start'!")
    
    
    nr <- nrow(ranges)
    nf <- length(bamFiles)
    
    for(i in 1:nf)
    {
        reader <- bamReader(bamFiles[i], idx=TRUE)
        cat("[i] ", format(i, width=2), "\n")
        header <- getHeader(reader)
        writer <- bamWriter(header, outFiles[i])
        
        for(j in 1:nr)
        {
            sn <- getRefCoords(reader,as.character(ranges$seqid[j]))
            coords <- c(sn[1], ranges$start[j], ranges$end[j])
            brg <- bamRange(reader, coords)
            bamSave(writer, brg, refid=sn[1])        
        }
        bamClose(reader)
        bamClose(writer)
    }
    return(invisible())
}



# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#  End of File (rbamtools.r)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
`%||%` <- function(x, y) if (is.null(x)) y else x

#' Merge two lists and overwrite latter entries with former entries
#' if names are the same.
#'
#' For example, \code{list_merge(list(a = 1, b = 2), list(b = 3, c = 4))}
#' will be \code{list(a = 1, b = 3, c = 4)}.
#' @param list1 list
#' @param list2 list
#' @return the merged list.
#' @examples
#' stopifnot(identical(syberiaStages:::list_merge(list(a = 1, b = 2), list(b = 3, c = 4)),
#'                     list(a = 1, b = 3, c = 4)))
#' stopifnot(identical(syberiaStages:::list_merge(NULL, list(a = 1)), list(a = 1)))
# TODO: (RK) This is a duplicate of the function in mungebits -- is there
# any way to pull them out into one place? Maybe Ramd?
list_merge <- function(list1, list2) {
  list1 <- list1 %||% list()
  # Pre-allocate memory to make this slightly faster.
  list1[Filter(function(x) nchar(x) > 0, names(list2) %||% c())] <- NULL
  for (i in seq_along(list2)) {
    name <- names(list2)[i]
    if (!identical(name, NULL) && !identical(name, "")) list1[[name]] <- list2[[i]]
    else list1 <- append(list1, list(list2[[i]]))
  }
  list1
}

#' Parse functions out of a custom resource.
#'
#' @param functions character. The names of functions to parse out.
#' @param provided_env environment. The environment the resource was loaded from.
#' @param type character. The keyword for the resource.
#' @param resource_type character. The type of the resource (e.g., "classifier",
#'   "adapter", etc.). This will be used to generate error messages.
#' @param strict logical. Whether or not to error if the functions are not found.
#' @return a list containing keys same as the \code{functions} argument.
#'    and predict functions.
parse_custom_functions <- function(functions, provided_env, type,
                                   resource_type = 'classifier', strict = TRUE) {
  provided_fns <- setNames(vector('list', length(functions)), functions)
  for (function_type in names(provided_fns)) {
    fn <- Filter(
      function(x) is.function(provided_env[[x]]),
      grep(function_type, ls(provided_env), value = TRUE)
    )
    # TODO: (RK) Refactor this to be more careful about idempotent resources.
    error <- function(snip = 'a') paste0("The custom ", resource_type, " in ",
      "lib/", resource_type, "s/", type, ".R should define ", snip, " '",
      testthat::colourise(function_type, 'green'), "' function.")
    if (length(fn) == 0 && identical(strict, TRUE)) stop(error(), call. = FALSE)
    else if (length(fn) > 1)
      stop(error('only one'), " Instead, you defined ", length(fn), ", namely: ",
           paste0(fn, collapse = ', '), call. = FALSE)
    else if (length(fn) == 1)
      provided_fns[[function_type]] <- provided_env[[fn]]
  }
  provided_fns
}

# Helper function to serialize a tundraContainer of xgboost model object
#
serialize_xgb_object <- function(object) {
	file_save <- tempfile()
  on.exit(unlink(file_save))
  xgboost::xgb.save(object$output$model, file_save)
  stopifnot(!is.na(as.integer(file.info(file_save)$size)))
  object$output$model <- NULL
  con <- file(file_save, 'rb')
  on.exit(close(con), add = TRUE)
  object <- structure(
	            class = 'special_serialized_object', 
							list(
							  deserialize = function(x) {
                  file_load <- tempfile()
                  on.exit(unlink(file_load))
                  con <- file(file_load, 'wb')
                  on.exit(close(con), add = TRUE)
                  writeBin(x$xgb.bin, con, useBytes = TRUE)
                  x$container$output$model <- xgboost::xgb.load(file_load)
                  invisible(x$container)
                }, 
								object = list(container = object, 
							                xgb.bin = readBin(con, raw(), 
															                  n = file.info(file_save)$size))
							)
					  )
	invisible(object)
}
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
		require(xgboost)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()
    if (is(object, 'tundraContainer') &&
        # Hack for model object requiring customized
        # serializer, e.g., xgb.Booster
        is(object$output$model, 'xgb.Booster')) {
      file_save <- tempfile()
      on.exit(unlink(file_save))
      xgboost::xgb.save(object$output$model, file_save)
      stopifnot(!is.na(as.integer(file.info(file_save)$size)))
      object$output$model <- NULL
      con <- file(file_save, 'rb')
      on.exit(close(con), add = TRUE)
      object <- structure(class = 'special_serialized_object', list(
                  deserialize = function(x) {
                    file_load <- tempfile()
                    on.exit(unlink(file_load))
                    con <- file(file_load, 'wb')
                    on.exit(close(con), add = TRUE)
                    writeBin(x$xgb.bin, con, useBytes = TRUE)
                    close(con)
                    x$container$output$model <- xgboost::xgb.load(file_load)
                    x$container
                  }, object = list(container = object, xgb.bin = readBin(con, raw(), n = file.info(file_save)$size)))
                )
      close(con)
    }
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Native function specs"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0.
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Note: [
		"Used to generates C enums and tables"
		"Boot bind attributes are SET and not DEEP"
		"Todo: before beta release remove extra/unused refinements"
	]
]

;-- Control Natives - nat_control.c

ajoin: native [
	{Reduces and joins a block of values into a new string.}
	block [block!]
]

also: native [
	{Returns the first value, but also evaluates the second.}
	value1 [any-type!]
	value2 [any-type!]
]

all: native [
	{Shortcut AND. Evaluates and returns at the first FALSE or NONE.}
	block [block!] {Block of expressions}
]

any: native [
	{Shortcut OR. Evaluates and returns the first value that is not FALSE or NONE.}
	block [block!] {Block of expressions}
]

apply: native [
	{Apply a function to a reduced block of arguments.}
	func [any-function!] "Function value to apply"
	block [block!] "Block of args, reduced first (unless /only)"
	/only "Use arg values as-is, do not reduce the block"
]

assert: native [
	"Assert that condition is true, else cause an assertion error."
	conditions [block!]
	/type "Safely check datatypes of variables (words and paths)"
]

attempt: native [
	"Tries to evaluate a block and returns result or NONE on error."
	block [block!]
]

break: native [
	{Breaks out of a loop, while, until, repeat, foreach, etc.}
	/return {Forces the loop function to return a value}
	value [any-type!]
]

case: native [
	{Evaluates each condition, and when true, evaluates what follows it.}
	block [block!] {Block of cases (conditions followed by values)}
	/all {Evaluate all cases (do not stop at first true case)}
]

catch: native [
	{Catches a throw from a block and returns its value.}
	block [block!] {Block to evaluate}
	/name {Catches a named throw}
	word [word! block!] {One or more names}
	/quit {Special catch for QUIT native}
]

;cause: native [
;	{Force error processing on an error value.}
;	error [error!]
;]

comment: native [
	{Ignores the argument value and returns nothing.}
	value {A string, block, file, etc.}
]

compose: native [
	{Evaluates a block of expressions, only evaluating parens, and returns a block.}
	value "Block to compose"
	/deep "Compose nested blocks"
	/only {Insert a block as a single value (not the contents of the block)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

context: native [
	{Creates an object.}
	spec ; [block!] -- no check required, we know it is correct
]

continue: native [
	{Throws control back to top of loop.}
]

;dir?: native [
;	{Returns true if file is a directory.}
;	file [any-string! none!]
;	/any {Allow * or ? wildcards for directory}
;]

;disarm: native [
;	{(Deprecated - not needed) Converts error to an object. Other types not modified.}
;	error [any-type!]
;]

do: native [
	{Evaluates a block, file, URL, function, word, or any other value.}
	value [any-type!] "Normally a file name, URL, or block"
	/args "If value is a script, this will set its system/script/args"
	arg   "Args passed to a script (normally a string)"
	/next "Do next expression only, return it, update block variable"
	var [word!] "Variable updated with new block position"
]

;eval: native [
;	{Evaluates a block, file, URL, function, word, or any other value.}
;	value "Normally a file name, URL, or block"
;]

either: native [
	{If TRUE condition return first arg, else second; evaluate blocks by default.}
	condition
	true-branch
	false-branch
	/only "Suppress evaluation of block args."
]

exit: native [
	{Exits a function, returning no value.}
]

find-script: native [
	{Find a script header within a binary string. Returns starting position.}
	script [binary!]
]

for: native [
	{Evaluate a block over a range of values. (See also: REPEAT)}
	'word [word!] "Variable to hold current value"
	start [series! number!] "Starting value"
	end   [series! number!] "Ending value"
	bump  [number!] "Amount to skip each time"
	body  [block!] "Block to evaluate"
]

forall: native [
	"Evaluates a block for every value in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	body [block!] "Block to evaluate each time"
]

forever: native [
	{Evaluates a block endlessly.}
	body [block!] {Block to evaluate each time}
]

foreach: native [
	{Evaluates a block for each value(s) in a series.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series! any-object! map! none!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

forskip: native [
	"Evaluates a block for periodic values in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	size [integer! decimal!] "Number of positions to skip each time"
	body [block!] "Block to evaluate each time"
	/local orig result
]

halt: native [
	{Stops evaluation and returns to the input prompt.}
]

if: native [
	{If TRUE condition, return arg; evaluate block args by default}
	condition
	true-branch
	/else "If FALSE condition, return second arg; evaluate block by default"
	false-branch
	/only "Suppress evaluation of block args."
]

loop: native [
	{Evaluates a block a specified number of times.}
	count [number!] {Number of repetitions}
	block [block!] {Block to evaluate}
]

map-each: native [
	{Evaluates a block for each value(s) in a series and returns them as a block.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [block! vector!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

;replace-all: native [
;	"Search and replace multiple values with a series; returns a new series."
;	target [block! string! binary!]
;	values [block!] "A block of [old new] search/replace pairs"
;]

quit: native [
	{Stops evaluation and exits the interpreter.}
	/return {Returns a value (to prior script or command shell)}
	value {Note: use integers for command shell}
	/now {Quit immediately}
]

protect: native [
	"Protect a series or a variable from being modified."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series/objects as well"
	/words  "Process list as words (and path words)"
	/values "Process list of values (implied GET)"
	/hide "Hide variables (avoid binding and lookup)"
]

unprotect: native [
	"Unprotect a series or a variable (it can again be modified)."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series as well"
	/words "Block is a list of words"
	/values "Process list of values (implied GET)"
]

recycle: native [
	{Recycles unused memory.}
	/off {Disable auto-recycling}
	/on {Enable auto-recycling}
	/ballast {Trigger for auto-recycle (memory used)}
	size [integer!]
	/torture {Constant recycle (for internal debugging)}
]

reduce: native [
	{Evaluates expressions and returns multiple results.}
	value
	/no-set {Keep set-words as-is. Do not set them.}
	/only {Only evaluate words and paths, not functions}
	words [block! none!] {Optional words that are not evaluated (keywords)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

repeat: native [
	{Evaluates a block a number of times or over a series.}
	'word [word!] {Word to set each time}
	value [number! series! none!] {Maximum number or series to traverse}
	body [block!] {Block to evaluate each time}
]

remove-each: native [
	{Removes values for each block that returns true; returns removal count.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series!] {The series to traverse (modified)}
	body [block!] {Block to evaluate (return TRUE to remove)}
]

return: native [
	{Returns a value from a function.}
	value [any-type!]
	/redo {Upon return, re-evaluate the returned result. (Used for DO)}
]

switch: native [
	"Selects a choice and evaluates the block that follows it."
	value "Target value"
	cases [block!] "Block of cases to check"
	/default case "Default case if no others found"
	/all "Evaluate all matches (not just first one)"
]

throw: native [
	{Throws control back to a previous catch.}
	value [any-type!] {Value returned from catch}
	/name {Throws to a named catch}
	word [word!]
]

trace: native [
	{Enables and disables evaluation tracing and backtrace.}
	mode [integer! logic!]
	/back {Set mode ON to enable or integer for lines to display}
	/function {Traces functions only (less output)}
;	/stack {Show stack index}
]

try: native [
	{Tries to DO a block and returns its value or an error.}
	block [block!]
	/except "On exception, evaluate this code block"
	code [block! any-function!]
]

unless: native [
	{If FALSE condition, return arg; evaluate block args by default.}
	condition
	false-branch
	/only "Suppress evaluation of block args."
]

until: native [
	{Evaluates a block until it is TRUE. }
	block [block!]
]

while: native [
	{While a condition block is TRUE, evaluates another block.}
	cond-block [block!]
	body-block [block!]
]

;-- Data Natives - nat_data.c

;alias: native [
;	See CC#1835
;	{Creates an alternate spelling for a word.}
;	word [word!] {Word to alias}
;	name [string!] {Name of alias}
;]

;as-binary: native [
;	{Coerces any type of string into a binary! datatype without copying it.}
;	string [any-string!]
;]
;
;as-string: native [
;	{Coerces any type of string into a string! datatype without copying it.}
;	string [any-string!]
;]

bind: native [
	{Binds words to the specified context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	context [any-word! any-object!] {A reference to the target context}
	/copy {Bind and return a deep copy of a block, don't modify original}
	/only {Bind only first block (not deep)}
	/new {Add to context any new words found}
	/set {Add to context any new set-words found}
]

unbind: native [
	{Unbinds words from context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	/deep "Process nested blocks"
]

bound?: native [
	{Returns the context in which a word is bound.}
	word [any-word!]
]

collect-words: native [
	"Collect unique words used in a block (used for context construction)."
	block [block!]
	/deep "Include nested blocks"
	/set "Only include set-words"
	/ignore "Ignore prior words"
	words [any-object! block! none!] "Words to ignore"
]

checksum: native [
	{Computes a checksum, CRC, or hash.}
	data [binary!] {Bytes to checksum}
	/part length {Length of data}
	/tcp {Returns an Internet TCP 16-bit checksum}
	/secure {Returns a cryptographically secure checksum}
	/hash {Returns a hash value}
	size [integer!] {Size of the hash table}
	/method {Method to use}
	word [word!] {Methods: SHA1 MD5 CRC32}
	/key {Returns keyed HMAC value}
	key-value [any-string!] {Key to use}
]

compress: native [
	{Compresses a string series and returns it.}
	data [binary! string!] {If string, it will be UTF8 encoded}
	/part length {Length of data (elements)}
	/gzip {Use GZIP checksum}
]

decompress: native [
	{Decompresses data. Result is binary.}
	data [binary!] {Data to decompress}
	/part length {Length of compressed data (must match end marker)}
	/gzip {Use GZIP checksum}
	/limit size {Error out if result is larger than this}
]

construct: native [
	{Creates an object with scant (safe) evaluation.}
	block [block! string! binary!] "Specification (modified)"
	/with "Default object" object [object!]
	/only "Values are kept as-is"
]

debase: native [
	{Decodes binary-coded string (BASE-64 default) to binary value.}
	value [binary! string!] {The string to decode}
	/base {Binary base to use}
	base-value [integer!] {The base to convert from: 64, 16, or 2}
]

enbase: native [
	{Encodes a string into a binary-coded string (BASE-64 default).}
	value [binary! string!] {If string, will be UTF8 encoded}
	/base {Binary base to use}
	base-value [integer!] {The base to convert to: 64, 16, or 2}
]

decloak: native [
	{Decodes a binary string scrambled previously by encloak.}
	data [binary!] "Binary series to descramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

encloak: native [
	{Scrambles a binary string based on a key.}
	data [binary!] "Binary series to scramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

deline: native [
	"Converts string terminators to standard format, e.g. CRLF to LF."
	string [any-string!] {(modified)}
	/lines "Return block of lines (works for LF, CR, CR-LF endings) (no modify)"
]

enline: native [
	"Converts string terminators to native OS format, e.g. LF to CRLF."
	series [any-string! block!] {(modified)}
]

detab: native [
	"Converts tabs to spaces (default tab size is 4)."
	string [any-string!] {(modified)}
	/size  "Specifies the number of spaces per tab"
	number [integer!]
]

entab: native [
	"Converts spaces to tabs (default tab size is 4)."
	string [any-string!] {(modified)}
	/size "Specifies the number of spaces per tab"
	number [integer!]
]

delect: native [
	"Parses a common form of dialects. Returns updated input block."
	 dialect [object!] "Describes the words and datatypes of the dialect"
	 input [block!] "Input stream to parse"
	 output [block!] "Resulting values, ordered as defined (modified)"
	 /in "Search for var words in specific objects (contexts)"
	 where [block!] "Block of objects to search (non objects ignored)"
	 /all "Parse entire block, not just one command at a time"
]

difference: native [
	{Returns the special difference of two values.}
	set1 [block! string! binary! bitset! date! typeset!] "First data set"
	set2 [block! string! binary! bitset! date! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

exclude: native [
	{Returns the first data set less the second data set.}
	set1 [block! string! binary! bitset! typeset!] "First data set"
	set2 [block! string! binary! bitset! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

intersect: native [
	{Returns the intersection of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

union: native [
	{Returns the union of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Use case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

unique: native [
	{Returns the data set with duplicates removed.}
	set1 [block! string! binary! bitset! typeset!]
	/case  {Use case-sensitive comparison (except bitsets)}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

lowercase: native [
	"Converts string of characters to lowercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

uppercase: native [
	"Converts string of characters to uppercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

dehex: native [
	{Converts URL-style hex encoded (%xx) strings.}
	value [any-string!] {The string to dehex}
]

get: native [
	{Gets the value of a word or path, or values of an object.}
	word {Word, path, object to get}
	/any {Allows word to have no value (allows unset)}
]

in: native [
	{Returns the word or block in the object's context.}
	object [any-object! block!]
	word [any-word! block! paren!]  {(modified if series)}
]

parse: native [
	{Parses a string or block series according to grammar rules.}
	input [series!] {Input series to parse}
	rules [block! string! char! none!] {Rules to parse by (none = ",;")}
	/all {For simple rules (not blocks) parse all chars including whitespace}
	/case {Uses case-sensitive comparison}
]

set: native [
	{Sets a word, path, block of words, or object to specified value(s).}
	word [any-word! any-path! block! object!] {Word, block of words, path, or object to be set (modified)}
	value [any-type!] {Value or block of values}
	/any {Allows setting words to any value, including unset}
	/pad {For objects, if block is too short, remaining words are set to NONE}
]

to-hex: native [
	{Converts numeric value to a hex issue! datatype (with leading # and 0's).}
	value [integer! tuple!] {Value to be converted}
	/size {Specify number of hex digits in result}
	len [integer!]
]

type?: native [
	{Returns the datatype of a value.}
	value [any-type!]
	/word {Returns the datatype as a word}
]

unset: native [
	{Unsets the value of a word (in its current context.)}
	word [word! block!] {Word or block of words}
]

utf?: native [
	{Returns UTF BOM (byte order marker) encoding; + for BE, - for LE.}
	data [binary!]
]

invalid-utf?: native [
	{Checks UTF encoding; if correct, returns none else position of error.}
	data [binary!]
	/utf "Check encodings other than UTF-8"
	num [integer!] "Bit size - positive for BE negative for LE"
]

value?: native [
	{Returns TRUE if the word has a value.}
	value
]

;-- IO Natives - nat_io.c

print: native [
	{Outputs a value followed by a line break.}
	value [any-type!] {The value to print}
]

prin: native [
	{Outputs a value with no line break.}
	value [any-type!]
]

mold: native [
	{Converts a value to a REBOL-readable string.}
	value [any-type!] {The value to mold}
	/only {For a block value, mold only its contents, no outer []}
	/all  {Use construction syntax}
	/flat {No indentation}
]

form: native [
	{Converts a value to a human-readable string.}
	value [any-type!] {The value to form}
]

new-line: native [
	{Sets or clears the new-line marker within a block or paren.}
	position [block! paren!] {Position to change marker (modified)}
	value {Set TRUE for newline}
	/all {Set/clear marker to end of series}
	/skip {Set/clear marker periodically to the end of the series}
	size [integer!]
]

new-line?: native [
	{Returns the state of the new-line marker within a block or paren.}
	position [block! paren!] {Position to check marker}
]

to-local-file: native [
	{Converts a REBOL file path to the local system file path.}
	path [file! string!]
	/full "Prepends current dir for full path (for relative paths only)"
]

to-rebol-file: native [
	{Converts a local system file path to a REBOL file path.}
	path [file! string!]
]

transcode: native [
	{Translates UTF-8 binary source to values. Returns [value binary].}
	source [binary!] "Must be Unicode UTF-8 encoded"
	/next "Translate next complete value (blocks as single value)"
	/only "Translate only a single value (blocks dissected)"
	/error "Do not cause errors - return error object as value in place"
]

echo: native [
    {Copies console output to a file.}
    target [file! none! logic!]
]

now: native [
	{Returns date and time.}
	/year {Returns year only}
	/month {Returns month only}
	/day {Returns day of the month only}
	/time {Returns time only}
	/zone {Returns time zone offset from UCT (GMT) only}
	/date {Returns date only}
	/weekday {Returns day of the week as integer (Monday is day 1)}
	/yearday {Returns day of the year (Julian)}
	/precise {High precision time}
	/utc {Universal time (no zone)}
]

wait: native [
	{Waits for a duration, port, or both.}
	value [number! time! port! block! none!]
	/all {Returns all in a block}
	/only {only check for ports given in the block to this function}
]

wake-up: native [
	{Awake and update a port with event.}
	port [port!]
	event [event!]
]

what-dir: native ["Returns the current directory path."]

change-dir: native [
	"Changes the current directory path."
	path [file!]
]

;-- Series Natives

first: native [
	{Returns the first value of a series.}
	value
]

second: native [
	{Returns the second value of a series.}
	value
]

third: native [
	{Returns the third value of a series.}
	value
]

fourth: native [
	{Returns the fourth value of a series.}
	value
]

fifth: native [
	{Returns the fifth value of a series.}
	value
]

sixth: native [
	{Returns the sixth value of a series.}
	value
]

seventh: native [
	{Returns the seventh value of a series.}
	value
]

eighth: native [
	{Returns the eighth value of a series.}
	value
]

ninth: native [
	{Returns the ninth value of a series.}
	value
]

tenth: native [
	{Returns the tenth value of a series.}
	value
]

last: native [
	{Returns the last value of a series.}
	value [series! tuple! gob!]
]

;-- Math Natives - nat_math.c

cosine: native [
	{Returns the trigonometric cosine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

sine: native [
	{Returns the trigonometric sine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

tangent: native [
	{Returns the trigonometric tangent.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

arccosine: native [
	{Returns the trigonometric arccosine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arcsine: native [
	{Returns the trigonometric arcsine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arctangent: native [
	{Returns the trigonometric arctangent (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

exp: native [
	{Raises E (the base of natural logarithm) to the power specified}
	power [number!]
]

log-10: native [
	{Returns the base-10 logarithm.}
	value [number!]
]

log-2: native [
	{Return the base-2 logarithm.}
	value [number!]
]

log-e: native [
	{Returns the natural (base-E) logarithm of the given value} 
	value [number!]
]

not: native [
	{Returns the logic complement.}
	value {(Only FALSE and NONE return TRUE)}
]

square-root: native [
	{Returns the square root of a number.}
	value [number!]
]

shift: native [
	{Shifts an integer left or right by a number of bits.}
	value [integer!]
	bits [integer!] "Positive for left shift, negative for right shift"
	/logical "Logical shift (sign bit ignored)"
]

;-- New, hackish stuff:

++: native [
	{Increment an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

--: native [
	{Decrement an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

first+: native [
	{Return the FIRST of a series then increment the series index.}
	'word [word!] "Word must refer to a series"
]

stack: native [
	{Returns stack backtrace or other values.}
	offset [integer!] "Relative backward offset"
	/block "Block evaluation position"
	/word "Function or object name, if known"
	/func "Function value"
	/args "Block of args (may be modified)"
	/size "Current stack size (in value units)"
	/depth "Stack depth (frames)"
	/limit "Stack bounds (auto expanding)"
]

resolve: native [
	{Copy context by setting values in the target from those in the source.}
	target [any-object!] {(modified)}
	source [any-object!]
	/only from [block! integer!] "Only specific words (exports) or new words in target (index to tail)"
	/all "Set all words, even those in the target that already have a value"
	/extend "Add source words to the target if necessary"
]

;in-context: native [
;	{Set the default context for global words.}
;	context [object!]
;]

get-env: native [
	{Returns the value of an OS environment variable (for current process).}
	var [any-string! any-word!]
]

set-env: native [
	{Sets the value of an operating system environment variable (for current process).} 
	var [any-string! any-word!] "Variable to set" 
	value [string!  none!] "Value to set, or NONE to unset it"
]

list-env: native [
	{Returns a map of OS environment variables (for current process).}
]

call: native [
	{Run another program; return immediately.}
	command [string! block!] "An OS-local command line, quoted as necessary"
	/wait "Wait for command to terminate before returning"
	/console "Runs command with I/O redirected to console"
	/shell "Forces command to be run from shell"
	/info "Returns process information object"
	/input in [string! binary! file! none!] "Redirects stdin to in"
	/output out [string! binary! file! none!] "Redirects stdout to out"
	/error err [string! binary! file! none!] "Redirects stderr to err"
]

browse: native [
	{Open web browser to a URL or local file.}
	url [url! file! none!]
]

evoke: native [
	{Special guru meditations. (Not for beginners.)}
	chant [word! block! integer!] "Single or block of words ('? to list)"
]

request-file: native [
	{Asks user to select a file and returns full file path (or block of paths).}
	/save "File save mode"
	/multi "Allows multiple file selection, returned as a block"
	/file name [file!] "Default file name or directory"
	/title text [string!] "Window title"
	/filter list [block!] "Block of filters (filter-name filter)"
]

ascii?: native [
	{Returns TRUE if value or string is in ASCII character range (below 128).}
	value [any-string! char! integer!]
]

latin1?: native [
	{Returns TRUE if value or string is in Latin-1 character range (below 256).}
	value [any-string! char! integer!]
]

; Temps...

stats: native [
	{Provides status and statistics information about the interpreter.}
	/show {Print formatted results to console}
	/profile {Returns profiler object}
	/timer {High resolution time difference from start}
	/evals {Number of values evaluated by interpreter}
	/dump-series pool-id [integer!] {Dump all series in pool pool-id, -1 for all pools}
]

do-codec: native [
	{Evaluate a CODEC function to encode or decode media types.}
	handle [handle!] "Internal link to codec"
	action [word!] "Decode, encode, identify"
	data [binary! image!]
]

set-scheme: native [
	"Low-level port scheme actor initialization."
	scheme [object!]
]

load-extension: native [
	"Low level extension module loader (for DLLs)."
	name [file! binary!] "DLL file or UTF-8 source"
	/dispatch "Specify native command dispatch (from hosted extensions)"
	function [handle!] "Command dispatcher (native)"
]

do-commands: native [
	"Evaluate a block of extension module command functions (special evaluation rules.)"
	commands [block!] "Series of commands and their arguments"
]

ds: native ["Temporary stack debug"]
dump: native ["Temporary debug dump" v]
check: native ["Temporary series debug check" val [series!]]

do-callback: native [
	"Internal function to process callback events."
	event [event!] "Callback event"
]


limit-usage: native [
	"Set a usage limit only once (used for SECURE)."
	field [word!] "eval (count) or memory (bytes)"
	limit [number!]
]

selfless?: native [
    "Returns true if the context doesn't bind 'self."
    context [any-word! any-object!] "A reference to the target context"
]

map-event: native [
	"Returns event with inner-most graphical object and coordinate."
	event [event!]
]

map-gob-offset: native [
	"Translates a gob and offset to the deepest gob and offset in it, returned as a block."
	gob [gob!] "Starting object"
	xy [pair!] "Staring offset"
	/reverse "Translate from deeper gob to top gob."
]

as-pair: native [
	"Combine X and Y values into a pair."
	x [number!]
	y [number!]
]

;read-file: native [f [file!]]

equal?: native [
	{Returns TRUE if the values are equal.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equal?: native [
	{Returns TRUE if the values are not equal.}
	value1 [any-type!]
	value2 [any-type!]
]

equiv?: native [
	{Returns TRUE if the values are equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equiv?: native [
	{Returns TRUE if the values are not equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-equal?: native [
	{Returns TRUE if the values are strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-not-equal?: native [
	{Returns TRUE if the values are not strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

same?: native [
	{Returns TRUE if the values are identical.}
	value1 [any-type!]
	value2 [any-type!]
]

greater?: native [ ; Note: some datatypes expect >, <, >=, <= to be in this order.
	{Returns TRUE if the first value is greater than the second value.}
	value1 value2
]

greater-or-equal?: native [
	{Returns TRUE if the first value is greater than or equal to the second value.}
	value1 value2
]

lesser?: native [
	{Returns TRUE if the first value is less than the second value.}
	value1 value2
]

lesser-or-equal?: native [
	{Returns TRUE if the first value is less than or equal to the second value.}
	value1 value2
]

minimum: native [
	{Returns the lesser of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

maximum: native [ ; Note: Some datatypes expect all binary ops to be <= this
	{Returns the greater of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

negative?: native [
	{Returns TRUE if the number is negative.}
	number [number! money! time! pair!]
]

positive?: native [
	{Returns TRUE if the value is positive.}
	number [number! money! time! pair!]
]

zero?: native [
	{Returns TRUE if the value is zero (for its datatype).}
	value
]
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Native function specs"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0.
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Note: [
		"Used to generates C enums and tables"
		"Boot bind attributes are SET and not DEEP"
		"Todo: before beta release remove extra/unused refinements"
	]
]

;-- Control Natives - nat_control.c

ajoin: native [
	{Reduces and joins a block of values into a new string.}
	block [block!]
]

also: native [
	{Returns the first value, but also evaluates the second.}
	value1 [any-type!]
	value2 [any-type!]
]

all: native [
	{Shortcut AND. Evaluates and returns at the first FALSE or NONE.}
	block [block!] {Block of expressions}
]

any: native [
	{Shortcut OR. Evaluates and returns the first value that is not FALSE or NONE.}
	block [block!] {Block of expressions}
]

apply: native [
	{Apply a function to a reduced block of arguments.}
	func [any-function!] "Function value to apply"
	block [block!] "Block of args, reduced first (unless /only)"
	/only "Use arg values as-is, do not reduce the block"
]

assert: native [
	"Assert that condition is true, else cause an assertion error."
	conditions [block!]
	/type "Safely check datatypes of variables (words and paths)"
]

attempt: native [
	"Tries to evaluate a block and returns result or NONE on error."
	block [block!]
]

break: native [
	{Breaks out of a loop, while, until, repeat, foreach, etc.}
	/return {Forces the loop function to return a value}
	value [any-type!]
]

case: native [
	{Evaluates each condition, and when true, evaluates what follows it.}
	block [block!] {Block of cases (conditions followed by values)}
	/all {Evaluate all cases (do not stop at first true case)}
]

catch: native [
	{Catches a throw from a block and returns its value.}
	block [block!] {Block to evaluate}
	/name {Catches a named throw}
	word [word! block!] {One or more names}
	/quit {Special catch for QUIT native}
]

;cause: native [
;	{Force error processing on an error value.}
;	error [error!]
;]

comment: native [
	{Ignores the argument value and returns nothing.}
	value {A string, block, file, etc.}
]

compose: native [
	{Evaluates a block of expressions, only evaluating parens, and returns a block.}
	value "Block to compose"
	/deep "Compose nested blocks"
	/only {Insert a block as a single value (not the contents of the block)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

context: native [
	{Creates an object.}
	spec ; [block!] -- no check required, we know it is correct
]

continue: native [
	{Throws control back to top of loop.}
]

;dir?: native [
;	{Returns true if file is a directory.}
;	file [any-string! none!]
;	/any {Allow * or ? wildcards for directory}
;]

;disarm: native [
;	{(Deprecated - not needed) Converts error to an object. Other types not modified.}
;	error [any-type!]
;]

do: native [
	{Evaluates a block, file, URL, function, word, or any other value.}
	value [any-type!] "Normally a file name, URL, or block"
	/args "If value is a script, this will set its system/script/args"
	arg   "Args passed to a script (normally a string)"
	/next "Do next expression only, return it, update block variable"
	var [word!] "Variable updated with new block position"
]

;eval: native [
;	{Evaluates a block, file, URL, function, word, or any other value.}
;	value "Normally a file name, URL, or block"
;]

either: native [
	{If TRUE condition return first arg, else second; evaluate blocks by default.}
	condition
	true-branch
	false-branch
	/only "Suppress evaluation of block args."
]

exit: native [
	{Exits a function, returning no value.}
]

find-script: native [
	{Find a script header within a binary string. Returns starting position.}
	script [binary!]
]

for: native [
	{Evaluate a block over a range of values. (See also: REPEAT)}
	'word [word!] "Variable to hold current value"
	start [series! number!] "Starting value"
	end   [series! number!] "Ending value"
	bump  [number!] "Amount to skip each time"
	body  [block!] "Block to evaluate"
]

forall: native [
	"Evaluates a block for every value in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	body [block!] "Block to evaluate each time"
]

forever: native [
	{Evaluates a block endlessly.}
	body [block!] {Block to evaluate each time}
]

foreach: native [
	{Evaluates a block for each value(s) in a series.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series! any-object! map! none!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

forskip: native [
	"Evaluates a block for periodic values in a series."
	'word [word!] {Word that refers to the series, set to each position in series}
	size [integer! decimal!] "Number of positions to skip each time"
	body [block!] "Block to evaluate each time"
	/local orig result
]

halt: native [
	{Stops evaluation and returns to the input prompt.}
]

if: native [
	{If TRUE condition, return arg; evaluate block args by default}
	condition
	true-branch
	/else "If FALSE condition, return second arg; evaluate block by default"
	false-branch
	/only "Suppress evaluation of block args."
]

loop: native [
	{Evaluates a block a specified number of times.}
	count [number!] {Number of repetitions}
	block [block!] {Block to evaluate}
]

map-each: native [
	{Evaluates a block for each value(s) in a series and returns them as a block.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [block! vector!] {The series to traverse}
	body [block!] {Block to evaluate each time}
]

;replace-all: native [
;	"Search and replace multiple values with a series; returns a new series."
;	target [block! string! binary!]
;	values [block!] "A block of [old new] search/replace pairs"
;]

quit: native [
	{Stops evaluation and exits the interpreter.}
	/return {Returns a value (to prior script or command shell)}
	value {Note: use integers for command shell}
	/now {Quit immediately}
]

protect: native [
	"Protect a series or a variable from being modified."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series/objects as well"
	/words  "Process list as words (and path words)"
	/values "Process list of values (implied GET)"
	/hide "Hide variables (avoid binding and lookup)"
]

unprotect: native [
	"Unprotect a series or a variable (it can again be modified)."
	value [word! series! bitset! map! object! module!]
	/deep "Protect all sub-series as well"
	/words "Block is a list of words"
	/values "Process list of values (implied GET)"
]

recycle: native [
	{Recycles unused memory.}
	/off {Disable auto-recycling}
	/on {Enable auto-recycling}
	/ballast {Trigger for auto-recycle (memory used)}
	size [integer!]
	/torture {Constant recycle (for internal debugging)}
]

reduce: native [
	{Evaluates expressions and returns multiple results.}
	value
	/no-set {Keep set-words as-is. Do not set them.}
	/only {Only evaluate words and paths, not functions}
	words [block! none!] {Optional words that are not evaluated (keywords)}
	/into {Output results into a block with no intermediate storage}
	out [any-block!]
]

repeat: native [
	{Evaluates a block a number of times or over a series.}
	'word [word!] {Word to set each time}
	value [number! series! none!] {Maximum number or series to traverse}
	body [block!] {Block to evaluate each time}
]

remove-each: native [
	{Removes values for each block that returns true; returns removal count.}
	'word [word! block!] {Word or block of words to set each time (local)}
	data [series!] {The series to traverse (modified)}
	body [block!] {Block to evaluate (return TRUE to remove)}
]

return: native [
	{Returns a value from a function.}
	value [any-type!]
	/redo {Upon return, re-evaluate the returned result. (Used for DO)}
]

switch: native [
	"Selects a choice and evaluates the block that follows it."
	value "Target value"
	cases [block!] "Block of cases to check"
	/default case "Default case if no others found"
	/all "Evaluate all matches (not just first one)"
]

throw: native [
	{Throws control back to a previous catch.}
	value [any-type!] {Value returned from catch}
	/name {Throws to a named catch}
	word [word!]
]

trace: native [
	{Enables and disables evaluation tracing and backtrace.}
	mode [integer! logic!]
	/back {Set mode ON to enable or integer for lines to display}
	/function {Traces functions only (less output)}
;	/stack {Show stack index}
]

try: native [
	{Tries to DO a block and returns its value or an error.}
	block [block!]
	/except "On exception, evaluate this code block"
	code [block! any-function!]
]

unless: native [
	{If FALSE condition, return arg; evaluate block args by default.}
	condition
	false-branch
	/only "Suppress evaluation of block args."
]

until: native [
	{Evaluates a block until it is TRUE. }
	block [block!]
]

while: native [
	{While a condition block is TRUE, evaluates another block.}
	cond-block [block!]
	body-block [block!]
]

;-- Data Natives - nat_data.c

;alias: native [
;	See CC#1835
;	{Creates an alternate spelling for a word.}
;	word [word!] {Word to alias}
;	name [string!] {Name of alias}
;]

;as-binary: native [
;	{Coerces any type of string into a binary! datatype without copying it.}
;	string [any-string!]
;]
;
;as-string: native [
;	{Coerces any type of string into a string! datatype without copying it.}
;	string [any-string!]
;]

bind: native [
	{Binds words to the specified context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	context [any-word! any-object!] {A reference to the target context}
	/copy {Bind and return a deep copy of a block, don't modify original}
	/only {Bind only first block (not deep)}
	/new {Add to context any new words found}
	/set {Add to context any new set-words found}
]

unbind: native [
	{Unbinds words from context.}
	word [block! any-word!] {A word or block (modified) (returned)}
	/deep "Process nested blocks"
]

bound?: native [
	{Returns the context in which a word is bound.}
	word [any-word!]
]

collect-words: native [
	"Collect unique words used in a block (used for context construction)."
	block [block!]
	/deep "Include nested blocks"
	/set "Only include set-words"
	/ignore "Ignore prior words"
	words [any-object! block! none!] "Words to ignore"
]

checksum: native [
	{Computes a checksum, CRC, or hash.}
	data [binary!] {Bytes to checksum}
	/part length {Length of data}
	/tcp {Returns an Internet TCP 16-bit checksum}
	/secure {Returns a cryptographically secure checksum}
	/hash {Returns a hash value}
	size [integer!] {Size of the hash table}
	/method {Method to use}
	word [word!] {Methods: SHA1 MD5 CRC32}
	/key {Returns keyed HMAC value}
	key-value [any-string!] {Key to use}
]

compress: native [
	{Compresses a string series and returns it.}
	data [binary! string!] {If string, it will be UTF8 encoded}
	/part length {Length of data (elements)}
	/gzip {Use GZIP checksum}
]

decompress: native [
	{Decompresses data. Result is binary.}
	data [binary!] {Data to decompress}
	/part length {Length of compressed data (must match end marker)}
	/gzip {Use GZIP checksum}
	/limit size {Error out if result is larger than this}
]

construct: native [
	{Creates an object with scant (safe) evaluation.}
	block [block! string! binary!] "Specification (modified)"
	/with "Default object" object [object!]
	/only "Values are kept as-is"
]

debase: native [
	{Decodes binary-coded string (BASE-64 default) to binary value.}
	value [binary! string!] {The string to decode}
	/base {Binary base to use}
	base-value [integer!] {The base to convert from: 64, 16, or 2}
]

enbase: native [
	{Encodes a string into a binary-coded string (BASE-64 default).}
	value [binary! string!] {If string, will be UTF8 encoded}
	/base {Binary base to use}
	base-value [integer!] {The base to convert to: 64, 16, or 2}
]

decloak: native [
	{Decodes a binary string scrambled previously by encloak.}
	data [binary!] "Binary series to descramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

encloak: native [
	{Scrambles a binary string based on a key.}
	data [binary!] "Binary series to scramble (modified)"
	key [string! binary! integer!] "Encryption key or pass phrase"
	/with "Use a string! key as-is (do not generate hash)"
]

deline: native [
	"Converts string terminators to standard format, e.g. CRLF to LF."
	string [any-string!] {(modified)}
	/lines "Return block of lines (works for LF, CR, CR-LF endings) (no modify)"
]

enline: native [
	"Converts string terminators to native OS format, e.g. LF to CRLF."
	series [any-string! block!] {(modified)}
]

detab: native [
	"Converts tabs to spaces (default tab size is 4)."
	string [any-string!] {(modified)}
	/size  "Specifies the number of spaces per tab"
	number [integer!]
]

entab: native [
	"Converts spaces to tabs (default tab size is 4)."
	string [any-string!] {(modified)}
	/size "Specifies the number of spaces per tab"
	number [integer!]
]

delect: native [
	"Parses a common form of dialects. Returns updated input block."
	 dialect [object!] "Describes the words and datatypes of the dialect"
	 input [block!] "Input stream to parse"
	 output [block!] "Resulting values, ordered as defined (modified)"
	 /in "Search for var words in specific objects (contexts)"
	 where [block!] "Block of objects to search (non objects ignored)"
	 /all "Parse entire block, not just one command at a time"
]

difference: native [
	{Returns the special difference of two values.}
	set1 [block! string! binary! bitset! date! typeset!] "First data set"
	set2 [block! string! binary! bitset! date! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

exclude: native [
	{Returns the first data set less the second data set.}
	set1 [block! string! binary! bitset! typeset!] "First data set"
	set2 [block! string! binary! bitset! typeset!] "Second data set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

intersect: native [
	{Returns the intersection of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Uses case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

union: native [
	{Returns the union of two data sets.}
	set1 [block! string! binary! bitset! typeset!] "first set"
	set2 [block! string! binary! bitset! typeset!] "second set"
	/case {Use case-sensitive comparison}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

unique: native [
	{Returns the data set with duplicates removed.}
	set1 [block! string! binary! bitset! typeset!]
	/case  {Use case-sensitive comparison (except bitsets)}
	/skip {Treat the series as records of fixed size}
	size [integer!]
]

lowercase: native [
	"Converts string of characters to lowercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

uppercase: native [
	"Converts string of characters to uppercase."
	string [any-string! char!] {(modified if series)}
	/part {Limits to a given length or position}
	length [number! any-string!]
]

dehex: native [
	{Converts URL-style hex encoded (%xx) strings.}
	value [any-string!] {The string to dehex}
]

get: native [
	{Gets the value of a word or path, or values of an object.}
	word {Word, path, object to get}
	/any {Allows word to have no value (allows unset)}
]

in: native [
	{Returns the word or block in the object's context.}
	object [any-object! block!]
	word [any-word! block! paren!]  {(modified if series)}
]

parse: native [
	{Parses a string or block series according to grammar rules.}
	input [series!] {Input series to parse}
	rules [block! string! char! none!] {Rules to parse by (none = ",;")}
	/all {For simple rules (not blocks) parse all chars including whitespace}
	/case {Uses case-sensitive comparison}
]

set: native [
	{Sets a word, path, block of words, or object to specified value(s).}
	word [any-word! any-path! block! object!] {Word, block of words, path, or object to be set (modified)}
	value [any-type!] {Value or block of values}
	/any {Allows setting words to any value, including unset}
	/pad {For objects, if block is too short, remaining words are set to NONE}
]

to-hex: native [
	{Converts numeric value to a hex issue! datatype (with leading # and 0's).}
	value [integer! tuple!] {Value to be converted}
	/size {Specify number of hex digits in result}
	len [integer!]
]

type?: native [
	{Returns the datatype of a value.}
	value [any-type!]
	/word {Returns the datatype as a word}
]

unset: native [
	{Unsets the value of a word (in its current context.)}
	word [word! block!] {Word or block of words}
]

utf?: native [
	{Returns UTF BOM (byte order marker) encoding; + for BE, - for LE.}
	data [binary!]
]

invalid-utf?: native [
	{Checks UTF encoding; if correct, returns none else position of error.}
	data [binary!]
	/utf "Check encodings other than UTF-8"
	num [integer!] "Bit size - positive for BE negative for LE"
]

value?: native [
	{Returns TRUE if the word has a value.}
	value
]

;-- IO Natives - nat_io.c

print: native [
	{Outputs a value followed by a line break.}
	value [any-type!] {The value to print}
]

prin: native [
	{Outputs a value with no line break.}
	value [any-type!]
]

mold: native [
	{Converts a value to a REBOL-readable string.}
	value [any-type!] {The value to mold}
	/only {For a block value, mold only its contents, no outer []}
	/all  {Use construction syntax}
	/flat {No indentation}
]

form: native [
	{Converts a value to a human-readable string.}
	value [any-type!] {The value to form}
]

new-line: native [
	{Sets or clears the new-line marker within a block or paren.}
	position [block! paren!] {Position to change marker (modified)}
	value {Set TRUE for newline}
	/all {Set/clear marker to end of series}
	/skip {Set/clear marker periodically to the end of the series}
	size [integer!]
]

new-line?: native [
	{Returns the state of the new-line marker within a block or paren.}
	position [block! paren!] {Position to check marker}
]

to-local-file: native [
	{Converts a REBOL file path to the local system file path.}
	path [file! string!]
	/full "Prepends current dir for full path (for relative paths only)"
]

to-rebol-file: native [
	{Converts a local system file path to a REBOL file path.}
	path [file! string!]
]

transcode: native [
	{Translates UTF-8 binary source to values. Returns [value binary].}
	source [binary!] "Must be Unicode UTF-8 encoded"
	/next "Translate next complete value (blocks as single value)"
	/only "Translate only a single value (blocks dissected)"
	/error "Do not cause errors - return error object as value in place"
]

echo: native [
    {Copies console output to a file.}
    target [file! none! logic!]
]

now: native [
	{Returns date and time.}
	/year {Returns year only}
	/month {Returns month only}
	/day {Returns day of the month only}
	/time {Returns time only}
	/zone {Returns time zone offset from UCT (GMT) only}
	/date {Returns date only}
	/weekday {Returns day of the week as integer (Monday is day 1)}
	/yearday {Returns day of the year (Julian)}
	/precise {High precision time}
	/utc {Universal time (no zone)}
]

wait: native [
	{Waits for a duration, port, or both.}
	value [number! time! port! block! none!]
	/all {Returns all in a block}
	/only {only check for ports given in the block to this function}
]

wake-up: native [
	{Awake and update a port with event.}
	port [port!]
	event [event!]
]

what-dir: native ["Returns the current directory path."]

change-dir: native [
	"Changes the current directory path."
	path [file!]
]

;-- Series Natives

first: native [
	{Returns the first value of a series.}
	value
]

second: native [
	{Returns the second value of a series.}
	value
]

third: native [
	{Returns the third value of a series.}
	value
]

fourth: native [
	{Returns the fourth value of a series.}
	value
]

fifth: native [
	{Returns the fifth value of a series.}
	value
]

sixth: native [
	{Returns the sixth value of a series.}
	value
]

seventh: native [
	{Returns the seventh value of a series.}
	value
]

eighth: native [
	{Returns the eighth value of a series.}
	value
]

ninth: native [
	{Returns the ninth value of a series.}
	value
]

tenth: native [
	{Returns the tenth value of a series.}
	value
]

last: native [
	{Returns the last value of a series.}
	value [series! tuple! gob!]
]

;-- Math Natives - nat_math.c

cosine: native [
	{Returns the trigonometric cosine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

sine: native [
	{Returns the trigonometric sine.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

tangent: native [
	{Returns the trigonometric tangent.}
	value [number!] {In degrees by default}
	/radians {Value is specified in radians}
]

arccosine: native [
	{Returns the trigonometric arccosine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arcsine: native [
	{Returns the trigonometric arcsine (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

arctangent: native [
	{Returns the trigonometric arctangent (in degrees by default).}
	value [number!]
	/radians {Returns result in radians}
]

exp: native [
	{Raises E (the base of natural logarithm) to the power specified}
	power [number!]
]

log-10: native [
	{Returns the base-10 logarithm.}
	value [number!]
]

log-2: native [
	{Return the base-2 logarithm.}
	value [number!]
]

log-e: native [
	{Returns the natural (base-E) logarithm of the given value} 
	value [number!]
]

not: native [
	{Returns the logic complement.}
	value {(Only FALSE and NONE return TRUE)}
]

square-root: native [
	{Returns the square root of a number.}
	value [number!]
]

shift: native [
	{Shifts an integer left or right by a number of bits.}
	value [integer!]
	bits [integer!] "Positive for left shift, negative for right shift"
	/logical "Logical shift (sign bit ignored)"
]

;-- New, hackish stuff:

++: native [
	{Increment an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

--: native [
	{Decrement an integer or series index. Return its prior value.}
	'word [word!] "Integer or series variable"
]

first+: native [
	{Return the FIRST of a series then increment the series index.}
	'word [word!] "Word must refer to a series"
]

stack: native [
	{Returns stack backtrace or other values.}
	offset [integer!] "Relative backward offset"
	/block "Block evaluation position"
	/word "Function or object name, if known"
	/func "Function value"
	/args "Block of args (may be modified)"
	/size "Current stack size (in value units)"
	/depth "Stack depth (frames)"
	/limit "Stack bounds (auto expanding)"
]

resolve: native [
	{Copy context by setting values in the target from those in the source.}
	target [any-object!] {(modified)}
	source [any-object!]
	/only from [block! integer!] "Only specific words (exports) or new words in target (index to tail)"
	/all "Set all words, even those in the target that already have a value"
	/extend "Add source words to the target if necessary"
]

;in-context: native [
;	{Set the default context for global words.}
;	context [object!]
;]

get-env: native [
	{Returns the value of an OS environment variable (for current process).}
	var [any-string! any-word!]
]

set-env: native [
	{Sets the value of an operating system environment variable (for current process).} 
	var [any-string! any-word!] "Variable to set" 
	value [string!  none!] "Value to set, or NONE to unset it"
]

list-env: native [
	{Returns a map of OS environment variables (for current process).}
]

call: native [
	{Run another program; return immediately.}
	command [string! block!] "An OS-local command line, quoted as necessary"
	/wait "Wait for command to terminate before returning"
	/console "Runs command with I/O redirected to console"
	/shell "Forces command to be run from shell"
	/info "Returns process information object"
	/input in [string! binary! file! none!] "Redirects stdin to in"
	/output out [string! binary! file! none!] "Redirects stdout to out"
	/error err [string! binary! file! none!] "Redirects stderr to err"
]

browse: native [
	{Open web browser to a URL or local file.}
	url [url! file! none!]
]

evoke: native [
	{Special guru meditations. (Not for beginners.)}
	chant [word! block! integer!] "Single or block of words ('? to list)"
]

request-file: native [
	{Asks user to select a file and returns full file path (or block of paths).}
	/save "File save mode"
	/multi "Allows multiple file selection, returned as a block"
	/file name [file!] "Default file name or directory"
	/title text [string!] "Window title"
	/filter list [block!] "Block of filters (filter-name filter)"
]

ascii?: native [
	{Returns TRUE if value or string is in ASCII character range (below 128).}
	value [any-string! char! integer!]
]

latin1?: native [
	{Returns TRUE if value or string is in Latin-1 character range (below 256).}
	value [any-string! char! integer!]
]

; Temps...

stats: native [
	{Provides status and statistics information about the interpreter.}
	/show {Print formatted results to console}
	/profile {Returns profiler object}
	/timer {High resolution time difference from start}
	/evals {Number of values evaluated by interpreter}
	/dump-series pool-id [integer!] {Dump all series in pool pool-id, -1 for all pools}
]

do-codec: native [
	{Evaluate a CODEC function to encode or decode media types.}
	handle [handle!] "Internal link to codec"
	action [word!] "Decode, encode, identify"
	data [binary! image!]
]

set-scheme: native [
	"Low-level port scheme actor initialization."
	scheme [object!]
]

load-extension: native [
	"Low level extension module loader (for DLLs)."
	name [file! binary!] "DLL file or UTF-8 source"
	/dispatch "Specify native command dispatch (from hosted extensions)"
	function [handle!] "Command dispatcher (native)"
]

do-commands: native [
	"Evaluate a block of extension module command functions (special evaluation rules.)"
	commands [block!] "Series of commands and their arguments"
]

ds: native ["Temporary stack debug"]
dump: native ["Temporary debug dump" v]
check: native ["Temporary series debug check" val [series!]]

do-callback: native [
	"Internal function to process callback events."
	event [event!] "Callback event"
]


limit-usage: native [
	"Set a usage limit only once (used for SECURE)."
	field [word!] "eval (count) or memory (bytes)"
	limit [number!]
]

selfless?: native [
    "Returns true if the context doesn't bind 'self."
    context [any-word! any-object!] "A reference to the target context"
]

map-event: native [
	"Returns event with inner-most graphical object and coordinate."
	event [event!]
]

map-gob-offset: native [
	"Translates a gob and offset to the deepest gob and offset in it, returned as a block."
	gob [gob!] "Starting object"
	xy [pair!] "Staring offset"
	/reverse "Translate from deeper gob to top gob."
]

as-pair: native [
	"Combine X and Y values into a pair."
	x [number!]
	y [number!]
]

;read-file: native [f [file!]]

equal?: native [
	{Returns TRUE if the values are equal.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equal?: native [
	{Returns TRUE if the values are not equal.}
	value1 [any-type!]
	value2 [any-type!]
]

equiv?: native [
	{Returns TRUE if the values are equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

not-equiv?: native [
	{Returns TRUE if the values are not equivalent.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-equal?: native [
	{Returns TRUE if the values are strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

strict-not-equal?: native [
	{Returns TRUE if the values are not strictly equal.}
	value1 [any-type!]
	value2 [any-type!]
]

same?: native [
	{Returns TRUE if the values are identical.}
	value1 [any-type!]
	value2 [any-type!]
]

greater?: native [ ; Note: some datatypes expect >, <, >=, <= to be in this order.
	{Returns TRUE if the first value is greater than the second value.}
	value1 value2
]

greater-or-equal?: native [
	{Returns TRUE if the first value is greater than or equal to the second value.}
	value1 value2
]

lesser?: native [
	{Returns TRUE if the first value is less than the second value.}
	value1 value2
]

lesser-or-equal?: native [
	{Returns TRUE if the first value is less than or equal to the second value.}
	value1 value2
]

minimum: native [
	{Returns the lesser of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

maximum: native [ ; Note: Some datatypes expect all binary ops to be <= this
	{Returns the greater of the two values.}
	value1 [scalar! date! series!]
	value2 [scalar! date! series!]
]

negative?: native [
	{Returns TRUE if the number is negative.}
	number [number! money! time! pair!]
]

positive?: native [
	{Returns TRUE if the value is positive.}
	number [number! money! time! pair!]
]

zero?: native [
	{Returns TRUE if the value is zero (for its datatype).}
	value
]
#extract commit log from each relase cycle

##### set from args #####
args<-commandArgs(trailingOnly=T)

#check the number of arguments
if(length(args) == 0){
  print("use default setting (for Chromium), --args 42 2 2014-06-20 24")
  release_cycle<-42#days(= 6 weeks = 1.5month)
  threshold<-2#commits/release_cycle
  newest_relase_date<-as.Date("2014-06-20")#ver37
  num_release<-24#: a number of past release to trace
}else if(length(args) != 4){
  write("Error: commandline arguments for <release_cycle(days)> <threshold of commits> <newest release date(yyyy-mm-dd)> <the number of going back release> are required", stderr())
  q()
}else{
  release_cycle<-as.numeric(args[1])
  threshold<-as.numeric(args[2])
  newest_relase_date<-as.Date(args[3])
  num_release<-as.numeric(args[4])
}
# import merged git log file
git_log.df<-read.csv("git_log_main_change_merged.csv",header=T)
git_log.df$author_date<-as.Date(git_log.df$author_date)
git_log.df$author_mail<-as.character(git_log.df$author_mail)
#filtering
activity.df<-data.frame(1:num_release,1:2)
names(activity.df)<-c("Duration","Effort")
for(i in 1:num_release){
  git_log_tmp.df<-subset(git_log.df,git_log.df$author_date<(newest_relase_date-release_cycle*(i-1)) & (newest_relase_date-release_cycle*i)<=git_log.df$author_date)
  auth_freq.df<-data.frame(table(git_log_tmp.df$author_mail))
  names(auth_freq.df)<-c("author_mail","commit_count")
  
  activity.df$Duration[i]<-paste(newest_relase_date-release_cycle*(i-1),"-",newest_relase_date-release_cycle*i,sep="")
  # In original paper, non-fulltime developers' effort is caliculated by commit_count/threshold, so using ">="
  # http://gsyc.urjc.es/~grex/repro/2014-msr-effort/msr14-robles-estimating-effort.pdf
  fulltime_auth.df<-subset(auth_freq.df,auth_freq.df$commit_count>=threshold)
  parttime_auth.df<-subset(auth_freq.df,auth_freq.df$commit_count<threshold)
  parttime_auth.df$effort<-parttime_auth.df$commit_count/threshold
  # 28 = 1 month
  activity.df$Effort[i]<-(nrow(fulltime_auth.df)+sum(parttime_auth.df$effort))*(release_cycle/28)
  activity.df$commits[i]<-nrow(git_log_tmp.df)
  activity.df$bugfix_commits[i]<-nrow(subset(git_log_tmp.df,git_log_tmp.df$bug_fix==1))
  activity.df$refactoring_commits[i]<-nrow(subset(git_log_tmp.df,git_log_tmp.df$refactoring_flag==1))
  activity.df$newfunc_commits[i]<-nrow(subset(git_log_tmp.df,git_log_tmp.df$bug_fix!=1 & git_log_tmp.df$refactoring_flag!=1))
  activity.df$add_lines[i]<-sum(git_log_tmp.df$add_lines)
  activity.df$del_lines[i]<-sum(git_log_tmp.df$del_lines)
  activity.df$change_files[i]<-sum(git_log_tmp.df$change_files)
  
  ##temporary dataframe output
  #write.csv(auth_freq.df,paste("author_activity_from_",(newest_relase_date-release_cycle*i),"_to_",(newest_relase_date-release_cycle*(i-1)),".csv",sep=""),row.names=F)
}
write.csv(activity.df,paste("chromium_activity_metrics.csv",sep=""),row.names=F)
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
		require(xgboost)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

		if (is(object, 'tundraContainer') &&
		  # Hack for model object requiring customized
			#	serializer, e.g., xgb.Booster
		  is(object$output$model, 'xgb.Booster')) {
		    file_save <- tempfile()
				on.exit(unlink(file_save))
		    xgboost::xgb.save(object$output$model, file_save)
				stopifnot(!is.na(as.integer(file.info(file_save)$size)))
		    object$output$model <- NULL
				con <- file(file_save, 'rb')
				on.exit(close(con), add = TRUE)
		    object <- structure(class = 'special_serialized_object', list(
		      deserialize = function(x) {
		        file_load <- tempfile()
		        on.exit(unlink(file_load))
						con <- file(file_load, 'wb')
						on.exit(close(con), add = TRUE)
		        writeBin(x$xgb.bin, con, useBytes = TRUE)
						close(con)
		        x$container$output$model <- xgboost::xgb.load(file_load)
		        x$container
		      }, object = list(container = object,
						 							 xgb.bin = readBin(con, raw(), n = file.info(file_save)$size))
		    ))
				close(con)
		}
    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = map(X, along, function(x) FUN(x), subsets)
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=aggr_error, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll) {
    abind::asub(X, ll, drop=F)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        if (length(dim(Y)) < length(dim(X)))
            Y
        else
            aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    else if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along])) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)==dim(X)[along])
        lnames = base::dimnames(X)[[along]]
    else
        lnames = usubsets
    setNames(lapply(idxList, function(ll) subset(X, ll)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=aggr_error) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
#' Fetch the default adapter keyword from the active syberia
#' project's configuration file.
#'
#' @return a string representing the default adapter.
default_adapter <- function() {
  # TODO: (RK) Multi-syberia projects root tracking?

  # Grab the default adapter if it is not provided from the Syberia
  # project's configuration file. If no default is specified there,
  # we will assume we're reading from a file.
  default_adapter <-
    (if (!is.null(syberia_root())) syberia_config()$default_adapter) %||% 'file'
}

#' Fetch a syberia IO adapter.
#'
#' IO adapters are (reference class) objects that have a \code{read}
#' and \code{write} method. By wrapping things in an adapter, you do not have to
#' worry about whether to use, e.g., \code{read.csv} versus \code{s3read}
#' or \code{write.csv} versus \code{s3store}. If you are familiar with
#' the tundra package, think of adapters as like tundra containers for
#' importing and exporting data.
#'
#' For example, we can do: \code{fetch_adapter('file')$write(iris, '/tmp/iris.csv')}
#' and the contents of the built-in \code{iris} data set will be stored
#' in the file \code{"/tmp/iris.csv"}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_adapter <- function(keyword) {
  adapters <- syberiaStructure:::get_cache('adapters')
  keyword <- tolower(keyword)
  is_built_in <- is.element(keyword, names(built_in_adapters))
  if (!is.element(keyword, names(adapters)) ||
      (!is_built_in && fetch_custom_adapter(keyword, modified_check = TRUE))) {
    # If this adapter is not cached, or is a custom adapter and has been
    # modified since being cached, re-compute it.

    if (is.null(adapters)) adapters <- list()
    new_adapter <-
      if (is.element(keyword, names(built_in_adapters)))
        built_in_adapters[[keyword]]()
      else fetch_custom_adapter(keyword)
    adapters[[keyword]] <- new_adapter
    syberiaStructure:::set_cache(adapters, 'adapters')
  }

  # TODO: (RK) Should we re-compile the adapter if the syberia config
  # changed, or force the user to restart R/syberia?
  adapters[[keyword]]
}

#' Publically exported version of \code{fetch_adapter}.
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @export
#' @seealso \code{\link{fetch_adapter}}
fetch_syberia_adapter <- fetch_adapter

#' Fetch a custom syberia IO adapter.
#'
#' Custom adapters are defined in \code{lib/adapters} from the root
#' of the syberia project. Placing a file there with, for example, name 'foo.R',
#' will cause \code{fetch_custom_adapter('foo')} to return an appropriate
#' IO adapter. The file 'foo.R' must contain a 'read', 'write', and (optionally)
#' 'format' function, which will be used to construct the adapter. (See
#' the definition of the adapter reference class.)
#'
#' @param keyword character. The keyword for the adapter (e.g., 'file', 's3', etc.)
#' @param modified_check logical. If \code{TRUE}, will return a logical indicating
#'    whether or not the customer adapter has been modified. By default, \code{FALSE}.
#' @return an \code{adapter} object (defined in this package, syberiaStages)
fetch_custom_adapter <- function(keyword, modified_check = FALSE) {
  # TODO: (RK) Better multi-project support
  adapters_path <- file.path(syberia_root(), 'lib', 'adapters')
  valid_adapters <- vapply(syberia_objects('', adapters_path), function(x)
    tolower(gsub("\\.[rR]$", "", x)), character(1))

  if (!is.element(keyword, valid_adapters))
    stop("There is no adapter ", sQuote(keyword), " for reading and ",
         "writing data. The available adapters are: ",
         paste0(c(names(built_in_adapters), valid_adapters), collapse = ', '),
         call. = FALSE)

  provided_env <- new.env()
  adapter_index <- which(valid_adapters == keyword)[1]
  adapter_file <- names(valid_adapters)[adapter_index]
  filename <- file.path(adapters_path, adapter_file)
  resource <- syberiaStructure:::syberia_resource_with_modification_tracking(
    filename, root = syberia_root(filename), provides = provided_env, body = FALSE)

  if (identical(modified_check, FALSE)) {
    resource$value()
    parse_custom_adapter(provided_env, valid_adapters[adapter_index])
  } else resource$modified
}

#' Ensures a custom adapter resource is valid and returns the corresponding
#' adapter reference class object.
#'
#' There can only be one function defined that contains the string "read".
#' Similarly there can only be one such function containing "write".
#' If this condition is not met, this function will throw an error.
#' Finally, there is also an optional "format" function that can be defined.
#'
#' @param provided_env environment. The environment the adapter was loaded from.
#' @param type character. The keyword for the adapter.
#' @return the \code{adapter} reference class object constructed from the parsed
#'    adapter resource.
parse_custom_adapter <- function(provided_env, type) {
  args <- parse_custom_functions(c('read', 'write'), provided_env, type, 'adapter')
  names(args) <- c('read_function', 'write_function')
  format_fn <- parse_custom_functions(c('format'), provided_env,
                                      type, 'adapter', strict = FALSE)
  if (!is.null(format_fn$format)) args$format_function <- format_fn$format
  args$keyword <- type

  # TODO: (RK) Read defaults for adapter from syberia project config file.
  do.call(adapter$new, args)
}

#' A helper function for formatting parameters for adapters to
#' correctly include an argument "file", with aliases
#' "resource", "filename", "name", and "path".
#'
#' @param opts list. The options that will get passed to the adapter
#'   constructor function.
#' @return the fixed and sanitized formatted options.
common_file_formatter <- function(opts) {
  if (!is.element('resource', names(opts))) {
    filename <- opts$file %||% opts$filename %||% opts$name %||% opts$path
    if (is.null(filename))
      stop("You are trying to read from ", sQuote(.keyword), ", but you did ",
           "not provide a file name.", call. = FALSE)
    opts$resource <- filename
  }
  if (!is.character(opts$resource))
    stop("You are trying to read from ", sQuote(.keyword), ", but you provided ",
         "a filename of type ", sQuote(class(opts$resource)[1]), " instead of ",
         "a string. Make sure you are passing a file name ",
         "(for example, 'example/file.csv')", call. = FALSE)
  opts
}

#' Construct a file adapter.
#'
#' @return an \code{adapter} object which reads and writes to a file.
construct_file_adapter <- function() {
  read_function <- function(opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to read.csv
    if ('.rds' == substring(opts$resource, nchar(opts$resource) - 3, nchar(opts$resource)))
      readRDS(opts$resource)
    else {
      read_csv_params <- c('header', 'sep', 'quote', 'dec', 'fill', 'comment.char',
                           'stringsAsFactors')
      args <- list_merge(list(file = opts$resource, stringsAsFactors = FALSE),
                         opts[read_csv_params])
      do.call(read.csv, args)
    }
  }

  write_function <- function(object, opts) {
    # If the user provided any of the options below in their syberia model,
    # pass them along to write.csv
    if (is.data.frame(object)) {
      write_csv_params <- setdiff(names(formals(write.table)), c('x', 'file'))
      args <- list_merge(
        list(x = object, file = opts$resource, row.names = FALSE),
        opts[write_csv_params])
      do.call(write.csv, args)
    } else {
      save_rds_params <- setdiff(names(formals(saveRDS)), c('object', 'file'))
      args <- list_merge(list(object = object, file = opts$resource),
                         opts[save_rds_params])
      do.call(saveRDS, args)
    }
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(), keyword = 'file')
}

#' Construct an Amazon Web Services S3 adapter.
#'
#' This requires that the user has set up the s3mpi package to
#' work correctly (for example, the s3mpi.path option should be set).
#' (Note that this adapter is not related to R's S3 classes).
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_s3_adapter <- function() {
  load_s3mpi_package <- function() {
    if (!'s3mpi' %in% installed.packages())
      stop("You must install and set up the s3mpi package from ",
           "https://github.com/robertzk/s3mpi", call. = FALSE)
    require(s3mpi)
  }

  read_function <- function(opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3read, args)
  }

  write_function <- function(object, opts) {
    load_s3mpi_package()

    # If the user provided an s3 path, like "s3://somebucket/some/path/", 
    # pass it along to the s3read function.
    args <- list(obj = object, name = opts$resource)
    if (is.element('s3path', names(opts))) args$.path <- opts$s3path
    do.call(s3mpi::s3store, args)
  }

  format_function <- function(opts) {
    environment(common_file_formatter) <- environment()
    opts <- common_file_formatter(opts)
    if (is.element('bucket', names(opts)))
      opts$s3path <- paste0("s3://", opts$bucket, "/")
    opts
  }

  # TODO: (RK) Read default_options in from config, so a user can
  # specify default options for various adapters.
  adapter(read_function, write_function, format_function = format_function,
          default_options = list(), keyword = 's3')
}

#' Construct an adapter for reading to and from an R environment,
#' by default the global environment.
#'
#' @return an \code{adapter} object which reads and writes to Amazon's S3.
construct_R_adapter <- function() {
  read_function <- function(opts) {
    get(opts$resource, envir = opts$env) # TODO: (RK) Support "inherits"?
  }

  write_function <- function(object, opts) {
    assign(opts$resource, object, envir = opts$env)
  }

  adapter(read_function, write_function, format_function = common_file_formatter,
          default_options = list(env = globalenv()), keyword = 'R')
}

# A reference class to abstract importing and exporting data.
adapter <- setRefClass('adapter',
  list(.read_function = 'function', .write_function = 'function',
       .format_function = 'function', .default_options = 'list', .keyword = 'character'),
  methods = list(
    initialize = function(read_function, write_function,
                          format_function = identity, default_options = list(),
                          keyword = character(0)) { 
      .read_function <<- read_function
      .write_function <<- write_function
      .format_function <<- format_function
      .default_options <<- default_options
      .keyword <<- keyword
    },

    read = function(options = list()) {
      .read_function(format(options))
    },

    write = function(value, options = list()) {
      .write_function(value, format(options))
    },

    store = function(...) { write(...) },

    format = function(options) {
      if (!is.list(options)) options <- list(resource = options)

      # Merge in default options if they have not been set.
      for (i in seq_along(.default_options))
        if (!is.element(name <- names(.default_options)[i], names(options)))
          options[[name]] <- .default_options[[i]]

      environment(.format_function) <<- environment()
      .format_function(options)
    },

    show = function() {
      has_default_options <- length(.default_options) > 0
      cat("A syberia IO adapter of type ", sQuote(.keyword), ' with',
          if (has_default_options) '' else ' no', ' default options',
          if (has_default_options) ': ' else '.', "\n", sep = '')
      if (has_default_options) print(.default_options)
    }
  )
)

built_in_adapters <- list(file = construct_file_adapter,
                          s3 = construct_s3_adapter,
                          r = construct_R_adapter)

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v11b <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if(debug==TRUE){print(paste("argument test:", argument_test))}

  
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly one of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done
  
  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors

  # save some space by removing my_data
  rm(my_data)

  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)

  
  # make sure everything is sorted by id
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]

  if(debug==TRUE){
    #eigen_vectors.test<<-eigen_vectors
    #eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  #num_samples <- ncol(my_data$eigen_vectors)
  num_samples <- ncol(eigen_vectors)
  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  #pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug)
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(eigen_vectors), debug)

  #if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  # save some space by removing pch_object
  rm(pch_object)
  
  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==0 ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    #num_lines_string <- paste("wc -l ", metadata_table)
    #num_lines <- scan(pipe(num_lines_string), what=list(0, NULL))[[1]]
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                                 read.table(
                                            file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                            colClasses = "character", check.names=FALSE,
                                            comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE #, nrows=num_lines
                                            )
                                 )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        #if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        #if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        #if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          #test.color_column <<- color_column
          #test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      #if(debug==TRUE){ test1<<-metadata_column }
      
      image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
      figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      #if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
      #if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")

  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      #plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
    pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    #if(debug==TRUE){pch_levels.test<<-pch_levels}
    pch_labels <- pch_labels
    #if(debug==TRUE){pch_labels.test<<-pch_labels}
    
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      #plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    #if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch))) ##### ? does this need to be a global ? 10-7-14


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  #if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ order(sample_names), metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  #if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  #if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  #if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

# This script uses matR to generate 2 or 3 dimmensional pcoas

# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata 
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table

# basic operation is to produce a color-less pcoa of the input data

# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# This is a PCoA plotting functions that can handle a number of different scenarios
# It always requires a *.PCoA file (like that produce by AMETHST/plot_pco.r)
# It can handle metadata as a table - producing plots for all or selected metadata columns (metadata used to generate colors automatically)
# It can handle an amthst groups file as metadata (metadata used to generate colors automatically)
# It can handle a list of colors - using them to pain the points directly
# It can handle the case when there is no metadata - painting all of points the same
# users can also specify a pch table to control the shape of plotted icons (this feature may not be ready yet)

render_pcoa.v11b <- function(
                            PCoA_in="", # annotation abundance table (raw or normalized values)
                            image_out="default",
                            figure_main ="principal coordinates",
                            components=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
                            label_points=FALSE, # default is off
                            metadata_table=NA, # matrix that contains colors or metadata that can be used to generate colors
                            metadata_column_index=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
                            amethst_groups=NA,        
                            color_list=NA, # use explicit list of colors - trumps table if both are supplied
                            pch_behavior="default", #  "default" use pch_default for all; "auto" automatically assign pch from table; "asis" use integer values in the column
                            pch_default=16,
                            pch_table="default",
                            pch_column=1,
                            pch_labels="default",
                            image_width_in=22,
                            image_height_in=17,
                            image_res_dpi=300,
                            width_legend = 0.2, # fraction of width used by legend
                            width_figure = 0.8, # fraction of width used by figure
                            title_cex = "default", # cex for the title of title of the figure, "default" for auto scaling
                            legend_cex = "default", # cex for the legend, default for auto scaling
                            figure_cex = 2, # cex for the figure
                            figure_symbol_cex=2,
                            vert_line="dotted", # "blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"
                            bar_cex = "default",
                            bar_vert_adjust = 0,  
                            use_all_metadata_columns=FALSE, # option to overide color_column -- if true, plots are generate for all of the metadata columns
                            debug=FALSE
                            )
  
{
  
  require(matR)
  require(scatterplot3d)
  
  argument_test <- is.na(c(metadata_table,amethst_groups,color_list)) # check that incompatible options were not selected
  if ( 3 - length(subset(argument_test, argument_test==TRUE) ) > 1){
    stop(
         paste(
               "\n\nOnly on of these can have a non NA value:\n",
               "     metadata_table: ", metadata_table,"\n",
               "     amethst_groups: ", amethst_groups, "\n",
               "     color_list    : ", color_list, "\n\n",
               sep="", collapse=""
               )
         )
  }

  
  ######################
  ######## MAIN ########
  ######################

  # load data - everything is sorted by id
  my_data <- load_pcoa_data(PCoA_in) # import PCoA data from *.PCoA file --- this is always done

  # load data - everything is sorted by id
  eigen_values <- my_data$eigen_values
  eigen_vectors <- my_data$eigen_vectors

  # save some space by removing my_data
  rm(my_data)

  # get the sample names for ordering data, colors, and pch later
  sample_names <- rownames(eigen_vectors)

  
  # make sure everything is sorted by id
  eigen_vectors <- eigen_vectors[ order(sample_names), ]
  eigen_values <- eigen_values[ order(sample_names) ]

  if(debug==TRUE){
    #eigen_vectors.test<<-eigen_vectors
    #eigen_values.test<<-eigen_values  
  }
  
  #eigen_vectors <- eigen_vectors[ order(rownames(my_data$eigen_vectors)), ]
  #eigen_values <- eigen_values[ order(rownames(my_data$eigen_vectors)) ] # order will reflect id
  
  #num_samples <- ncol(my_data$eigen_vectors)
  num_samples <- ncol(eigen_vectors)
  
  #if ( debug == TRUE ){ print(paste("num_samples: ", num_samples)) } 

  if(debug==TRUE){print("made it here 1")}

  # CHECK FOR LEVELS OF PCH AS FACTOR _ DEFINE TWO TYPES OF LEGENDS
  # load pch - handles table or integer(pch_default)




  
  # somwhere here logic for three pch options
  #  pch_behavior = c("default", "auto", "asis")


  if(debug==TRUE){print("ABOUT TO LOAD PCH")}
  #pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(my_data$eigen_vectors), debug)
  pch_object <- load_pch(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, rownames(eigen_vectors), debug)

  #if(debug==TRUE){ pch_object.test <<- pch_object}
#return(list( "plot_pch_values"=plot_pch_values, "pch.levels"=pch_levels, "pch.labels"=pch_labels) )
  
  plot_pch <- pch_object$plot_pch_vector
  pch_levels <- pch_object$pch_levels
  pch_labels <- pch_object$pch_labels

  # save some space by removing pch_object
  rm(pch_object)
  
  if(debug==TRUE){print("made it here 2")}

                                        #if(debug==TRUE){print(paste("main.pch_levels", pch_levels))}
  #if(debug==TRUE){print(paste("main.pch_labels", pch_labels))}
 
  
  
  if(debug==TRUE){print(paste("2.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("2.pch_labels", pch_labels))}

  
  #####################################################################################
  ########## PLOT WITH NO METADATA OR COLORS SPECIFIED (all point same color) #########
  #####################################################################################
  if ( length(argument_test==TRUE)==0 ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".NO_COLOR.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".NO_COLOR.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }
    
    column_levels <- "data" # assign necessary defaults for plotting
    num_levels <- 1
    color_levels <- 1
    ncol.color_matrix <- 1
    pcoa_colors <- "black"   

    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################


  
  #####################################################################################
  ########### PLOT WITH AMETHST GROUPS (colors generated by load_metadata) ############
  #####################################################################################
  if ( identical( is.na(amethst_groups), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".AMETHST_GROUPS.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".AMETHST_GROUPS.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    con_grp <- file(amethst_groups) # get metadata and generate colors from amethst groups file
    open(con_grp)
    line_count <- 1
    groups.list <- vector(mode="character")
    while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
      new_line <- my_line
      split_line <- unlist(strsplit(my_line, split=","))
      split_line.list <- rep(line_count, length(split_line))
      names(split_line.list) <- split_line
      groups.list <- c(groups.list, split_line.list)
      line_count <- line_count + 1
    }
    close(con_grp)
    if ( length(groups.list) != length(unique(names(groups.list))) ){
      stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
    }
    metadata_column <- matrix(groups.list, ncol=1)

    suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
    if( is.na(numericCheck[1])==FALSE ){
      column_name = colnames(metadata_column)[1]
      row_names = rownames(metadata_column)
      metadata_column <- matrix(numericCheck, ncol=1)
      colnames(metadata_column) <- column_name
      rownames(metadata_column) <- row_names
    }
    #sample_names
    metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by sample 1d
    #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
    color_column <- create_colors(metadata_column, color_mode = "auto")

    column_levels <- levels(as.factor(as.matrix(metadata_column))) 
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    
    colnames(metadata_column) <- "amethst_metadata"
    column_levels <- column_levels[ order(column_levels) ] # NEW (order by levels values)
    color_levels <- color_levels[ order(column_levels) ] # NEW (order by levels values)

    pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
    
  }
  #####################################################################################
  #####################################################################################

  if(debug==TRUE){print("made it here 3")}

  if(debug==TRUE){print(paste("3.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("3.pch_labels", pch_labels))}
  
  #####################################################################################
  ############ PLOT WITH LIST OF COLORS (colors generated by load_metadata) ###########
  #####################################################################################
  if ( identical( is.na(color_list), FALSE ) ){ # create names for the output files
    if ( identical(image_out, "default") ){
      image_out = paste( PCoA_in,".color_List.PCoA.png", sep="", collapse="" )
      figure_main = paste( PCoA_in, ".color_list.PCoA", sep="", collapse="" )
    }else{
      image_out = paste(image_out, ".png", sep="", collapse="")
      figure_main = paste( image_out,".PCoA", sep="", collapse="")
    }

    column_levels <- levels(as.factor(as.matrix(color_list))) # get colors directly from list of colors
    num_levels <- length(column_levels)
    color_levels <- col.wheel(num_levels)
    #color_levels <- col.wheel(num_levels)
    ncol.color_matrix <- 1
    pcoa_colors <- color_list
    
    create_plot( # generate the plot
                PCoA_in,
                ncol.color_matrix,
                eigen_values, eigen_vectors, components,
                column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                image_out,figure_main,
                image_width_in, image_height_in, image_res_dpi,
                width_legend, width_figure,
                title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                )
  }
  #####################################################################################
  #####################################################################################

  
  if(debug==TRUE){print("made it here 4")}

  if(debug==TRUE){print(paste("4.pch_levels", pch_levels))}
  if(debug==TRUE){print(paste("4.pch_labels", pch_labels))}
  
  #####################################################################################
  ########### PLOT WITH METADATA_TABLE (colors produced from color_matrix) ############
  ######## CAN HANDLE PLOTTING ALL OR A SINGLE SELECTED METADATA TABLE COLUMN #########
  #####################################################################################
  if ( identical( is.na(metadata_table), FALSE ) ){

    #num_lines_string <- paste("wc -l ", metadata_table)
    #num_lines <- scan(pipe(num_lines_string), what=list(0, NULL))[[1]]
    metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                                 read.table(
                                            file=metadata_table,row.names=1,header=TRUE,sep="\t",
                                            colClasses = "character", check.names=FALSE,
                                            comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE #, nrows=num_lines
                                            )
                                 )   
    #metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
    
    if(debug==TRUE){print("made it here 5")}
    
    if ( use_all_metadata_columns==TRUE ){ # AUTOGENERATE PLOTS FOR ALL COLUMNS IN THE METADATA FILE - ONE PLOT PER METADATA COLUMN

      ncol.color_matrix <- ncol( metadata_matrix) # get then number of columns in the metadata data file = number of plots
      for (i in 1:ncol.color_matrix){ # loop to process through all columns

        if(debug==TRUE){print("made it here 6")}
        
        metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
        #if(debug==TRUE){ test1<<-metadata_column }

        if(debug==TRUE){print("made it here 7")}
        if(debug==TRUE){print(paste("7.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("7.pch_labels", pch_labels))}
       
        
        image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
        figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
        
        suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
        if( is.na(numericCheck[1])==FALSE ){
          column_name = colnames(metadata_column)[1]
          row_names = rownames(metadata_column)
          metadata_column <- matrix(numericCheck, ncol=1)
          colnames(metadata_column) <- column_name
          rownames(metadata_column) <- row_names
        }

        if(debug==TRUE){print("made it here 8")}
        if(debug==TRUE){print(paste("8.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("8.pch_labels", pch_labels))}
       

        
        #if(debug==TRUE){ test2<<-metadata_column }
        
        metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
        #metadata_column <- metadata_column[ order(rownames(metadata_column)),,drop=FALSE ] # order the metadata by value
        #if(debug==TRUE){ test3<<-metadata_column }
        
        color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
        ncol.color_matrix <- 1 
        column_factors <- as.factor(metadata_column) 
        column_levels <- levels(as.factor(metadata_column))
        num_levels <- length(column_levels)
        color_levels <- col.wheel(num_levels)

        rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
        eigen_vectors <- eigen_vectors[ rownames(color_column), ]

        if(debug==TRUE){print("made it here 9")}
        if(debug==TRUE){print(paste("9.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("9.pch_labels", pch_labels))}
       
        
        #plot_pch <- plot_pch[ rownames(color_column) ]# make sure pch is sorted identically to colors
        
        pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
  
        if(debug==TRUE){
          #test.color_column <<- color_column
          #test.pcoa_colors <<- pcoa_colors
        }


        if(debug==TRUE){print("made it here 10")}
        if(debug==TRUE){print(paste("10.pch_levels", pch_levels))}
        if(debug==TRUE){print(paste("10.pch_labels", pch_labels))}
       

        
        create_plot( # generate the plot
                    PCoA_in,
                    ncol.color_matrix,
                    eigen_values, eigen_vectors, components,
                    column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                    image_out,figure_main,
                    image_width_in, image_height_in, image_res_dpi,
                    width_legend, width_figure,
                    title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                    )        
      }
      
      
    }else if ( use_all_metadata_columns==FALSE ){ # ONLY CREATE A PLOT FOR THE SELECTED COLUMN IN THE METADATA FILE
      

      metadata_column <- metadata_matrix[ ,metadata_column_index,drop=FALSE ] # get column i from the metadata matrix
      #if(debug==TRUE){ test1<<-metadata_column }
      
      image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
      figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot
      
      suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
      if( is.na(numericCheck[1])==FALSE ){
        column_name = colnames(metadata_column)[1]
        row_names = rownames(metadata_column)
        metadata_column <- matrix(numericCheck, ncol=1)
        colnames(metadata_column) <- column_name
        rownames(metadata_column) <- row_names
      }

      #if(debug==TRUE){ test2<<-metadata_column }
      
      #metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
      metadata_column <- metadata_column[ order(sample_names),,drop=FALSE ] # order the metadata by value
      #if(debug==TRUE){ test3<<-metadata_column }
      
      color_column <- create_colors(metadata_column, color_mode = "auto") # set parameters for plotting
      ncol.color_matrix <- 1 
      column_factors <- as.factor(metadata_column) 
      column_levels <- levels(as.factor(metadata_column))
      num_levels <- length(column_levels)
      color_levels <- col.wheel(num_levels)
      rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors)) # make sure that vectors are sorted identically to the colors
      eigen_vectors <- eigen_vectors[ rownames(color_column), ]        
      pcoa_colors <- as.character(color_column[,1]) # convert colors to a list after they've been used to sort the eigen vectors
      create_plot( # generate the plot
                  PCoA_in,
                  ncol.color_matrix,
                  eigen_values, eigen_vectors, components,
                  column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                  image_out,figure_main,
                  image_width_in, image_height_in, image_res_dpi,
                  width_legend, width_figure,
                  title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                  )
      
    }else{
      stop(paste("invalid value for use_all_metadata_columns(", use_all_metadata_columns,") was specified, please try again", sep="", collapse=""))
    }
  }
  
}
#####################################################################################

######################
###### END MAIN ######
######################
  
######################
######## SUBS ########
######################

#######################
######## SUB(1): Function to import the data from a pre-calculated PCoA
######################
load_pcoa_data <- function(PCoA_in){

  #print("loading PCoA")
  
  con_1 <- file(PCoA_in)
  con_2 <- file(PCoA_in)
  # read through the first time to get the number of samples
  open(con_1);
  num_values <- 0
  data_type = "NA"
  while ( length(my_line <- readLines(con_1,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("PCO", my_line) ) == 1  ){
      num_values <- num_values + 1
    }
  }
  close(con_1)
  # create object for values
  eigen_values <- matrix("", num_values, 1)
  dimnames(eigen_values)[[1]] <- 1:num_values
  eigen_vectors <- matrix("", num_values, num_values)
  dimnames(eigen_vectors)[[1]] <- 1:num_values
  # read through a second time to populate the R objects
  value_index <- 1
  vector_index <- 1
  open(con_2)
  current.line <- 1
  data_type = "NA"
  while ( length(my_line <- readLines(con_2,n = 1, warn = FALSE)) > 0) {
    if ( length( grep("#", my_line) ) == 1  ){
      if ( length( grep("EIGEN VALUES", my_line) ) == 1  ){
        data_type="eigen_values"
      } else if ( length( grep("EIGEN VECTORS", my_line) ) == 1 ){
        data_type="eigen_vectors"
      }
    }else{
      split_line <- noquote(strsplit(my_line, split="\t"))
      if ( identical(data_type, "eigen_values")==TRUE ){
        dimnames(eigen_values)[[1]][value_index] <- noquote(split_line[[1]][1])
        eigen_values[value_index,1] <- noquote(split_line[[1]][2])       
        value_index <- value_index + 1
      }
      if ( identical(data_type, "eigen_vectors")==TRUE ){
        dimnames(eigen_vectors)[[1]][vector_index] <- noquote(split_line[[1]][1])
        for (i in 2:(num_values+1)){
          eigen_vectors[vector_index, (i-1)] <- as.numeric(noquote(split_line[[1]][i]))
        }
        vector_index <- vector_index + 1
      }
    }
  }
  close(con_2)
  # finish labeling of data objects
  dimnames(eigen_values)[[2]] <- "EigenValues"
  dimnames(eigen_vectors)[[2]] <- dimnames(eigen_values)[[1]]
  class(eigen_values) <- "numeric"
  class(eigen_vectors) <- "numeric"
  # write imported data to global objects
  #eigen_values <<- eigen_values
  #eigen_vectors <<- eigen_vectors
  return(list(eigen_values=eigen_values, eigen_vectors=eigen_vectors))
  
}
######################
######################
######################


## ######################
## # SUB(2): Function to load the metadata/ generate or import colors for the points
## ######################
## #load_metadata <- function(metadata_table, metadata_column, color_list, amethst_groups){
## load_metadata <- function(metadata_table, ...){
  
##   if ( identical( is.na(metadata_table), FALSE ) ){ # HANDLE METADATA TABLE for generating colors
##     metadata_matrix <- as.matrix( # Import metadata table, use it to generate colors
##                               read.table(
##                                          file=metadata_table,row.names=1,header=TRUE,sep="\t",
##                                          colClasses = "character", check.names=FALSE,
##                                          comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
##                                          )
##                               )   
##     metadata_matrix <- metadata_matrix[ order(rownames(metadata_matrix)),,drop=FALSE ]  # make sure that the metadata matrix is sorted (ROWWISE) by id
##     return(metadata_matrix)
    
##   } else if ( identical( is.na(amethst_groups), FALSE ) ){ # HANDLE AMETHST GROUPS for generating colors

##     con_grp <- file(amethst_groups)
##     open(con_grp)
##     line_count <- 1
##     groups.list <- vector(mode="character")
##     while ( length(my_line <- readLines(con_grp,n = 1, warn = FALSE)) > 0) {
##       new_line <- my_line
##       split_line <- unlist(strsplit(my_line, split=","))
##       split_line.list <- rep(line_count, length(split_line))
##       names(split_line.list) <- split_line
##       groups.list <- c(groups.list, split_line.list)
##       line_count <- line_count + 1
##     }
##     close(con_grp)
##     if ( length(groups.list) != length(unique(names(groups.list))) ){
##       stop("One or more groups have redundant entries - this is not allowed for coloring the PCoA")
##     }
##     metadata_matrix <- matrix(groups.list, ncol=1)
##     metadata_matrix <- metadata_matrix[ order(metadata_matrix),,drop=FALSE ] # order by metadata value
##     colnames(metadata_matrix) <- "amethst_metadata"
##     #column_levels <<- levels(metadata_column)
##     #num_levels <<- length(column_levels)
##     #color_levels <<- col.wheel(num_levels)
##     #ncol.color_matrix <<- 1
##     #pcoa_colors <<- color_list
##     return(metadata_matrix)
    
##   }else if ( identical( is.na(color_list), FALSE ) ){ # HANDLE COLOR LIST; use list of color if it is supplied
    
##     column_levels <<- levels(as.factor(as.matrix(color_list)))
##     num_levels <<- length(column_levels)
##     color_levels <<- col.wheel(num_levels)
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- color_list
   
##   }else{ # HANDLE NO INPUT METADATA OR COLORS; use a default of black if no table or list is supplied
                                     
##     column_levels <<- "data"
##     num_levels <<- 1
##     color_levels <<- 1
##     ncol.color_matrix <<- 1
##     pcoa_colors <<- "black"    

##   }
## }
## ######################
## ######################

  
######################
# SUB(3): Function to import the pch information for the points # load pch matrix if one is specified
######################
load_pch <- function(pch_behavior, pch_default, pch_table, pch_column, pch_labels, sample_names, num_samples, my_names, debug){

  
#pch_behavior=c("default", "auto", "asis")

  if(debug==TRUE){print(rep("LOADING PCH",50))}
  
  if(debug==TRUE){print(paste("class(my_names): ", class(my_names), sep=""))}

  if(debug==TRUE){print(paste("(preloop) PCH_BEHAVIOR: ", pch_behavior))}
  
  if( identical(pch_behavior,"default") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    my_names <- gsub("\"", "", my_names)
    pch_matrix <- data.matrix(matrix(rep(pch_default, num_samples), ncol=1))
    plot_pch <- pch_matrix[ , 1, drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    pch_labels <- levels(as.factor(plot_pch_vector))
    #names(plot_pch_vector) <- my_names
    pch_levels <- pch_labels
    pch_labels <- pch_labels
    if(debug==TRUE){
      print(paste("plot_pch_vector: ", class(plot_pch_vector)))
      print(plot_pch_vector)
      #plot_pch_vector.test <<- plot_pch_vector
    }
   
  }else if ( identical(pch_behavior,"asis") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}
    
    pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
    pch_matrix <- pch_matrix[ order(sample_names), ]
    plot_pch <- pch_matrix[ , pch_column, drop=FALSE ]
    #plot_pch <- pch_matrix[ order(pch_column), drop=FALSE]
    plot_pch_vector <- as.vector(plot_pch)
    names(plot_pch_vector) <- sample_names
    pch_levels <- levels(as.factor(plot_pch_vector))
    #if(debug==TRUE){pch_levels.test<<-pch_levels}
    pch_labels <- pch_labels
    #if(debug==TRUE){pch_labels.test<<-pch_labels}
    
    if(debug==TRUE){print(paste("ASIS.pch_labels", pch_labels))}
    if(debug==TRUE){print(paste("ASIS.pch_levels", pch_levels))}
    
    if( length(pch_levels)!=length(pch_labels) ){ stop("you have (", length(pch_labels), ") labels in pch_labels for (", length(pch_levels),") unique factor levels") }
   
    if(debug==TRUE){
      print(paste("plot_pch_vector class: ", class(plot_pch_vector)))
      print(paste("plot_pch_vector: ",plot_pch_vector))
      #plot_pch_vector.test <<- plot_pch_vector
    }
    
  }else if( identical(pch_behavior, "auto") ){

    if(debug==TRUE){print(paste("(in loop) PCH_BEHAVIOR: ", pch_behavior))}

    # pch_matrix <- data.matrix(read.table(pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))

      pch_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
                              read.table(
                                         file=pch_table,row.names=1,header=TRUE,sep="\t",
                                         colClasses = "character", check.names=FALSE,
                                         comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
                                         )
                              )   

    #if(debug==TRUE){ pch_matrix.test <<- pch_matrix }
    pch_temp <- create_pch(pch_matrix, pch_column, sample_names, debug)
    plot_pch_vector <- as.vector(pch_temp$my_pch)
    pch_levels <- pch_temp$pch_levels
    pch_labels <- names(pch_levels)  
    
  }else{
    stop(paste("( ",pch_behavior, " )", "is an invalid pch_behavior option value - try \"default\", \"asis\", or \"auto\""))
  }
                                    
  if( length(plot_pch_vector) != num_samples ){
    stop(paste("The number of samples in pch column ( ", length(plot_pch), " ) does not match number of samples ( ", num_samples, " )"))
  }

  return(list( "plot_pch_vector"=plot_pch_vector, "pch_levels"=pch_levels, "pch_labels"=pch_labels) )
}
######################
######################


######################
# SUB(3): Sub to provide scaling for title and legened cex
######################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
  
  # get figure width and height from pin
  my_width <- my_pin[1]
  my_height <- my_pin[2]
  
  # get margine from mai
  my_margin_bottom <- my_mai[1]
  my_margin_left <- my_mai[2]
  my_margin_top <- my_mai[3]
  my_margin_right <- my_mai[4]
  
  #if(debug==TRUE){
  #  print(paste("my_pin: ", my_pin, sep=""))
  #  print(paste("my_mai: ", my_mai, sep=""))
  #}
  
  # find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
  label_width_max <- 0
  for (i in 1:length(my_labels)){  
    label_width <- strwidth(my_labels[i],'inches')
    if ( label_width > label_width_max){ label_width_max<-label_width  }
  }
  label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_width: ", my_width, "\n", 
  ##                           "label_width_max: ", label_width_max, "\n",
  ##                           "label_width_scale_max: ", label_width_scale_max, "\n",
  ##                           sep=""))  
  ##                 }
  
  
  # find the number of labels, and figure out the maximum height scaling that is possible
  label_height_max <- 0
  for (i in 1:length(my_labels)){  
    label_height <- strheight(my_labels[i],'inches')
    if ( label_height > label_height_max){ label_height_max<-label_height  }
  }
  adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
  label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
  ## if(debug==TRUE){ 
  ##                 cat(paste("\n", "my_height: ", my_height, "\n", 
  ##                           "label_height_max: ", label_height_max, "\n", 
  ##                           "length(my_labels): ", length(my_labels), "\n",
  ##                           "label_height_scale_max: ", label_height_scale_max, "\n",
  ##                           sep="" )) 
  ##                 }
  
  # max possible scale is the smaller of the two 
  scale_max <- min(label_width_scale_max, label_height_scale_max)
  # adjust by buffer
  #scale_max <- scale_max*(100-buffer/100) 
  adjusted_scale_max <- ( scale_max * (1-reduce_by) )
  #if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep=""))  }
  return(adjusted_scale_max)
  
}

######################
######################

######################
# SUB(3): Fetch par values of the current frame - use to scale cex
######################
par_fetch <- function(){
    my_pin<-par('pin')
    my_mai<-par('mai')
    my_mar<-par('mar')
    return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))    
}
######################
######################





######################
# SUB(5): Workhorse function that creates the plot
######################
create_plot <- function(
                        PCoA_in,
                        ncol.color_matrix,
                        eigen_values, eigen_vectors, components,
                        column_levels, num_levels, color_levels, pcoa_colors, plot_pch, pch_labels, pch_levels,
                        image_out,figure_main,
                        image_width_in, image_height_in, image_res_dpi,
                        width_legend, width_figure,
                        title_cex, legend_cex, figure_cex, figure_symbol_cex, bar_cex, bar_vert_adjust, label_points, vert_line, debug
                        ){

  if(debug==TRUE){print("creating figure")}
  
  png( # initialize the png 
      filename = image_out,
      width = image_width_in,
      height = image_height_in,
      res = image_res_dpi,
      units = 'in'
      )

  # LAYOUT CREATION HAS TO BE DICTATED BY PCH TO A DEGREE _ NUM LEVELS (1 or more)
  # Determine num levels for pch
  num_pch <- length(levels(as.factor(plot_pch)))
  # CREATE THE LAYOUT
  if ( num_pch > 1 ){
    my_layout <- layout( matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(0.5,0.5), heights=c(0.1,0.8,0.3,0.1) )
  }else{
    my_layout <- layout(  matrix(c(1,1,2,3,4,4), 3, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.8,0.1) )
    # requires an extra plot.new() to skip over pch legend (frame 4 or none )
  }
                                        # my_layout <- layout(  matrix(c(1,1,2,3,4,3,5,5), 4, 2, byrow=TRUE ), widths=c(width_legend,width_figure), heights=c(0.1,0.4,0.8,0.4,0.1) ) # for auto pch legend
  layout.show(my_layout)

  # PLOT THE TITLE (layout frame 1)
  par( mai = c(0,0,0,0) )
  par( oma = c(0,0,0,0) )
  plot.new()
  if ( identical(title_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the title cex")}
    title_par <- par_fetch()
    title_cex <- calculate_cex(figure_main, title_par$my_pin, title_par$my_mai, reduce_by=0.10)
  }
  text(x=0.5, y=0.5, figure_main, cex=title_cex)
  
  # PLOT THE LEGEND (layout frame 2)
  plot.new()
  if ( identical(legend_cex, "default") ){ # automatically scale cex for the legend
    if(debug==TRUE){print("autoscaling the legend cex")}
    legend_par <- par_fetch()
    legend_cex <- calculate_cex(column_levels, legend_par$my_pin, legend_par$my_mai, reduce_by=0.40)
  }
  legend( x="center", y="center", legend=column_levels, pch=15, col=color_levels, cex=legend_cex)

  # PLOT THE PCoA FIGURE (layout frame 3)
  # set par options (Most of the code in this section is copied/adapted from Dan Braithwaite's pco plotting in matR)


  #par(op)
  par <- list ()
  #par$mar <- par()['mar']
  #par$oma <- par()['oma']
                                        #par$mar <- c(4,4,4,4)
  #par$mar <- par(op)['mar']
  #par$oma <- par(op)['oma']
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  par$main <- ""#figure_main
  #par$labels <- if (length (names (x)) != 0) names (x) else samples (x)
  if ( label_points==TRUE ){
    par$labels <-  rownames(eigen_vectors)
  } else {
    par$labels <- NA
  }
  #if (length (groups (x)) != 0) par$labels <- paste (par$labels, " (", groups (x), ")", sep = "")
  par [c ("xlab", "ylab", if (length (components) == 3) "zlab" else NULL)] <- paste ("PC", components, ", R^2 = ", format (eigen_values [components], dig = 3), sep = "")
  #col <- if (length (groups (x)) != 0) groups (x) else factor (rep (1, length (samples (x))))
  #levels (col) <- colors() [sample (length (colors()), nlevels (col))]
  #g <- as.character (col)
  #par$pch <- 19
  par$cex <- figure_cex
  #par$oma <- c(1,1,1,1)
  #par$mai <- c(1,1,1,1)
  # main plot paramters - create the 2d or 3d plot
  i <- eigen_vectors [ ,components [1]]
  j <- eigen_vectors [ ,components [2]]
  k <- if (length (components) == 3) eigen_vectors [ ,components [3]] else NULL
  if (is.null (k)) {
    #par$col <- col

     par$cex <- figure_cex
     par$col <- pcoa_colors ####<--------------
     #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
     par$pch <- plot_pch
    #par$cex.symbols <- figure_symbol_cex
    #par <- resolveMerge (list (...), par)
     xcall (plot, x = i, y = j, with = par, without = "labels")
     xcall (points, x = i, y = j, with = par, without = "labels")
     grid ()
  } else {
    # parameter "color" has to be specially handled.
    # "points" above wants "col", scatterplot3d wants "color", and we
    # want the user not to worry about it...
    # par$color <- col
    #par$cex <- figure_cex
    par$color <- pcoa_colors
    #if(debug==TRUE){print(paste("func_pch: ",plot_pch, sep="")}
    par$pch <- plot_pch
    par$cex.symbols <- figure_symbol_cex
    par$type <- "h"
    par$lty.hplot <- vert_line
    par$axis <- TRUE
    par$box <- FALSE
    #par <- resolveMerge (list (...), par)
    reqPack ("scatterplot3d")
    xys <- xcall (scatterplot3d, x = i, y = j, z = k, with = par,
                  without = c ("cex", "labels")) $ xyz.convert (i, j, k)
                  #without = c ("labels")) $ xyz.convert (i, j, k)
    i <- xys$x ; j <- xys$y
  }
  text (x = i, y = j, labels = par$labels, pos = 4, cex = par$cex)
  #invisible (P)
  #})

  # PCH LEGEND (4 or doesn't exist) ############ <-

  if (num_pch>1){
    #par( mai = c(0,0,0,0) )
    #par( oma = c(0,0,0,0) )
    plot.new()
    par_legend_par <- par_fetch()
    par_legend_cex <- calculate_cex(column_levels, par_legend_par$my_pin, par_legend_par$my_mai, reduce_by=0.40)
    #my_pch_levels <<- as.integer(levels(as.factor(plot_pch))) ##### ? does this need to be a global ? 10-7-14


    if(debug==TRUE){print("made it here 11")}
    if(debug==TRUE){print(paste("11.pch_levels", pch_levels))}
    if(debug==TRUE){print(paste("11.pch_labels", pch_labels))}
       
    #if( identical(pch_behavior, "default") ){
    #  pch_legend_text <- rep("pch",num_pch)
    #}else{
      #pch_legend_text<-pch_labels[ order(pch_labels) ]
    #  pch_legend_text <- pch_labels
    #  if ( length(pch_legend_text)!=num_pch ){
    #    stop(paste("length(pch_legend_text) (", length(pch_legend_text), ") and num of unique pch entries (", num_pch,") is not the same."))
    #  }
    #}


    #pch_legend_pch <- as.integer(levels(as.factor(plot_pch)))
    #ordered_pch_legend_pch <- pch_legend_pch[ order(pch_legend_pch) ]
    pch_levels <- as(pch_levels, "numeric")
    legend( x="center", y="center", legend=pch_labels, pch=pch_levels, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", y="center", legend=pch_legend_text, pch=ordered_pch_legend_pch, cex=par_legend_cex, pt.cex=par_legend_cex)
    #legend( x="center", legend="TEST", cex=par_legend_cex, pt.cex=par_legend_cex)
  }

  # PLOT THE COLOR BAR (frame 4 or 5)
  #par( mar = c(2,2,2,2) )
  #par( oma = c(1,1,1,1) )
  bar_x <- 1:num_levels
  bar_y <- 1
  bar_z <- matrix(1:num_levels, ncol=1)
  image(x=bar_x,y=bar_y,z=bar_z,col=color_levels,axes=FALSE,xlab="",ylab="")
  loc <- par("usr")
  if( identical(bar_cex,"default") ){
    bar_texts <- paste(column_levels[1], column_levels[num_levels])
    bar_par <- par_fetch()
    bar_cex <- calculate_cex(bar_texts, bar_par$my_pin, bar_par$my_mai, reduce_by=0.10)
  }
  text(loc[1], (loc[1]+bar_vert_adjust), column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
#1 3
  
  text(loc[2], (loc[1]+bar_vert_adjust), column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))

  #text(loc[2], (loc[1]+bar_vert_adjust), paste(column_levels[num_levels],":1",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[2]+bar_vert_adjust), paste(column_levels[num_levels],":2",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[3]+bar_vert_adjust), paste(column_levels[num_levels],":3",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], (loc[4]+bar_vert_adjust), paste(column_levels[num_levels],":4",sep=""), pos = 2, xpd = T, cex=bar_cex, adj=c(0,0))
  
                                        #text(loc[1], loc[2], column_levels[1], pos = 4, xpd = T, cex=bar_cex, adj=c(0,0))
  #text(loc[2], loc[2], column_levels[num_levels], pos = 2, xpd = T, cex=bar_cex, adj=c(0,1))
  
  graphics.off()
}
######################
######################


######################
# SUB(5): Handle partially formatted metadata to produce colors for a single column in a metadata table
######################
## column_color <- function( color_matrix, my_color_mode="auto", my_column ){
##   ncol.color_matrix <<- ncol(color_matrix)
##   plot_colors.matrix <<- create_colors(color_matrix, color_mode=my_color_mode)
##   column_factors <<- as.factor(color_matrix[,my_column])
##   column_levels <<- levels(as.factor(color_matrix[,my_column]))
##   num_levels <<- length(column_levels)
##   color_levels <<- col.wheel(num_levels)
##   pcoa_colors <<- plot_colors.matrix[,my_column]
## }
######################
######################

  
######################
# SUB(6): Create optimal contrast color selection using a color wheel
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html 
######################
col.wheel <- function(num_col, my_cex=0.75) {
  cols <- rainbow(num_col)
  col_names <- vector(mode="list", length=num_col)
  for (i in 1:num_col){
    col_names[i] <- getColorTable(cols[i])
  }
  cols
}
######################
######################


######################
# SUB(7): The inverse function to col2rgb()
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
rgb2col <- function(rgb) {
  rgb <- as.integer(rgb)
  class(rgb) <- "hexmode"
  rgb <- as.character(rgb)
  rgb <- matrix(rgb, nrow=3)
  paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
######################
######################

  
######################
# SUB(8): Convert all colors into format "#rrggbb"
# adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
######################
getColorTable <- function(col) {
  rgb <- col2rgb(col);
  col <- rgb2col(rgb);
  sort(unique(col))
}
######################
######################


######################
# SUB(9): Automtically generate colors from metadata with identical text or values
######################
create_colors <- function(metadata_column, color_mode = "auto"){ # function to     
  my_data.color <- data.frame(metadata_column)
  #ids <- rownames(metadata_column)
  #color_categories <- colnames(metadata_column)
  #for ( i in 1:dim(metadata_matrix)[2] ){
  column_factors <- as.factor(metadata_column[,1])
  column_levels <- levels(as.factor(metadata_column[,1]))
  num_levels <- length(column_levels)
  color_levels <- col.wheel(num_levels)
  levels(column_factors) <- color_levels
  my_data.color[,1]<-as.character(column_factors)
  #}

  
  return(my_data.color)
}
######################
######################


######################
# SUB(10): Automtically generate pch from metadata with identical text or values
######################
create_pch <- function(metadata_table, metadata_column, sample_names, debug){ # function to     
 #return(list("my_pch"=my_pch, "pch_levels"=pch_levels, "pch_levels_text"=pch_levels_text))

  
  #pch_matrix <- data.matrix(metadata_table)
  #if(debug==TRUE){metadata_table.test <<- metadata_table}
  
  plot_pch <- metadata_table[ order(sample_names), metadata_column, drop=FALSE ]
  plot_pch_vector <- as.vector(plot_pch)

  #if(debug==TRUE){plot_pch_vector.test <<- plot_pch_vector}
  
  names(plot_pch_vector) <- sample_names
  pch_labels <- levels(as.factor(plot_pch_vector))
  
  num_labels <- length(pch_labels)

  if( num_labels>25 ){ stop("too many pch levels - must be 25 or less") }

  pch_levels <- 1:num_labels
  names(pch_levels) <- pch_labels
  #if(debug==TRUE){ pch_levels.test <<- pch_levels }

  my_pch <- integer()
  for (i in 1:nrow(plot_pch)){
    my_pch <- c(my_pch, pch_levels[ as.character( plot_pch[i,metadata_column] ) ])
    if(debug==TRUE){ print(paste("my_pch: ", my_pch)) }
  }

  #if(debug==TRUE){ my_pch.test <<- my_pch; pch_levels.test <<- pch_levels}
  
  return(list("my_pch"=my_pch, "pch_levels"=pch_levels))
}
######################
######################

    
## create_colors <- function(metadata_matrix, color_mode = "auto"){ # function to     
##   #my_data.color <- data.frame(metadata_matrix)
##   my_data.color <- vector(length=nrow(metadata_matrix), mode="character")
##   ids <- rownames(metadata_matrix)
##   color_categories <- colnames(metadata_matrix)
##   for ( i in 1:dim(metadata_matrix)[2] ){
##     column_factors <- as.factor(metadata_matrix[,i])
##     column_levels <- levels(as.factor(metadata_matrix[,i]))
##     num_levels <- length(column_levels)
##     color_levels <- col.wheel(num_levels)
##     levels(column_factors) <- color_levels
##     my_data.color[i] <- as.character(column_factors)
##   }
##   return(my_data.color)
## }
######################
######################


## ######################
## # SUB(10): Plot operations for a single metadata column
## ######################

## plot_column <- function(
##                         metadata_matrix,i,
##                         PCoA_in,
##                         ncol.color_matrix,
##                         eigen_values, eigen_vectors, components,
##                         plot_pch,
##                         image_width_in, image_height_in, image_res_dpi,
##                         width_legend, width_figure,
##                         title_cex, legend_cex, figure_cex, bar_cex, label_points
##                         )
## {
##   metadata_column <- metadata_matrix[ ,i,drop=FALSE ] # get column i from the metadata matrix
  
##   suppressWarnings( numericCheck <- as.numeric(metadata_column) ) # check to see if metadata are numeric, and sort accordingly
##   if( is.numeric(numericCheck[1]) ){
##     column_name = colnames(metadata_column)[1]
##     row_names = rownames(metadata_column)
##     metadata_column <- matrix(numericCheck, ncol=1)
##     colnames(metadata_column) <- column_name
##     rownames(metadata_column) <- row_names
##   }

##   metadata_column <- metadata_column[ order(metadata_column),,drop=FALSE ] # order the metadata by value
  
##   color_column <- create_colors(metadata_matrix=metadata_column, color_mode = "auto")
##   #pcoa_colors <<- #color_column[ ,1,drop=FALSE ]
##   ncol.color_matrix <- 1 
##   column_factors <- as.factor(metadata_column) 
##   column_levels <- levels(as.factor(metadata_column))
##   num_levels <- length(column_levels)
##   color_levels <- col.wheel(num_levels)
##   pcoa_colors <- color_column #[,1, drop=FALSE]

##   image_out = paste(PCoA_in,".", colnames(metadata_column), ".pcoa.png", sep="", collapse="") # generate name for plot file
##   figure_main = paste( PCoA_in,".", colnames(metadata_column),".PCoA", sep="", collapse="") # generate title for the plot

##   #rownames(eigen_vectors) <<- noquote(rownames(eigen_vectors))
##   # test2 <- test2[rownames(test1),,drop=FALSE]
##   # eigen_vectors <<- eigen_vectors[ rownames(color_column),,drop=FALSE ] # sort vectors by ordering of colors
##   #test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]


## ###### HERE
  
##   #vector_rownames <<- rownames(eigen_vectors)
##   #vector_colnames <<- colnames(eigen_vectors)
##   #color_column <<- as.matrix(color_column)
##   #rownames(eigen_vectors) <<-

##   #test_2 <- eigen_vectors
##   #rownames(test_2) <- gsub("\"", "", rownames(test_2))

##   rownames(eigen_vectors) <- gsub("\"", "", rownames(eigen_vectors))
  
##   #eigen_vectors[ match(rownames(eigen_vectors), rownames(pcoa_colors)),1,drop=FALSE]
##   #eigen_vectors[ match(rownames(pcoa_colors), rownames(eigen_vectors)),1,drop=FALSE]
##   eigen_vectors <- eigen_vectors[ rownames(pcoa_colors), ]
##   #eigen_vectors[ rownames(pcoa_colors)),]
  
##   create_plot( # generate the  plot
##               PCoA_in,
##               ncol.color_matrix,
##               eigen_values, eigen_vectors, components,
##               column_levels, num_levels, color_levels, pcoa_colors, plot_pch,
##               image_out,figure_main,
##               image_width_in, image_height_in, image_res_dpi,
##               width_legend, width_figure,
##               title_cex, legend_cex, figure_cex, bar_cex, label_points              
##               ) 
## }



  
######################
###### END SUBS ######
######################

subsets = function(X, along, subsets) {
    if (length(subsets) != dim(X)[along])
        stop("subset length must match X dimension on along axis")

    if (any(is.na(subsets)))
        stop("found NA in subsets, exiting")
}

along = function(X, along) {
    if (any(duplicated(dimnames(X)[[along]])))
        stop("duplicated names found along mapping axis, exiting")

    if (is.character(along))
        assign('along', which(names(dim(X)) == along, envir=parent.frame()))
}

x = function(X, to.array, classes=NULL) {
    if (!is.null(classes) && !class(X) %in% classes)
        stop(paste("class of X not in classes:", classes))

    if (to.array)
        assign('X', as.array(X), envir=parent.frame())
}

all = function(X, along, subsets, x.to.array) {
    along(X, along)
    subsets(X, along, subsets)
    x(X, x.to.array)
}
REBOL [
    Title: "Wav-to-mp3"
    Date: 24-Sep-2013/13:41:18+2:00
    Name: none
    Version: none
    File: none
    Home: none
    Author: "A Rebol"
    Owner: none
    Rights: none
    Needs: none
    Tabs: none
    Usage: none
    Purpose: none
    Comment: none
    History: none
    Language: none
    Type: none
    Content: none
    Email: none
]

camelize-wav-name: func[name][
	name: uppercase/part name 1
	parse/all name [
		any [
			  s: "_16bit" e: (s: remove/part s e) :s
			| s: "_16b"   e: (s: remove/part s e) :s
			;| s: ".wav" end e: (s: remove/part s e) :s
			| s: some [#" " | #"_" | #"-"] e: (s: remove/part s e uppercase/part s 1) :s
			|
			1 skip	
		]
	]
	probe name
]


wav-to-mp3: func[source [file! string!] /local wavs cmd][
	wavs: copy []
	if string? source [source: to-rebol-file source]
	if #"/" <> first source [ insert source what-dir ]
	either dir? source [
		foreach file read source [
			append wavs rejoin [source file]
		]
	][
		append wavs source
	]
	foreach wav wavs [
		if parse wav [thru ".wav" end][
			parts: split-path wav
			mp3: join parts/1 camelize-wav-name replace parts/2 ".wav" ".mp3"
			print join "==> " cmd: rejoin [{x:\utils\lame\lame -b 320 -h --silent -t "} to-local-file wav {" "} to-local-file mp3 {"}]
			call/console cmd
		]
	]
]
wmc: does [wav-to-mp3 read clipboard://]REBOL [
    Title: "Pack-assets"
    Date: 7-Mar-2013/17:26:32+1:00
    Version: 0.3.0
    Author: "Oldes"
    Email: oldes.huhuman@gmail.com
	Home: https://github.com/Oldes/rs/blob/master/projects-rswf/pack-assets/fastmem/pack-assets.r
	require: [
		rs-project %stream-io
		rs-project %form-timeline
		rs-project %texture-packer
		rs-project %triangulator ;'shrink
		rs-project %zlib
		rs-project %mp3
	]
	comment: {
		complex example where this script is used is here:
		https://github.com/Oldes/Starling-timeline-example
		warning: the timeline example is not updated so it will be probably not compatible with this version
	}
	
	note-to-myself: {
		Should I try this ATF packing once iOS will be more important for us?
		
		from http://forum.starling-framework.org/topic/i-got-my-game-to-60fps-with-an-iphone4-on-ios7
		<i>
		Here are some snippets from my applescripts

		For PVRTC (Alpha Compressed)
		do script "PVRTexToolCLI -f PVRTC1_4 -potcanvas + -q pvrtcbest -l -m 2 -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -n 0,0 -p " & file_name & ".pvr -o " & file_name & ".atf" in first window

		For DXT (RGBA) Works on desktop and iOS
		do script "PVRTexToolCLI -f r8g8b8a8,UBN,lRGB -potcanvas + -m 1 -q pvrtcbest -dither -l -i " & file_name & ".png -o " & file_name & ".pvr"
		do script "pvr2atf -r " & file_name & ".pvr -c p -n 0,0 -o " & file_name & ".atf" in first window
		</i>
		
		or maybe from:
		http://forum.starling-framework.org/topic/atf-observations-ymmv
		Since this post has been useful to some, I'll add another tidbit. The best quality PVR compression I've found for iOS is attained using the PVRTexTool utility from PowerVR. I think you have to sign up for their developer program to download the PowerVR GraphicsSDK, but it's free, though maybe you can find the tool itself elsewhere. Anyway, this commandline gives better PVR compression quality than Adobe's tool*:

		PVRTexToolCL -i atlas.png -o atlas.pvr -m -l -f PVRTC1_4 -q pvrtcbest -mfilter cubic
		This creates a .pvr file, and you then use Adobe's pvr2atf to create the atf file:

		pvr2atf -p atlas.pvr -o atlas.atf
		* - this is interesting, since it seems that Adobe's tool (png2atf) uses PVRTexTool libraries under the hood (same stdout while encoding). PVRTexTool also has more options for quality and encoding - play around with them in the GUI, but the above setting represents the best quality (albeit fairly slow to encode) for iOS compatibility.
	}
]

with: func [obj body][do bind body obj]

ctx-pack-assets: context [
	dirBinUtils:   %./Utils/
	dirAssetsRoot: %./Assets/
	dirPacks:      join dirAssetsRoot %Packs/

	pngQuantExe:   dirBinUtils/pngquant
	if system/version/4 = 3 [append pngQuantExe %.exe]
	
	;charsets:
		chNotSpace: complement charset "^/^- "
		chDigits: charset "0123456789" 
	
	;Asset's commands:
		cmdUseLevel:                 1
		cmdTextureData:              2
		cmdPackedAssets:              102
		cmdUseTexture:                103
		cmdDefineImage:              3
		cmdStartMovie:               4
		cmdEndMovie:                 5
		cmdAddMovieTexture:          6
		cmdAddMovieTextureWithFrame: 7
		
		cmdLoadSWF:                  8

		cmdTimelineData:             10
		cmdTimelineObject:           11
		cmdTimelineShape:            12
		cmdTimelineShape2:           13
		
		cmdTimelineData2:            40
		cmdShapeBuffers:             41
		
		cmdDefineSound:              15
		cmdDefineSoundOgg:           16
		cmdDefineSoundLoop:          17
		cmdDefineSoundRAW:			 18

		cmdWalkData:                 20
		cmdPathData:                 25

		cmdImageNames:               30
		cmdStringPool:               31
	;Shape's commands:
		cmdLineStyle:                1
		cmdMoveTo:                   2
		cmdCurve:                    3
		cmdLine:                     4
	;ControlTag assets:
		cmdPlace:                    1
		cmdPlaceNamed:               10
		cmdMove:                     2
		cmdRemove:                   3
		cmdLabel:                    4
		cmdReplace:                  5
		cmdSound:                    6
		cmdLabelCallback:            7
		cmdSoundVBR:                 8
		cmdSoundVBR2:                9
		cmdRemoveAnd:                11
		cmdFPS:                      30
		cmdFPSRange:                 31
		cmdSlowFPS:                  32
		cmdStop:                     33
		cmdRelease:                  34
		cmdTouchable:                35
		cmdHide:                     36
		cmdShow:                     37
		cmdShowFrame:                128
		

	usedTimelineImages: none
	usedTimelineSounds: none
	level-images: copy []  ;Storing list of all defined level images
	pack-files:   copy []
	out: make stream-io [] ;Holds output stream
	outTextures: make stream-io [] ;Holds textures stream - textures are separated because they may be reloaded when a context is lost
	strings: copy []
	sound-groups: copy []
	noATFfiles: [] ;Add names of packs where just PNG must be used (no ATF)
	;Charsets:
	chDigit: charset "0123456789"
	
	offsetSoundId:
	offsetImageId:
	offsetShapeId:
	offsetObjectId:
	offsetStringId: 0
	maxSoundId:
	maxImageId:
	maxShapeId:
	maxObjectId: 0
	
	currentLevel: none;
	;Functions:


	write-string: func[
		"Writes string using UI16 pointer (zero based)"
		string [string!]
		/local f id
	][
		id: offsetStringId - 1 + either f: find strings string [
			index? f
		][
			append strings string
			length? strings
		]
		either id < 256 [
			out/writeUI8 id
		][
			print "*** StringPool max size (255) reached! So 1 byte per ID will not be enough."
			halt
		]
	]

	pack-bitmaps: func[
		level  [any-string!] "Lavel's name"
		name   [any-string!] "Per level texture sheet's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 2048x2048
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/" name]
		packFile: join name %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/:packFile
		][
			append result-files dirPacks/:name
			n: 1
			while [exists? rejoin [dirPacks name %_ n %.rpack]][
				append result-files rejoin [dirPacks name %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir dirPacks
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	
	pack-bitmaps-4096: func[
		level  [any-string!] "Lavel's name"
		/local
			srcDir packFile
			result-files
	][
		ctx-texture-packer/max-size: 4096x4096
		srcDir: rejoin [dirAssetsRoot %Bitmaps\ level #"/"]
		packFile: join level %.rpack
		result-files: copy []
		
		either any [
			exists? dirPacks/4096/:packFile
		][
			append result-files dirPacks/4096/:level
			n: 1
			while [exists? rejoin [dirPacks %4096/ level %_ n %.rpack]][
				append result-files rejoin [dirPacks %4096/ level %_ n]
				n: n + 1
			]
		][
			if error? set/any 'error try [
				result-files: texture-pack srcDir join dirPacks %4096/
			][
				print "Packing failed!"
				do error
			]
		]
		result-files
	]
	write-rpack-assets: func[
		rpack-file
		/local
			indx file partId index
			regions sequences
	][
		indx: index? out/outBuffer 
		regions: copy []
		sequences: copy []
		foreach [xy size file] load rpack-file [
			parse file [
				thru "Bitmaps/" [
					copy partId to #"_" 1 skip copy index to #"." to end (
						sequence: select sequences partId
						if none? sequence  [
							append sequences partId
							append/only sequences sequence: copy []
						]
						repend sequence [to integer! index xy size]
					)
					|
					copy partId to ".png" to end (
						repend regions [partId xy size]
					)
				]
			]
		]
		foreach [partId xy size] regions [
			out/writeUI8 cmdDefineImage
			out/writeUI16 offsetImageId - 1 + index? find level-images partId
			out/writeUI16 xy/1
			out/writeUI16 xy/2
			out/writeUI16 size/1
			out/writeUI16 size/2
		]
		unless empty? sequences [
			foreach [id sequence] probe sequences [
				print ["Sequence" mold id "with length" ((length? sequence) / 3)] 
				sort/skip sequence 3
				out/writeUI8 cmdStartMovie
				out/writeUTF id
				foreach [index xy size] sequence [
					out/writeUI8 cmdAddMovieTexture
					out/writeUI16 xy/1
					out/writeUI16 xy/2
					out/writeUI16 size/1
					out/writeUI16 size/2
				]
				out/writeUI8 cmdEndMovie
				out/writeUI16 0 ;no labels
			]
		]
		
		out/writeUI8 0 ;end of block
		;set output position in front of written asssets specification;
		out/outBuffer: at head out/outBuffer indx 
		out/writeUI32  length? out/outBuffer
		out/outBuffer: tail out/outBuffer
	]

	not-excluded-atf?: func[file][
		none? find noATFfiles last parse file "/"
	]
	
	get-atf-file: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
	][
		rejoin either all [
			atf-type
			not-excluded-atf? file
		][
			[file #"." atf-type]
		][
			[file #"." %png]
		]
	]

	has-atf-version: func[
		atf-type "Required ATF file extension (%dxt or %etc)"
		file     [any-string!] "Name of the bitmap file without extension"
		/local
			origFile
			imageFile
			localDirBinUtils
		][
		print ["=== has-atf-version ===" mold file atf-type]
		if not any [
			exists? origFile: join file %-fs8.png
			exists? origFile: join file %.png
		][
			ask reform ["Cannot found source file for ATF:" mold file]
		]
		all [
			atf-type
			not-excluded-atf? file
			any [
				all [
					
					exists? probe imageFile: rejoin [file #"." atf-type]
					(modified? imageFile) > (modified? origFile)
					;false ;;<-- uncomment to force re-conversion
				]
				(
					localDirBinUtils: join to-local-file dirBinUtils #"\"
					;delete imageFile
					switch/default atf-type [
						%dxt [
							{
							call/console probe rejoin [
								localDirBinUtils {PVRTexTool.exe -m -yflip0 -f DXT5 -dds}
									{ -i } to-local-file origFile
									{ -o } to-local-file file {.dds}
							]
							call/console probe rejoin [
								to-local-file dirBinUtils {\dds2atf.exe -4 -q 0}
									{ -i } to-local-file file {.dds}
									{ -o } to-local-file imageFile
							]}
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c d -4}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%etc [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c e -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%pvr [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -c p -4 -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
						%rgba [
							call/console probe rejoin [
								localDirBinUtils {png2atf.exe -4 -r -q 0}
									{ -i } to-local-file origFile
									{ -o } to-local-file imageFile
							]
							true
						]
					][ false ]
				)
			]
		]
	]
	
	idOffsetData: [
		%Univerzal         [0       0      0      0     10]
		%UniverzalPrasivka [100     100    100    150   15]
		%PlanetaDomovska   [600     1100   100    200   30]
		%PlanetaZluta      [600     1100   100    150   30]
		
		;%Konstrukter   [11      34     0      0     ]
		;%Prasivka      [195     1805   2      3     ]
		;%Domek         [632     4514   997    3     ]
		;%Mustek        [1364    7509   997    48    ]
		;%Houbar        [1464    8025   2160   48    ]
	]
	
	get-imageIdOffset: func[level [any-string!] /local tmp][
		tmp: select idOffsetData to-file level
		either tmp [tmp/2][1100]
	]
	set-timelineIdOffset: func[level [any-string!]][
		;if level <> %Univerzal [level: none]
		set [offsetObjectId offsetImageId offsetShapeId offsetSoundId offsetStringId] any[
			select idOffsetData to-file level
			[600 1100 100 210 30]
		]
	]
	set 'make-packs func [
		level [any-string!]   "Level's ID"
		/atf atf-type         "ATF extension which could be used for bitmap compression (dxt or etc)"
		/local
			sourceDir ;
			sourceSWF ;used for TimelineSWF file source
			sourceTXT ;used for parsed TimelineSWF source (cache)
			bin       ;used to store temporaly binary data
			indx      ;used to story temp output buffer position
			origImageFile
			imageFile
			name
			xml   ;for parsing starling's spritesheet animations
			x y width height frameX frameY frameWidth frameHeight ;variables used in starling's data xml
			files ;holds temporary data for farther processing
	][
		currentLevel: to string! level ;uppercase/part lowercase to string! level 1
		;-- Check if main directories are specifield...
		either dirAssetsRoot [
			dirAssetsRoot: to-file dirAssetsRoot
			if #"/" <> pick dirAssetsRoot 1 [insert dirAssetsRoot what-dir]
		][	make error! "Unspecified dirAssetsRoot" ]
		either dirBinUtils [
			dirBinUtils: to-file dirBinUtils
			if #"/" <> pick dirBinUtils 1 [insert dirBinUtils what-dir]
		][	make error! "Unspecified dirBinUtils" ]
		
		;-- Validate atf-type if there is any...
		if all [atf-type none? find [%dxt %etc %rgba %pvr] atf-type][ atf-type: none ]
		
		;-- Init ouput buffer...
		out/clearBuffers
		outTextures/clearBuffers
		clear pack-files
		clear level-images
		clear sound-groups
		clear strings
		
		set-timelineIdOffset level
		maxSoundId:
		maxImageId:
		maxShapeId:
		maxObjectId: 0

		;== BITMAPS:
		sourceDir: dirize rejoin [dirAssetsRoot %Bitmaps/ level]
		if exists? sourceDir [
			use-4096?: off
			either use-4096? [
				append pack-files  pack-bitmaps-4096 level
			][
				foreach dir read sourceDir [
					if all [
						#"/" = last dir   ;Search for bitmaps directory (content of each dir will have it's own texture atlas)
						#"_" <> first dir ;Do not use folder with underscore prefix
					][
						remove back tail dir
						append pack-files pack-bitmaps level dir
					]
				]
			]
			foreach pack pack-files [
				foreach [ofs size file] load join pack %.rpack [
					parse/all file [
						thru %Bitmaps/ copy name to %.png (
							append level-images name
						)
					]
				]
			]
			maxImageId: length? level-images
			new-line/all level-images true
			;probe level-images
			save rejoin [dirAssetsRoot %Bitmaps/ level %/images.txt] level-images
			
			foreach packName pack-files [
				probe origImageFile: rejoin [packName %.png]
				;-- Generate ATF versions if required...
				any [
					has-atf-version atf-type packName
					all [
						exists? imageFile: rejoin [packName %-fs8.png]
						any [
							(modified? imageFile) > (modified? origImageFile)
							(
								delete imageFile
								call/console probe rejoin [
									to-local-file pngQuantExe " "
									to-local-file join what-dir origImageFile
								]
								true
							)
						]
					]
					exists? imageFile: origImageFile
				]
				;-- Write bitmaps data into result stream
				bin: read/binary get-atf-file atf-type packName
				
				outTextures/writeUI8 cmdTextureData
				outTextures/writeUTF to-string find/tail packName dirPacks

				out/writeUI8 cmdPackedAssets
				out/writeUTF to-string find/tail packName dirPacks
				write-rpack-assets join packName %.rpack
				
				either all [
					atf-type
					not-excluded-atf? packName
				][
					outTextures/writeUI8   1 ;is compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				][
					outTextures/writeUI8   0 ;not compressed
					outTextures/writeUI32  length? bin
					outTextures/writeBytes bin
				]
			]
			
			if exists? tmp: rejoin [dirAssetsRoot %Bitmaps/ level %/images-named.txt][
				n: 0
				indx: index? out/outBuffer 
				foreach image load tmp [
					if tmp: find level-images image [
						out/writeUTF  image
						out/writeUI16 offsetImageId - 1 + index? tmp
						n: n + 1
					]
				]
				if n > 0 [
					out/outBuffer: at head out/outBuffer indx
					out/writeUI8   cmdImageNames
					out/writeUI16  n
					out/outBuffer: tail out/outBuffer
				]
			]
		]
		
		;;TIMELINE - form timeline before sound because it exports MP3 files
		case [
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %_anims.txt]
			]
			exists? sourceSWF: rejoin [dirAssetsRoot %TimelineSWFs\ level %.swf][
				sourceTXT: rejoin [dirAssetsRoot %TimelineSWFs\ level %.txt]
			]
		]
		if exists? sourceSWF [
			if any [
				;true ;;<-- just to force recreation every time
				not exists? sourceTXT
				(modified? sourceTXT) < (modified? sourceSWF)
				;(modified? join rs/get-project-dir 'form-timeline %form-timeline.r) > (modified? sourceTXT)
			][
				form-timeline sourceSWF
			]
		]
		
		;;SOUNDS:
		soundsDir: dirize rejoin [dirAssetsRoot %Sounds\ level]
		level-sounds: copy []
		if exists? soundsDir [
			n: 0
			soundsToImport: read soundsDir
			forall soundsToImport [
				probe file: soundsToImport/1
				either #"/" = last file [
					foreach subFile read soundsDir/:file [
						append soundsToImport rejoin [file subFile]
					]
				][
					parse file [
						copy name to ".mp3" 4 skip end (
							print ["Sound: " file]
							append level-sounds rejoin [to-string level %"/" name]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSound
							out/writeUTF   name
							out/writeUI16  offsetSoundId + n
							out/writeUI32  length? bin
							out/writeBytes bin
							n: n + 1
						)
						|
						copy name to ".loop" 5 skip end (
							bin: read/binary soundsDir/:file
							mp3/parse/file soundsDir/:file
							out/writeUI8   cmdDefineSoundLoop
							out/writeUTF   name
							out/writeUI32  mp3/num_frames
							out/writeUI32  length? bin
							out/writeBytes bin
						)
						|
						copy name to ".snd" 4 skip end (
							print ["Sound RAW: " file]
							bin: read/binary soundsDir/:file
							out/writeUI8   cmdDefineSoundRAW
							out/writeUTF   name
							out/writeUI32  b: length? bin
								;-- test for same length in level Mloci
								;	if (b / 5292) <> round(b / 5292) [
								;		ask "blby snd"
								;	]
								;--
							;while [not tail? bin][
							;	out/writeBytes head reverse copy/part bin 2
							;	bin: skip bin 2
							;]
							out/writeBytes bin
						)
						;|
						;copy name to ".ogg" 4 skip end (
						;	print ["Sound: " file]
						;	append level-sounds rejoin [to-string level %"/" name]
						;	bin: read/binary soundsDir/:file
						;	out/writeUI8   cmdDefineSoundOgg
						;	out/writeUTF   name
						;	out/writeUI16  offsetSoundId + n
						;	out/writeUI32  length? bin
						;	out/writeBytes bin
						;	n: n + 1
						;)
					]
				]
			]
			maxSoundId: n
			new-line/all level-sounds true
			save soundsDir/sounds.txt level-sounds
		]
		
		
		;;STARLING Sheets:
		sourceDir: dirize rejoin [dirAssetsRoot %Starling\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".xml" 4 skip end]
					any [
						has-atf-version atf-type join sourceDir name
						exists? imageFile: rejoin [sourceDir name %-fs8.png]
						exists? imageFile: rejoin [sourceDir name %.png]
					]
				][
					print ["using:" imageFile]
					outTextures/writeUI8 cmdTextureData
					outTextures/writeUTF name
					
					out/writeUI8 cmdPackedAssets
					out/writeUTF name
					;store output stream position
					indx: index? out/outBuffer 
					
					out/writeUI8 cmdStartMovie
					out/writeUTF name
					
					xml: read/binary sourceDir/:file
					replace/all xml "^@" "" ;very dirty conversion from UTF16 codepoint - NOTE: make sure to use just Latin1 chars in names!
					use [name x y width height frameX frameY frameWidth frameHeight][
						parse/all xml [
							any [
								thru {<SubTexture name="} copy name to {"}
								thru {x="} copy x to {"}
								thru {y="} copy y to {"}
								thru {width="} copy width to {"}
								thru {height="} copy height to {"}
								thru {frameX="} copy frameX to {"}
								thru {frameY="} copy frameY to {"}
								thru {frameWidth="} copy frameWidth to {"}
								thru {frameHeight="} copy frameHeight to {"}
								(
									out/writeUI8  cmdAddMovieTextureWithFrame
									out/writeUI16 to-integer x
									out/writeUI16 to-integer y
									out/writeUI16 to-integer width
									out/writeUI16 to-integer height
									out/writeUI32 to-integer frameX
									out/writeUI32 to-integer frameY
									out/writeUI16 to-integer frameWidth
									out/writeUI16 to-integer frameHeight
								)
							]
						]
					]
					out/writeUI8 cmdEndMovie

					either all [
						exists? probe sourceLabels: rejoin [sourceDir name %.labels]
						not empty? data: load sourceLabels
					][
						out/writeUI16 (length? data) / 2
						foreach [number label] data [
							print [number tab label]
							out/writeUI16 number
							out/writeUTF  label
						]
					][
						out/writeUI16 0 ;no labels
					]
					
					out/writeUI8 0 ;end of block
					
					;set output position in front of written asssets specification;
					out/outBuffer: at head out/outBuffer indx 
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					
					if all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						imageFile: get-atf-file atf-type join sourceDir name
					]
					bin: read/binary probe imageFile
					
					;out/outBuffer: at head out/outBuffer indx 
					either all [
						atf-type
						not-excluded-atf? join sourceDir name
					][
						;storing ATF in front of asset specifications
						;set output position in front of written asssets specification;
						outTextures/writeUI8   1
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin
						
						;out/outBuffer: tail out/outBuffer
						
					][
						outTextures/writeUI8   0
						;storing PNG after assets - because we must use loader to get bitmap from bytes
						;outTextures/outBuffer: tail outTextures/outBuffer
						outTextures/writeUI32  length? bin
						outTextures/writeBytes bin

					]
					;out/outBuffer: tail out/outBuffer ;sets output back after specifications
					
				];END OF CLASIC STARLING
			]
		]
		
		;;SWFs:
		sourceDir: dirize rejoin [dirAssetsRoot %SWFs\ level]
		if exists? sourceDir [
			foreach file read sourceDir [
				if all [
					parse file [copy name to ".swf" 4 skip end]
				][
					bin: read/binary probe rejoin [sourceDir file]
					out/writeUI8   cmdLoadSWF
					out/writeUTF   name
					out/writeUI32  length? bin
					out/writeBytes bin
				]
			]
		]
		
		;;TIMELINE OBJECTS DEFINITIONS (continue)
		if exists? sourceSWF [
			indx: index? out/outBuffer
			parse-timeline sourceTXT
			print ["Timeline bytes:" (index? out/outBuffer) - indx]
		]
		
		;;WALK DATA:
		sourceTXT: rejoin [dirAssetsRoot %WalkData\ level %_chuze.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scale
				num = length? data/rotate
			][
				print ["Walk DATA found.. frames:" num]
				out/writeUI8   cmdWalkData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scale  [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				;Reflections:
				either all [
					find first data 'rPosX
					0 < num: length? data/rPosX
				][
					out/writeUI16  num
					foreach value data/rPosX   [ out/writeFloat value ]
					foreach value data/rPosY   [ out/writeFloat value ]
					foreach value data/rRotate [ out/writeFloat value ]
				][
					out/writeUI16  0
				]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsLeft) / 2
				foreach [num name] data/labelsLeft [
					out/writeUI16 num
					out/writeUTF  name
				]
				
				out/writeUI16 (length? data/labelsRight) / 2
				foreach [num name] data/labelsRight [
					out/writeUI16 num
					out/writeUTF  name
				]
					
				either empty? data/sensors [
					out/writeUI8 0 ;no nodes
					out/writeUI8 0 ;no arcs
				][
					nodes: copy []
					arcs:  copy []
					foreach [name pos] data/sensors [
						parse/all to-string name [
							#"P" copy fromNode some chDigit (
								repend nodes [
									fromNode: to-integer fromNode
									pos
								]
							) any [
								#"_"
								copy arcType [#"j" | #"f" | #"b" | #"w" | #"n" | #"c" | #"v" | #"s" | #"r" | #"k" | none]
								copy toNode some chDigit
								(
									toNode: to-integer toNode
									if none? arcType [arcType: #"w"]
									;print [arcType fromNode toNode]
									repend arcs [arcType fromNode toNode]
								)
							]
						]
					]
					;nodes must be numbers from 0 to n
					probe new-line/skip sort/skip nodes 2 true 2
					if nodes/1 <> 0 [
						make error! "INVALID WALK NODE - Nodes must start with id 0!"
					]
					for n 3 length? nodes 2 [
						if 1 <> (nodes/(n) - nodes/(n - 2)) [
							print "!!! INVALID WALK NODEs (Nodes must be numbers from 0 to n with increment 1)!"
							print ["Found invalid sequence neer:" n mold node/(n)]
							halt
						]
					]
					out/writeUI8 (length? nodes) / 2
					foreach [node pos] nodes [
						out/writeUI16 pos/x
						out/writeUI16 pos/y
					]
					;probe new-line/skip arcs true 3
					out/writeUI8 (length? arcs) / 3
					foreach [arcType fromNode toNode] arcs [
						print rejoin [tab arcType #" " fromNode "-" toNode]
						out/writeByte arcType
						out/writeUI8  fromNode
						out/writeUI8  toNode
					]
				]
			]
		]
		
		;;PATH DATA:
		sourceTXT: rejoin [dirAssetsRoot %Paths\ level %_paths.txt]
		if exists? sourceTXT [
			data: context load sourceTXT
			num: length? data/posX
			tmp: first data
			if all [
				num = length? data/posY
				num = length? data/scaleX
				num = length? data/scaleY
				num = length? data/rotate
			][
				print ["Path DATA found.. frames:" num]
				out/writeUI8   cmdPathData
				out/writeUI16  num
				foreach value data/posX   [ out/writeFloat value ]
				foreach value data/posY   [ out/writeFloat value ]
				foreach value data/scaleX [ out/writeFloat value ]
				foreach value data/scaleY [ out/writeFloat value ]
				foreach value data/rotate [ out/writeFloat value ]
				
				out/writeUI16 (length? data/labelsAt) / 2
				foreach [num name] data/labelsAt [
					out/writeUI16 num
					out/writeUTF  name
				]
			]
		]

		;;RAW data:
		RAWDir: dirize rejoin [dirAssetsRoot %Raw\ level]
		if exists? RAWDir [
			n: 0
			filesToImport: read RAWDir
			forall filesToImport [
				probe file: filesToImport/1
				parse file [
					copy name to ".bin" 4 skip end (
						print ["RAW:" file]
						bin: read/binary RAWDir/:file
						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						out/writeUI32  b: length? bin
						out/writeBytes bin
					)
					|
					copy name to ".path" 5 skip end (
						print ["RAW Path:" file]
						data: make object! load RAWDir/:file

						out/writeUI8   cmdDefineSoundRAW
						out/writeUTF   name
						tmp: out/outBuffer
						if (length? data/x) <> (length? data/y) [
							print "Number of X positions is not same as Y!!"
							halt
						]
						;path data..
						out/writeUI16 length? data/x
						foreach x data/x [out/writeFloat x]
						foreach y data/y [out/writeFloat y]
						out/writeUI16 length? data/labels
						foreach [num label] data/labels [
							out/writeUI16 num
							out/writeUTF label
						]
						;..path data end
						out/outBuffer: tmp
						out/writeUI32 length? out/outBuffer ;size of path data in the raw block
						out/outBuffer: tail out/outBuffer
					)

				]
			]
		]
		
		outTextures/writeUI8 0 ;end
		outTextures/outBuffer: head outTextures/outBuffer
		outTextures/writeBytes as-binary "LVL"
		outTextures/writeUI8 cmdUseLevel
		outTextures/writeUTF level 
		
		print ["Writing textures file..."]
		write/binary join %./bin/ rejoin [%Data/ target #"/" level %.lvl] head outTextures/outBuffer
		
		out/writeUI8 0 ;end
		
		out/outBuffer: head out/outBuffer
		out/writeBytes as-binary "LVL"
		out/writeUI8 cmdUseLevel
		out/writeUTF level 

		out/writeUI8  cmdStringPool
		out/writeUI16 length? probe strings
		n: 0
		foreach string strings [
			out/writeUI16 offsetStringId + n
			out/writeUTF string
			n: n + 1
		]
		
		print ["Writing file..."]
		write/binary join %./bin/ rejoin [%Data/ level %.lvl] head out/outBuffer

		reduce [
			maxObjectId
			maxImageId
			maxShapeId
			maxSoundId
			length? strings
		]
	]
	
	parse-timeline: func[
		file [file!]   "Formed timeline specification"
		/local
			type id data name ;parse variables
			indx ;used to count total bytes per sprite/movie
			startIndx
			names ;used to store names-to-id data
	][
		print ["====== parse-timeline " file]
		ctx-triangulator/init
		names: copy []
		out/writeUI8  cmdTimelineData2
		startIndx: index? out/outBuffer
		parse/all load file [
			any [
				set type ['Movie | 'Sprite] set id integer! set data block! (
					out/writeUI8  cmdTimelineObject
					out/writeUI16 id + offsetObjectId
					indx: index? out/outBuffer
					parse-controlTags data
					out/writeUI8   0 ;end of timeline;
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32  length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxObjectId < id [maxObjectId: id]
				)
				|
				'Name set id integer! set name string! (
					print [id mold name length? head out/outBuffer]
					repend names [name id + offsetObjectId]
				)
				|
				'Shape set id integer! set data block! (
					{
					out/writeUI8  cmdTimelineShape
					out/writeUI16 id + offsetShapeId
					indx: index? out/outBuffer
					parse-ShapeDefinition data
					out/outBuffer: at head out/outBuffer indx
					out/writeUI32 length? out/outBuffer
					out/outBuffer: tail out/outBuffer
					if maxShapeId < id [maxShapeId: id]
					}
					out/writeUI8  cmdTimelineShape2
					out/writeUI16 id + offsetShapeId
					data: triangulate-shape data ;main result is stored in shared vertex and index buffers inside triangulator
					out/writeUI8  data/1 ;buffer number
					out/writeUI32 data/2 ;firstIndex
					out/writeUI32 data/3 ;numTriangles
					
					if maxShapeId < id [maxShapeId: id]
				)
				|
				'Images set usedTimelineImages block!
				|
				'Sounds set usedTimelineSounds block!
			]
		]
		
		outTextures/writeUI8 cmdShapeBuffers
		outTextures/writeBytes ctx-triangulator/get-buffers-binary
		
		
		out/outBuffer: at head out/outBuffer startIndx
		out/writeUI32  probe length? out/outBuffer
		out/outBuffer: tail out/outBuffer
		out/writeUI8   0
		
		out/writeUI32  0.5 * length? names 
		foreach [name id] names [
			out/writeUI16 id
			out/writeUTF  name
			;print ["Named TO:" id name]
		]
		
		out/writeUI32  length? sound-groups 
		id: 0
		foreach name sound-groups [
			id: id + 1
			out/writeUI8  id
			out/writeUTF  name
			print ["Sound Group:" id name]
		]
	]

	write-transform: func[
		transform color flags
		/local
			colorMult colorAdd hasColorMult removeTint alpha useColorMatrix
	][
		if transform/3 [flags: flags or 8]
		if transform/1 [flags: flags or 16]
		if transform/2 [flags: flags or 32]
		if color [
			set [colorMult colorAdd] color
			either any [
				block? colorAdd
				all [
					block? colorMult
					any [
						colorMult/1 <> 256
						colorMult/2 <> 256
						colorMult/3 <> 256
					]
				]
			][
				flags: flags or 64
				useColorMatrix: true
				print ["ColorMatrix.." mold color mold transform]
			][
				if block? colorMult [
					flags: flags or 128
					alpha: colorMult/4
				]
			]
			comment {
			either block? colorMult: color/1 [
				
				flags: flags or 64
				alpha: colorMult/4
				if any [
					colorMult/1 <> 256
					colorMult/2 <> 256
					colorMult/3 <> 256
				][
					flags: flags or 128
					hasColorMult: true
				]
			][
				flags: flags or 128
				colorMult: [255 255 255]
				hasColorMult: true
			]}
		]
		out/writeUI8  flags
		;probe transform
		if transform/3 [
			out/writeFloat transform/3/1 / 20 ;x
			out/writeFloat transform/3/2 / 20 ;y
		]
		if transform/1 [
			out/writeFloat transform/1/1 ;scaleX
			out/writeFloat transform/1/2 ;scaleY
		]
		if transform/2 [
			out/writeFloat transform/2/1 ;skewX
			out/writeFloat transform/2/2 ;skewY
		]
		either useColorMatrix [
			out/writeFloat colorMult/1 / 256
			out/writeFloat colorMult/2 / 256
			out/writeFloat colorMult/3 / 256
			out/writeFloat colorMult/4 / 256
			if none? colorAdd [colorAdd: [0 0 0 0]]
			out/writeFloat colorAdd/1 / 256
			out/writeFloat colorAdd/2 / 256
			out/writeFloat colorAdd/3 / 256
			out/writeFloat colorAdd/4 / 256
			{if hasColorMult [
				out/writeUI8 min 255 colorMult/1
				out/writeUI8 min 255 colorMult/2
				out/writeUI8 min 255 colorMult/3
			]}
		][
			if alpha [
				out/writeUI8 min 255 alpha
			]
		]
	]

	parse-ShapeDefinition: func[
		data
		/local
			thickness color
			points x y
			err
	][
		parse/all data [any[
			'lineStyle set thickness integer! set color tuple! (
				out/writeUI8   cmdLineStyle
				out/writeUI16  thickness
				out/writeBytes to-binary color
			)
			|
			'moveTo set x integer! set y integer! (
				out/writeUI8  cmdMoveTo
				out/writeUI16 x
				out/writeUI16 y
			)
			|
			'curve set points block! (
				out/writeUI8   cmdCurve
				out/writeUI16 (length? points) / 4 ;count
				
				foreach [cx cy ax ay] points [
					;print ["curve" cx cy ax ay]
					out/writeUI16 cx
					out/writeUI16 cy
					out/writeUI16 ax
					out/writeUI16 ay
				]
			)
			|
			'line set points block! (
				out/writeUI8  cmdLine
				out/writeUI16 (length? points) / 2 ;count
				foreach [x y] points [
					out/writeUI16 x
					out/writeUI16 y
				]
			)
			| copy err 1 skip (
				ask reform ["Invalid shape definition:" mold err]
			)
		]]
		out/writeUI8 0 ;end
	]

	parse-controlTags: func[
		data
		/local
			id depth transform type frames name colorTransform value value2 ;parse variables
			flags soundData pos imageName externalLevel soundGroup temp
	][
		place-command: does [
			;print ["Place: " id]
			switch/default type [
				image  [
					imageName: usedTimelineImages/:id
					if error? try [
						id: -1 + offsetImageId + index? find level-images imageName
					][
						if error? try [
							parse imageName [copy externalLevel to #"/" to end]
							;TODO: optimize this part!!
							id: index? find load rejoin [dirAssetsRoot %Bitmaps/ externalLevel %/images.txt] imageName
							id: id - 1 + get-imageIdOffset externalLevel
							;print ["External image:" imageName]
						][
							ask ["!!! Unknown timeline image!" id imageName]
							;probe level-images
							id: 0
						]

					]
					out/writeUI16 id 
				]
				object [ out/writeUI16 id + offsetObjectId ]
				shape  [ out/writeUI16 id + offsetShapeId ]
			][
				make error! reform ["!!! UNKNOWN TYPE:" type]
			]
			out/writeUI16 depth - 1
			flags: select [image 0 object 1 shape 2] type
			if none? flags [
				print ["Unknown place object type:" type]
				probe copy/part mold pos 200
				halt
			]
			write-transform transform color flags
		]

		parse/all data [
			'TotalFrames set frames integer! (
				out/writeUI16 frames
			)
			opt ['HasLabels (
				out/writeUI8 cmdLabelCallback
			)]
			any [
				pos:
				'Move set depth integer! set transform block! set color [block! | none] (
					;print ["Move: " depth]
					out/writeUI8  cmdMove
					out/writeUI16 depth - 1
					flags: 0
					write-transform transform color flags
				)
				|
				'ShowFrame (
					out/writeUI8  cmdShowFrame
				)
				|
				'Place 
					set type word!
					set id integer!
					set depth integer!
					set transform block!
					set color [block! | none]
					set name [string! | none]
				(
					either name [
						out/writeUI8 cmdPlaceNamed
						write-string name
						;ask ["NAMED.." name]
					][
						out/writeUI8 cmdPlace
					]
					place-command
				)
				|
				'Replace set type word! set id integer! set depth integer! set transform block! set color [block! | none] (
					; ["Replace: " id]
					out/writeUI8  cmdReplace
					switch/default type [
						image  [ out/writeUI16 id + offsetImageId ]
						object [ out/writeUI16 id + offsetObjectId ]
						shape  [ out/writeUI16 id + offsetShapeId ]
					][
						make error! reform ["!!! UNKNOWN TYPE:" type]
					]
					out/writeUI16 depth - 1
					flags: select [image 0 object 1 shape 2] type
					write-transform transform color flags
				)
				|
				'Remove set depth integer! temp: (
					;I'm testing there if next command is 'Place' and into same depth, if so, I do cmdReplace instead so I avoid 'splice' call in runtime
					either all [
						temp/1 = 'Place
						depth = temp/4
						not string? temp/7 ;temp/7 is place object's name - I don't use replace command when there is name
					][ 
						parse/all temp [
							'Place 
							set type word!
							set id integer!
							set depth integer!
							set transform block!
							set color [block! | none]
							set name [string! | none]
							temp:
							to end
						]
						out/writeUI8  cmdReplace
						place-command
					][
						out/writeUI8  cmdRemove
						out/writeUI16 depth - 1
					]
				) :temp
				|
				'Label set name string! (
					unless parse name [
						"_fps" copy value some chDigit end (
							out/writeUI8 cmdFPS
							out/writeUI8 to-integer value
						) |
						"_fps" copy value some chDigit "-" copy value2 some chDigit end (
							out/writeUI8 cmdFPSRange
							out/writeUI8 to-integer value
							out/writeUI8 to-integer value2
						)
						|
						"_stop" end (
							out/writeUI8 cmdStop
						)
						|
						"_hide" end (
							out/writeUI8 cmdHide
						)
						|
						"_show" end (
							out/writeUI8 cmdShow
						)
						|
						"_release" end (
							out/writeUI8 cmdRelease
						)
						|
						"_slowFps" copy value some chDigit end (
							;will set FPS to: 1 + Math.random()*value
							out/writeUI8 cmdSlowFPS
							out/writeUI8 to-integer value
						)
						|
						"_touchable" end (
							out/writeUI8 cmdTouchable
						)
						|
						"_snd" opt ["_"] copy name to #"_" 1 skip copy value some chDigit end (
							out/writeUI8 cmdSoundVBR
							write-string rejoin [currentLevel #"/" name]
							out/writeUI8 to-integer value
							either parse name [copy group to #"/" to end][
								out/writeUI8 1
								write-string group
							][
								out/writeUI8 0
							]
						)
					][
						out/writeUI8 cmdlabel
						write-string name
					]
				)
				|
				'Sound set id integer! set soundData block! (
					name: to string! usedTimelineSounds/:id
					if error? try [
						id: -1 + index? find level-sounds name
					][
						print ["!!! Unknown timeline sound!" id name]
						halt
					]
					out/writeUI8  cmdSound
					out/writeUI16 id + offsetSoundId
					out/writeUI16 soundData/1 ;repeat
					either parse name [thru #"/" copy id to #"/" to end][
						either tmp: find sound-groups id [
							out/writeUI8 index? tmp
						][
							append sound-groups id
							out/writeUI8 length? sound-groups
						]
					][
						out/writeUI8 0 ;no soundGroup
					]
					;not using all values from envelope, just first one
					out/writeUI16 soundData/2/2 ;leftVolume
					out/writeUI16 soundData/2/3 ;rightVolume
					
				)
				| pos: 1 skip (
					ask reform ["UNKNOWN COMMAND near:" mold copy/part pos 20 "..."] 
				)
			]
		]
	]
]# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = map(X, along, function(x) FUN(x), subsets)
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=length, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll) {
    abind::asub(X, ll, drop=F)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    else if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along])) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)==dim(X)[along])
        lnames = base::dimnames(X)[[along]]
    else
        lnames = usubsets
    setNames(lapply(idxList, function(ll) subset(X, ll)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=mean) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,]

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: better to remove NAs when creating index?
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
# Array programming utility functions
# Some tools to handle R^n matrices and perform operations on them
library(methods) # abind bug: relies on methods::Quote, which is not loaded from Rscript
library(dplyr)
.b = import('base')
import('./util', attach=T)
.check = import('./checks')

#' Stacks arrays while respecting names in each dimension
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Which axis arrays should be stacked on (default: new axis)
#' @param fill       Value for unknown values (default: \code{NA})
#' @param like       Array whose form/names the return value should take
#' @return           A stacked array, either n or n+1 dimensional
stack = function(arrayList, along=length(dim(arrayList[[1]]))+1, fill=NA, like=NA) {
#TODO: make sure there is no NA in the combined names
#TODO:? would be faster if just call abind() when there is nothing to sort
    if (!is.list(arrayList))
        stop(paste("arrayList needs to be a list, not a", class(arrayList)))
    arrayList = arrayList[!is.null(arrayList)]
    if (length(arrayList) == 0)
        stop("No element remaining after removing NULL entries")
    if (length(arrayList) == 1)
        return(arrayList[[1]])

    # union set of dimnames along a list of arrays (TODO: better way?)
    arrayList = lapply(arrayList, function(x) as.array(x))

    newAxis = FALSE
    if (along > length(dim(arrayList[[1]])))
        newAxis = TRUE

    if (identical(like, NA)) {
        dn = lapply(arrayList, dimnames)
        dimNames = lapply(1:length(dn[[1]]), function(j) 
            unique(c(unlist(sapply(1:length(dn), function(i) 
                dn[[i]][[j]]
            ))))
        )
        ndim = sapply(1:length(dimNames), function(i)
            if (!is.null(dimNames[[i]]))
                length(dimNames[[i]]) 
            else
                max(sapply(arrayList, function(j) dim(j)[i]))
        )

        # if creating new axis, amend ndim and dimNames
        if (newAxis) {
            dimNames = c(dimNames, list(names(arrayList)))
            ndim = c(ndim, length(arrayList))
        }

        result = array(fill, dim=ndim, dimnames=dimNames)
    } else {
        result = array(fill, dim=dim(like), dimnames=base::dimnames(like))
    }

    # create stack with fill=fill, replace each slice with matched values of arrayList
    for (i in dimnames(arrayList, null.as.integer=T)) {
        dm = dimnames(arrayList[[i]], null.as.integer=T)
        if (any(is.na(unlist(dm))))
            stop("NA found in array names, do not know how to stack those")
        if (newAxis)
            dm[[along]] = i
        result = do.call("[<-", c(list(result), dm, list(arrayList[[i]])))
    }
    result
}

#' Binds arrays together disregarding names
#'
#' @param arrayList  A list of n-dimensional arrays
#' @param along      Along which axis to bind them together
#' @return           A joined array
bind = function(arrayList, along=length(dim(arrayList[[1]]))+1) {
#TODO: check names?, call bind when no stacking needed automatically?
#TODO: data.table::rbindlist?
    do.call(function(f) abind::abind(f, along=along), arrayList)
}

#' Function to discard subsets of an array (NA or drop)
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply \code{FUN}
#' @param FUN      Function to apply, needs to return \code{TRUE} (keep) or \code{FALSE}
#' @param subsets  Subsets that should be used when applying \code{FUN}
#' @param na.rm    Whether to omit columns and rows with \code{NA}s
#' @return         An array where filtered values are \code{NA} or dropped
filter = function(X, along, FUN, subsets=rep(1,dim(X)[along]), na.rm=F) {
    .check$all(X, along, subsets)

    X = as.array(X)
    # apply the function to get a subset mask
    mask = map(X, along, function(x) FUN(x), subsets)
    if (mode(mask) != 'logical' || dim(mask)[1] != length(unique(subsets)))
        stop("FUN needs to return a single logical value")

#    for (mcol in seq_along(ncol(mask)))
        for (msub in rownames(mask))
            if (!mask[msub])
                X[subsets==msub] = NA #FIXME: work for matrices as well

    if (na.rm)
        .b$omit$na.col(na.omit(X))
    else
        X
}

#' A wrapper around reshape2::acast using a more intuitive formula syntax
#'
#' @param X              A data frame
#' @param formula        A formula: value [+ value2 ..] ~ axis1 [+ axis2 + axis n ..]
#' @param fill           Value to fill array with if undefined
#' @param fun.aggregate  Function to aggregate multiple values for the same position
#' @param ...            Additional arguments passed to reshape2::acast
#' @return               A structured array
construct = function(X, formula, fill=NULL, fun.aggregate=length, ...) {
    if (!is.data.frame(X) && is.list(X)) #TODO: check, names at level 1 = '.id'
        X = plyr::ldply(X, data.frame)
#TODO: convert nested list to data.frame first as well?
    dep_str = as.character(formula)[[2]]
    indep_str = as.character(formula)[[3]]
    vars = all.vars(formula)

    dep_vars = vars[sapply(vars, function(v) grepl(v, dep_str))]
    indep_vars = vars[sapply(vars, function(v) grepl(v, indep_str))]

    form = as.formula(paste(indep_vars, collapse = "~"))
    res = sapply(dep_vars, function(v) reshape2::acast(
        as.data.frame(X), formula=form, value.var=v,
        fill=fill, fun.aggregate=fun.aggregate, ...
    ), simplify=FALSE)
    if (length(res) == 1) #TODO: drop_list in base?
        res[[1]]
    else
        res
}

#' Subsets an array using a list with indices or names
#'
#' @param X   The array to subset
#' @param ll  The list to use for subsetting
#' @return    The subset of the array
subset = function(X, ll) {
    abind::asub(X, ll, drop=F)
}

#' Apply function that preserves order of dimensions
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
map_simple = function(X, along, FUN) { #TODO: replace this by alply?
    if (is.vector(X) || length(dim(X))==1)
        return(FUN(X))

    preserveAxes = c(1:length(dim(X)))[-along]
    Y = apply(X, preserveAxes, FUN)
    if (is.vector(Y)) {
        if (along == 1) {
            newdim = c(1, length(Y))
            newdimnames = list(NULL, names(Y))
        } else {
            newdim = c(length(Y), 1)
            newdimnames = list(names(Y), NULL)
        }
        array(Y, dim=newdim, dimnames=newdimnames)
    } else {
        aperm(Y, c(along, preserveAxes))
    }
}

#' Maps a function along an array preserving its structure
#'
#' @param X        An n-dimensional array
#' @param along    Along which axis to apply the function
#' @param FUN      A function that maps a vector to the same length or a scalar
#' @param subsets  Whether to apply \code{FUN} along the whole axis or subsets thereof
#' @return         An array where \code{FUN} has been applied
map = function(X, along, FUN, subsets=rep(1,dim(X)[along])) {
    .check$all(X, along, subsets, x.to.array=TRUE)

    subsets = as.factor(subsets)
    lsubsets = as.character(unique(subsets)) # levels(subsets) changes order!
    nsubsets = length(lsubsets)

    # create a list to index X with each subset
    subsetIndices = rep(list(rep(list(TRUE), length(dim(X)))), nsubsets)
    for (i in 1:nsubsets)
        subsetIndices[[i]][[along]] = (subsets==lsubsets[i])

    # for each subset, call mymap
    resultList = lapply(subsetIndices, function(f)
        map_simple(subset(X, f), along, FUN))
#    resultList = lapply(subsetIndices, function(x) alply(subset(X, f), along, FUN)) FIXME:

    # assemble results together
    Y = do.call(function(...) abind::abind(..., along=along), resultList)
    if (dim(Y)[along] == dim(X)[along])
        base::dimnames(Y)[[along]] = base::dimnames(X)[[along]]
    else if (dim(Y)[along] == nsubsets)
        base::dimnames(Y)[[along]] = lsubsets
    drop(Y)
}

#' Splits and array along a given axis, either totally or only subsets
#'
#' @param X        An array that should be split
#' @param along    Along which axis to split
#' @param subsets  Whether to split each element or keep some together
#' @return         A list of arrays that combined make up the input array
split = function(X, along, subsets=c(1:dim(X)[along])) {
    if (!is.array(X) && !is.vector(X))
        stop("X needs to be either vector, array or matrix")
    .check$all(X, along, subsets, x.to.array=TRUE)

    usubsets = unique(subsets)
    lus = length(usubsets)
    idxList = rep(list(rep(list(TRUE), length(dim(X)))), lus)

    for (i in 1:lus)
        idxList[[i]][[along]] = subsets==usubsets[i]

    if (length(usubsets)==dim(X)[along])
        lnames = base::dimnames(X)[[along]]
    else
        lnames = usubsets
    setNames(lapply(idxList, function(ll) subset(X, ll)), lnames)
}

#' Intersects all passed arrays along a give dimension, and modifies them in place
#'
#' @param ...    Arrays that should be intersected
#' @param along  The axis along which to intersect
intersect = function(..., along=1) { #TODO: accept along=c(1,2,1,1...)
    l. = list(...)
    varnames = match.call(expand.dots=FALSE)$...
    namesalong = lapply(l., function(f) dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(l.)) {
        dims = as.list(rep(T, length(dim(l.[[i]]))))
        dims[[along]] = common
        assign(as.character(varnames[[i]]),
               value = abind::asub(l.[[i]], dims),
               envir = parent.frame())
    }
}

#' Intersects a list of arrays, orders them the same, and returns the new list
#'
#' @param x      A list of arrays
#' @param along  The axis along which to intersect
#' @return       A list of intersected arrays
intersect_list = function(x, along=1) {
    re = list()
    namesalong = lapply(x, function(f) base::dimnames(as.array(f))[[along]])
    common = do.call(.b$intersect, namesalong)
    for (i in seq_along(x)) {
        dims = as.list(rep(T, length(dim(x[[i]]))))
        dims[[along]] = common
        re[[names(x)[i]]] = abind::asub(x[[i]], dims)
    }
    re
}

#' Converts a list of character vectors to a logical matrix
#'
#' @param x  A list of character vectors
#' @return   A logical occurrence matrix
mask = function(x) {
    if (is.factor(x))
        x = as.character(x)

    vectorList = lapply(x, function(xi) setNames(rep(T, length(xi)), xi))
    t(stack(vectorList, fill=F))
}

#' Summarize a matrix analogous to a grouped df in dplyr
#'
#' @param x      A matrix
#' @param from   Names that match the dimension `along`
#' @param to     Names that this dimension should be summarized to
#' @param along  Along which axis to summarize
#' @param FUN    Which function to apply, default is `mean`
#' @return       A summarized matrix as defined by `from`, `to`
summarize = function(x, to, from=rownames(x), along=1, FUN=mean) {
    if (!is.matrix(x))
        stop('currently only matrices supported')
    if (along!=1)
        stop('currently only rows supported')

    if (length(from) != length(to))
        stop("arguments from and to need to be of the same length")

    index = data.frame(from=from, to=to)
    # remove multi-mappings
    index = .b$omit$dups(index)
    index = index[!.b$duplicated(index[,1], all=T),]

    # subset x to where 'from' available
    x = x[dimnames(x)[[along]] %in% index$from,] #TODO: 2nd stop limit

    # subset object to where 'to' is available
    names_idx = match(dimnames(x)[[along]], index$from)
    newnames = index$to[names_idx]
    x = x[!is.na(newnames),] #TODO: split/map should throw an error if NA in subsets
    newnames = newnames[!is.na(newnames)]

    # aggregate the rest using fun
    split(x, along=along, subsets=newnames) %>%
        lapply(function(x) map(x, along, FUN)) %>%
        do.call(rbind, .)
}
#Load Packages

library(XML)
library(tidyr)
library(stringr)
library(magrittr)
library(plyr)
library(dplyr)
library(RWeka)

#Remove non-words from the raw icc texts
get_real_words <- function(word) {
  word[!stringr::str_detect(word, "[^a-z ]")]
}

#' Remove unreasonable n-grams containing characters other than letters and spaces
#' @param ngrams A list of n-grams
#' @return Returns a list of filtered n-grams
filter_unreasonable_ngrams <- function(ngrams) {
  require(stringr)
  ngrams[!str_detect(ngrams, "[^a-z ]")]
}

#load OCR'd ICC Deceisions data into R
icc_dir <- "text"
files <- dir(icc_dir, "*.txt")
raw <- file.path(icc_dir, files) %>%
  lapply(., scan, "character", sep = "\n")
names(raw) <- files
icc_texts <- lapply(raw, paste, collapse = " ") %>%
  lapply(., tolower) %>%
  lapply(., WordTokenizer) %>%
  lapply(., get_real_words) %>%
  lapply(., paste, collapse = " ")

#Create an N-gram maker with Rweka's function
#ngrammify <- function(data, n) { 
 # NGramTokenizer(data, Weka_control(min = n, max = n))
#}

#Turn text list into N-grams, in this case 5-grams
#icc_grams <- lapply(icc_texts, ngrammify, 5)
#every_grams <- icc_grams %>% unlist() %>% unique()

icc.df <- ldply(icc_texts)
decisions <- rename(icc.df, c(".id" = "id",
                            "V1" = "text"))


#Run the filter_unreasonable_ngrams function
#fix_grams <- filter_unreasonable_ngrams(icc_grams)
#head(fix_grams)

#Save the data
write.csv(icc.df, file = "out/icc_texts.csv")
        